diff --git a/.env b/.env index f83f8ea702..00d48ed6a2 100644 --- a/.env +++ b/.env @@ -14,6 +14,7 @@ UI_PORT=3000 AUTH_SECRET="N/c6mnaS5+SWq81+819OrzQZlmx1Vxtp/orjttJSmw8=" # Google Tag Manager ID NEXT_PUBLIC_GOOGLE_TAG_MANAGER_ID="" + #### Code Review Configuration #### # Enable Claude Code standards validation on pre-push hook # Set to 'true' to validate changes against AGENTS.md standards via Claude Code @@ -107,6 +108,8 @@ DJANGO_THROTTLE_TOKEN_OBTAIN=50/minute # Sentry settings SENTRY_ENVIRONMENT=local SENTRY_RELEASE=local +NEXT_PUBLIC_SENTRY_ENVIRONMENT=${SENTRY_ENVIRONMENT} + #### Prowler release version #### NEXT_PUBLIC_PROWLER_RELEASE_VERSION=v5.12.2 @@ -137,4 +140,3 @@ LANGCHAIN_PROJECT="" RSS_FEED_SOURCES='[{"id":"prowler-releases","name":"Prowler Releases","type":"github_releases","url":"https://github.com/prowler-cloud/prowler/releases.atom","enabled":true}]' # Example with multiple sources (no trailing comma after last item): # RSS_FEED_SOURCES='[{"id":"prowler-releases","name":"Prowler Releases","type":"github_releases","url":"https://github.com/prowler-cloud/prowler/releases.atom","enabled":true},{"id":"prowler-blog","name":"Prowler Blog","type":"blog","url":"https://prowler.com/blog/rss","enabled":false}]' - diff --git a/.github/workflows/api-container-build-push.yml b/.github/workflows/api-container-build-push.yml index 354c147a0b..3b3b4a4222 100644 --- a/.github/workflows/api-container-build-push.yml +++ b/.github/workflows/api-container-build-push.yml @@ -44,7 +44,16 @@ jobs: container-build-push: needs: setup - runs-on: ubuntu-latest + runs-on: ${{ matrix.runner }} + strategy: + matrix: + include: + - platform: linux/amd64 + runner: ubuntu-latest + arch: amd64 + - platform: linux/arm64 + runner: ubuntu-24.04-arm + arch: arm64 timeout-minutes: 30 permissions: contents: read @@ -63,17 +72,17 @@ jobs: - name: Set up Docker Buildx uses: docker/setup-buildx-action@e468171a9de216ec08956ac3ada2f0791b6bd435 # v3.11.1 - - name: Build and push API container (latest) - if: github.event_name == 'push' + - name: Build and push API container for ${{ matrix.arch }} + if: github.event_name == 'push' || github.event_name == 'release' uses: docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0 with: context: ${{ env.WORKING_DIRECTORY }} push: true + platforms: ${{ matrix.platform }} tags: | - ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ env.LATEST_TAG }} - ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ needs.setup.outputs.short-sha }} - cache-from: type=gha - cache-to: type=gha,mode=max + ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ needs.setup.outputs.short-sha }}-${{ matrix.arch }} + cache-from: type=gha,scope=${{ matrix.arch }} + cache-to: type=gha,mode=max,scope=${{ matrix.arch }} - name: Notify container push started if: github.event_name == 'release' @@ -89,19 +98,6 @@ jobs: slack-bot-token: ${{ secrets.SLACK_BOT_TOKEN }} payload-file-path: "./.github/scripts/slack-messages/container-release-started.json" - - name: Build and push API container (release) - if: github.event_name == 'release' - id: container-push - uses: docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0 - with: - context: ${{ env.WORKING_DIRECTORY }} - push: true - tags: | - ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ env.RELEASE_TAG }} - ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ env.STABLE_TAG }} - cache-from: type=gha - cache-to: type=gha,mode=max - - name: Notify container push completed if: github.event_name == 'release' && always() uses: ./.github/actions/slack-notification @@ -117,6 +113,52 @@ jobs: payload-file-path: "./.github/scripts/slack-messages/container-release-completed.json" step-outcome: ${{ steps.container-push.outcome }} + # Create and push multi-architecture manifest + create-manifest: + needs: [setup, container-build-push] + if: github.event_name == 'push' || github.event_name == 'release' + runs-on: ubuntu-latest + + steps: + - name: Login to DockerHub + uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@e468171a9de216ec08956ac3ada2f0791b6bd435 # v3.11.1 + + - name: Create and push manifests for push event + if: github.event_name == 'push' + run: | + docker buildx imagetools create \ + -t ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ env.LATEST_TAG }} \ + -t ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ needs.setup.outputs.short-sha }} \ + ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ needs.setup.outputs.short-sha }}-amd64 \ + ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ needs.setup.outputs.short-sha }}-arm64 + + - name: Create and push manifests for release event + if: github.event_name == 'release' + run: | + docker buildx imagetools create \ + -t ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ env.RELEASE_TAG }} \ + -t ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ env.STABLE_TAG }} \ + ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ needs.setup.outputs.short-sha }}-amd64 \ + ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ needs.setup.outputs.short-sha }}-arm64 + + - name: Install regctl + if: always() + uses: regclient/actions/regctl-installer@f61d18f46c86af724a9c804cb9ff2a6fec741c7c # main + + - name: Cleanup intermediate architecture tags + if: always() + run: | + echo "Cleaning up intermediate tags..." + regctl tag delete "${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ needs.setup.outputs.short-sha }}-amd64" || true + regctl tag delete "${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ needs.setup.outputs.short-sha }}-arm64" || true + echo "Cleanup completed" + trigger-deployment: if: github.event_name == 'push' needs: [setup, container-build-push] diff --git a/.github/workflows/comment-label-update.yml b/.github/workflows/comment-label-update.yml new file mode 100644 index 0000000000..9bddd6a9dd --- /dev/null +++ b/.github/workflows/comment-label-update.yml @@ -0,0 +1,39 @@ +name: 'Tools: Comment Label Update' + +on: + issue_comment: + types: + - 'created' + +concurrency: + group: ${{ github.workflow }}-${{ github.event.issue.number }} + cancel-in-progress: false + +jobs: + update-labels: + if: contains(github.event.issue.labels.*.name, 'status/awaiting-response') + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + issues: write + pull-requests: write + + steps: + - name: Remove 'status/awaiting-response' label + env: + GH_TOKEN: ${{ github.token }} + ISSUE_NUMBER: ${{ github.event.issue.number }} + run: | + echo "Removing 'status/awaiting-response' label from #$ISSUE_NUMBER" + gh api /repos/${{ github.repository }}/issues/$ISSUE_NUMBER/labels/status%2Fawaiting-response \ + -X DELETE + + - name: Add 'status/waiting-for-revision' label + env: + GH_TOKEN: ${{ github.token }} + ISSUE_NUMBER: ${{ github.event.issue.number }} + run: | + echo "Adding 'status/waiting-for-revision' label to #$ISSUE_NUMBER" + gh api /repos/${{ github.repository }}/issues/$ISSUE_NUMBER/labels \ + -X POST \ + -f labels[]='status/waiting-for-revision' diff --git a/.github/workflows/labeler-community.yml b/.github/workflows/labeler-community.yml deleted file mode 100644 index c6115b4d30..0000000000 --- a/.github/workflows/labeler-community.yml +++ /dev/null @@ -1,45 +0,0 @@ -name: Community PR labelling - -on: - # We need "write" permissions on the PR to be able to add a label. - pull_request_target: # We need this to have labelling permissions. There are no user inputs here, so we should be fine. - types: - - opened - -permissions: {} - -jobs: - label-if-community: - name: Add 'community' label if the PR is from a community contributor - if: github.repository == 'prowler-cloud/prowler' - runs-on: ubuntu-latest - permissions: - pull-requests: write - - steps: - - name: Check if author is org member - id: check_membership - env: - GH_TOKEN: ${{ github.token }} - AUTHOR: ${{ github.event.pull_request.user.login }} - ORG: ${{ github.repository_owner }} - run: | - echo "Checking if $AUTHOR is a member of $ORG" - if gh api --method GET "orgs/$ORG/members/$AUTHOR" >/dev/null 2>&1; then - echo "is_member=true" >> $GITHUB_OUTPUT - echo "$AUTHOR is an organization member" - else - echo "is_member=false" >> $GITHUB_OUTPUT - echo "$AUTHOR is not an organization member" - fi - - - name: Add community label - if: steps.check_membership.outputs.is_member == 'false' - env: - PR_NUMBER: ${{ github.event.pull_request.number }} - GH_TOKEN: ${{ github.token }} - run: | - echo "Adding 'community' label to PR #$PR_NUMBER" - gh api /repos/${{ github.repository }}/issues/${{ github.event.number }}/labels \ - -X POST \ - -f labels[]='community' diff --git a/.github/workflows/labeler.yml b/.github/workflows/labeler.yml index fad94177f7..85ccd34cc2 100644 --- a/.github/workflows/labeler.yml +++ b/.github/workflows/labeler.yml @@ -27,3 +27,66 @@ jobs: uses: actions/labeler@634933edcd8ababfe52f92936142cc22ac488b1b # v6.0.1 with: sync-labels: true + + label-community: + name: Add 'community' label if the PR is from a community contributor + needs: labeler + if: github.repository == 'prowler-cloud/prowler' && github.event.action == 'opened' + runs-on: ubuntu-latest + permissions: + pull-requests: write + + steps: + - name: Check if author is org member + id: check_membership + env: + AUTHOR: ${{ github.event.pull_request.user.login }} + run: | + # Hardcoded list of prowler-cloud organization members + # This list includes members who have set their organization membership as private + ORG_MEMBERS=( + "AdriiiPRodri" + "Alan-TheGentleman" + "alejandrobailo" + "amitsharm" + "andoniaf" + "cesararroba" + "Chan9390" + "danibarranqueroo" + "HugoPBrito" + "jfagoagas" + "josemazo" + "lydiavilchez" + "mmuller88" + "MrCloudSec" + "pedrooot" + "prowler-bot" + "puchy22" + "rakan-pro" + "RosaRivasProwler" + "StylusFrost" + "toniblyx" + "vicferpoy" + ) + + echo "Checking if $AUTHOR is a member of prowler-cloud organization" + + # Check if author is in the org members list + if printf '%s\n' "${ORG_MEMBERS[@]}" | grep -q "^${AUTHOR}$"; then + echo "is_member=true" >> $GITHUB_OUTPUT + echo "$AUTHOR is an organization member" + else + echo "is_member=false" >> $GITHUB_OUTPUT + echo "$AUTHOR is not an organization member" + fi + + - name: Add community label + if: steps.check_membership.outputs.is_member == 'false' + env: + PR_NUMBER: ${{ github.event.pull_request.number }} + GH_TOKEN: ${{ github.token }} + run: | + echo "Adding 'community' label to PR #$PR_NUMBER" + gh api /repos/${{ github.repository }}/issues/${{ github.event.number }}/labels \ + -X POST \ + -f labels[]='community' diff --git a/.github/workflows/mcp-container-build-push.yml b/.github/workflows/mcp-container-build-push.yml index 8fb2dfcba6..27bc3e84e0 100644 --- a/.github/workflows/mcp-container-build-push.yml +++ b/.github/workflows/mcp-container-build-push.yml @@ -43,7 +43,16 @@ jobs: container-build-push: needs: setup - runs-on: ubuntu-latest + runs-on: ${{ matrix.runner }} + strategy: + matrix: + include: + - platform: linux/amd64 + runner: ubuntu-latest + arch: amd64 + - platform: linux/arm64 + runner: ubuntu-24.04-arm + arch: arm64 timeout-minutes: 30 permissions: contents: read @@ -61,24 +70,25 @@ jobs: - name: Set up Docker Buildx uses: docker/setup-buildx-action@e468171a9de216ec08956ac3ada2f0791b6bd435 # v3.11.1 - - name: Build and push MCP container (latest) - if: github.event_name == 'push' + - name: Build and push MCP container for ${{ matrix.arch }} + if: github.event_name == 'push' || github.event_name == 'release' uses: docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0 with: context: ${{ env.WORKING_DIRECTORY }} push: true + platforms: ${{ matrix.platform }} tags: | - ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ env.LATEST_TAG }} - ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ needs.setup.outputs.short-sha }} + ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ needs.setup.outputs.short-sha }}-${{ matrix.arch }} labels: | org.opencontainers.image.title=Prowler MCP Server org.opencontainers.image.description=Model Context Protocol server for Prowler org.opencontainers.image.vendor=ProwlerPro, Inc. org.opencontainers.image.source=https://github.com/${{ github.repository }} org.opencontainers.image.revision=${{ github.sha }} - org.opencontainers.image.created=${{ github.event.head_commit.timestamp }} - cache-from: type=gha - cache-to: type=gha,mode=max + org.opencontainers.image.created=${{ github.event_name == 'release' && github.event.release.published_at || github.event.head_commit.timestamp }} + ${{ github.event_name == 'release' && format('org.opencontainers.image.version={0}', env.RELEASE_TAG) || '' }} + cache-from: type=gha,scope=${{ matrix.arch }} + cache-to: type=gha,mode=max,scope=${{ matrix.arch }} - name: Notify container push started if: github.event_name == 'release' @@ -94,27 +104,6 @@ jobs: slack-bot-token: ${{ secrets.SLACK_BOT_TOKEN }} payload-file-path: "./.github/scripts/slack-messages/container-release-started.json" - - name: Build and push MCP container (release) - if: github.event_name == 'release' - id: container-push - uses: docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0 - with: - context: ${{ env.WORKING_DIRECTORY }} - push: true - tags: | - ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ env.RELEASE_TAG }} - ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ env.STABLE_TAG }} - labels: | - org.opencontainers.image.title=Prowler MCP Server - org.opencontainers.image.description=Model Context Protocol server for Prowler - org.opencontainers.image.vendor=ProwlerPro, Inc. - org.opencontainers.image.version=${{ env.RELEASE_TAG }} - org.opencontainers.image.source=https://github.com/${{ github.repository }} - org.opencontainers.image.revision=${{ github.sha }} - org.opencontainers.image.created=${{ github.event.release.published_at }} - cache-from: type=gha - cache-to: type=gha,mode=max - - name: Notify container push completed if: github.event_name == 'release' && always() uses: ./.github/actions/slack-notification @@ -130,6 +119,52 @@ jobs: payload-file-path: "./.github/scripts/slack-messages/container-release-completed.json" step-outcome: ${{ steps.container-push.outcome }} + # Create and push multi-architecture manifest + create-manifest: + needs: [setup, container-build-push] + if: github.event_name == 'push' || github.event_name == 'release' + runs-on: ubuntu-latest + + steps: + - name: Login to DockerHub + uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@e468171a9de216ec08956ac3ada2f0791b6bd435 # v3.11.1 + + - name: Create and push manifests for push event + if: github.event_name == 'push' + run: | + docker buildx imagetools create \ + -t ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ env.LATEST_TAG }} \ + -t ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ needs.setup.outputs.short-sha }} \ + ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ needs.setup.outputs.short-sha }}-amd64 \ + ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ needs.setup.outputs.short-sha }}-arm64 + + - name: Create and push manifests for release event + if: github.event_name == 'release' + run: | + docker buildx imagetools create \ + -t ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ env.RELEASE_TAG }} \ + -t ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ env.STABLE_TAG }} \ + ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ needs.setup.outputs.short-sha }}-amd64 \ + ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ needs.setup.outputs.short-sha }}-arm64 + + - name: Install regctl + if: always() + uses: regclient/actions/regctl-installer@main + + - name: Cleanup intermediate architecture tags + if: always() + run: | + echo "Cleaning up intermediate tags..." + regctl tag delete "${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ needs.setup.outputs.short-sha }}-amd64" || true + regctl tag delete "${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ needs.setup.outputs.short-sha }}-arm64" || true + echo "Cleanup completed" + trigger-deployment: if: github.event_name == 'push' needs: [setup, container-build-push] diff --git a/.github/workflows/sdk-container-build-push.yml b/.github/workflows/sdk-container-build-push.yml index 1f7343d0cf..72b57ac246 100644 --- a/.github/workflows/sdk-container-build-push.yml +++ b/.github/workflows/sdk-container-build-push.yml @@ -46,7 +46,16 @@ env: jobs: container-build-push: if: github.repository == 'prowler-cloud/prowler' - runs-on: ubuntu-latest + runs-on: ${{ matrix.runner }} + strategy: + matrix: + include: + - platform: linux/amd64 + runner: ubuntu-latest + arch: amd64 + - platform: linux/arm64 + runner: ubuntu-24.04-arm + arch: arm64 timeout-minutes: 45 permissions: contents: read @@ -54,6 +63,8 @@ jobs: outputs: prowler_version: ${{ steps.get-prowler-version.outputs.prowler_version }} prowler_version_major: ${{ steps.get-prowler-version.outputs.prowler_version_major }} + latest_tag: ${{ steps.get-prowler-version.outputs.latest_tag }} + stable_tag: ${{ steps.get-prowler-version.outputs.stable_tag }} env: POETRY_VIRTUALENVS_CREATE: 'false' @@ -88,16 +99,22 @@ jobs: 3) echo "LATEST_TAG=v3-latest" >> "${GITHUB_ENV}" echo "STABLE_TAG=v3-stable" >> "${GITHUB_ENV}" + echo "latest_tag=v3-latest" >> "${GITHUB_OUTPUT}" + echo "stable_tag=v3-stable" >> "${GITHUB_OUTPUT}" echo "✓ Prowler v3 detected - tags: v3-latest, v3-stable" ;; 4) echo "LATEST_TAG=v4-latest" >> "${GITHUB_ENV}" echo "STABLE_TAG=v4-stable" >> "${GITHUB_ENV}" + echo "latest_tag=v4-latest" >> "${GITHUB_OUTPUT}" + echo "stable_tag=v4-stable" >> "${GITHUB_OUTPUT}" echo "✓ Prowler v4 detected - tags: v4-latest, v4-stable" ;; 5) echo "LATEST_TAG=latest" >> "${GITHUB_ENV}" echo "STABLE_TAG=stable" >> "${GITHUB_ENV}" + echo "latest_tag=latest" >> "${GITHUB_OUTPUT}" + echo "stable_tag=stable" >> "${GITHUB_OUTPUT}" echo "✓ Prowler v5 detected - tags: latest, stable" ;; *) @@ -124,19 +141,18 @@ jobs: - name: Set up Docker Buildx uses: docker/setup-buildx-action@e468171a9de216ec08956ac3ada2f0791b6bd435 # v3.11.1 - - name: Build and push SDK container (latest) - if: github.event_name == 'push' + - name: Build and push SDK container for ${{ matrix.arch }} + if: github.event_name == 'push' || github.event_name == 'release' uses: docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0 with: context: . file: ${{ env.DOCKERFILE_PATH }} push: true + platforms: ${{ matrix.platform }} tags: | - ${{ secrets.DOCKER_HUB_REPOSITORY }}/${{ env.IMAGE_NAME }}:${{ env.LATEST_TAG }} - ${{ secrets.PUBLIC_ECR_REPOSITORY }}/${{ env.IMAGE_NAME }}:${{ env.LATEST_TAG }} - ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ env.LATEST_TAG }} - cache-from: type=gha - cache-to: type=gha,mode=max + ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ env.LATEST_TAG }}-${{ matrix.arch }} + cache-from: type=gha,scope=${{ matrix.arch }} + cache-to: type=gha,mode=max,scope=${{ matrix.arch }} - name: Notify container push started if: github.event_name == 'release' @@ -151,25 +167,7 @@ jobs: with: slack-bot-token: ${{ secrets.SLACK_BOT_TOKEN }} payload-file-path: "./.github/scripts/slack-messages/container-release-started.json" - - - name: Build and push SDK container (release) - if: github.event_name == 'release' - id: container-push - uses: docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0 - with: - context: . - file: ${{ env.DOCKERFILE_PATH }} - push: true - tags: | - ${{ secrets.DOCKER_HUB_REPOSITORY }}/${{ env.IMAGE_NAME }}:${{ env.PROWLER_VERSION }} - ${{ secrets.DOCKER_HUB_REPOSITORY }}/${{ env.IMAGE_NAME }}:${{ env.STABLE_TAG }} - ${{ secrets.PUBLIC_ECR_REPOSITORY }}/${{ env.IMAGE_NAME }}:${{ env.PROWLER_VERSION }} - ${{ secrets.PUBLIC_ECR_REPOSITORY }}/${{ env.IMAGE_NAME }}:${{ env.STABLE_TAG }} - ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ env.PROWLER_VERSION }} - ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ env.STABLE_TAG }} - cache-from: type=gha - cache-to: type=gha,mode=max - + - name: Notify container push completed if: github.event_name == 'release' && always() uses: ./.github/actions/slack-notification @@ -185,6 +183,57 @@ jobs: payload-file-path: "./.github/scripts/slack-messages/container-release-completed.json" step-outcome: ${{ steps.container-push.outcome }} + # Create and push multi-architecture manifest + create-manifest: + needs: [container-build-push] + if: github.event_name == 'push' || github.event_name == 'release' + runs-on: ubuntu-latest + + steps: + - name: Login to DockerHub + uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@e468171a9de216ec08956ac3ada2f0791b6bd435 # v3.11.1 + + - name: Create and push manifests for push event + if: github.event_name == 'push' + run: | + docker buildx imagetools create \ + -t ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ needs.container-build-push.outputs.latest_tag }} \ + -t ${{ secrets.DOCKER_HUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ needs.container-build-push.outputs.latest_tag }} \ + -t ${{ secrets.PUBLIC_ECR_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ needs.container-build-push.outputs.latest_tag }} \ + ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ needs.container-build-push.outputs.latest_tag }}-amd64 \ + ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ needs.container-build-push.outputs.latest_tag }}-arm64 + + - name: Create and push manifests for release event + if: github.event_name == 'release' + run: | + docker buildx imagetools create \ + -t ${{ secrets.DOCKER_HUB_REPOSITORY }}/${{ env.IMAGE_NAME }}:${{ needs.container-build-push.outputs.prowler_version }} \ + -t ${{ secrets.DOCKER_HUB_REPOSITORY }}/${{ env.IMAGE_NAME }}:${{ needs.container-build-push.outputs.stable_tag }} \ + -t ${{ secrets.PUBLIC_ECR_REPOSITORY }}/${{ env.IMAGE_NAME }}:${{ needs.container-build-push.outputs.prowler_version }} \ + -t ${{ secrets.PUBLIC_ECR_REPOSITORY }}/${{ env.IMAGE_NAME }}:${{ needs.container-build-push.outputs.stable_tag }} \ + -t ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ needs.container-build-push.outputs.prowler_version }} \ + -t ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ needs.container-build-push.outputs.stable_tag }} \ + ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ needs.container-build-push.outputs.latest_tag }}-amd64 \ + ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ needs.container-build-push.outputs.latest_tag }}-arm64 + + - name: Install regctl + if: always() + uses: regclient/actions/regctl-installer@main + + - name: Cleanup intermediate architecture tags + if: always() + run: | + echo "Cleaning up intermediate tags..." + regctl tag delete "${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ needs.container-build-push.outputs.latest_tag }}-amd64" || true + regctl tag delete "${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ needs.container-build-push.outputs.latest_tag }}-arm64" || true + echo "Cleanup completed" + dispatch-v3-deployment: if: needs.container-build-push.outputs.prowler_version_major == '3' needs: container-build-push diff --git a/.github/workflows/ui-container-build-push.yml b/.github/workflows/ui-container-build-push.yml index 6641903953..34cddc900d 100644 --- a/.github/workflows/ui-container-build-push.yml +++ b/.github/workflows/ui-container-build-push.yml @@ -46,7 +46,16 @@ jobs: container-build-push: needs: setup - runs-on: ubuntu-latest + runs-on: ${{ matrix.runner }} + strategy: + matrix: + include: + - platform: linux/amd64 + runner: ubuntu-latest + arch: amd64 + - platform: linux/arm64 + runner: ubuntu-24.04-arm + arch: arm64 timeout-minutes: 30 permissions: contents: read @@ -65,7 +74,7 @@ jobs: - name: Set up Docker Buildx uses: docker/setup-buildx-action@e468171a9de216ec08956ac3ada2f0791b6bd435 # v3.11.1 - - name: Build and push UI container (latest) + - name: Build and push UI container for ${{ matrix.arch }} if: github.event_name == 'push' uses: docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0 with: @@ -74,8 +83,22 @@ jobs: NEXT_PUBLIC_PROWLER_RELEASE_VERSION=${{ needs.setup.outputs.short-sha }} NEXT_PUBLIC_API_BASE_URL=${{ env.NEXT_PUBLIC_API_BASE_URL }} push: true + platforms: ${{ matrix.platform }} + tags: | + ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ needs.setup.outputs.short-sha }}-${{ matrix.arch }} + cache-from: type=gha,scope=${{ matrix.arch }} + cache-to: type=gha,mode=max,scope=${{ matrix.arch }} + + - name: Build and push UI container for ${{ matrix.arch }} + if: github.event_name == 'push' || github.event_name == 'release' + uses: docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0 + with: + context: ${{ env.WORKING_DIRECTORY }} + build-args: | + NEXT_PUBLIC_PROWLER_RELEASE_VERSION=${{ github.event_name == 'release' && format('v{0}', env.RELEASE_TAG) || needs.setup.outputs.short_sha }} + NEXT_PUBLIC_API_BASE_URL=${{ env.NEXT_PUBLIC_API_BASE_URL }} + push: true tags: | - ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ env.LATEST_TAG }} ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ needs.setup.outputs.short-sha }} cache-from: type=gha cache-to: type=gha,mode=max @@ -94,22 +117,6 @@ jobs: slack-bot-token: ${{ secrets.SLACK_BOT_TOKEN }} payload-file-path: "./.github/scripts/slack-messages/container-release-started.json" - - name: Build and push UI container (release) - if: github.event_name == 'release' - id: container-push - uses: docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0 - with: - context: ${{ env.WORKING_DIRECTORY }} - build-args: | - NEXT_PUBLIC_PROWLER_RELEASE_VERSION=v${{ env.RELEASE_TAG }} - NEXT_PUBLIC_API_BASE_URL=${{ env.NEXT_PUBLIC_API_BASE_URL }} - push: true - tags: | - ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ env.RELEASE_TAG }} - ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ env.STABLE_TAG }} - cache-from: type=gha - cache-to: type=gha,mode=max - - name: Notify container push completed if: github.event_name == 'release' && always() uses: ./.github/actions/slack-notification @@ -125,6 +132,52 @@ jobs: payload-file-path: "./.github/scripts/slack-messages/container-release-completed.json" step-outcome: ${{ steps.container-push.outcome }} + # Create and push multi-architecture manifest + create-manifest: + needs: [setup, container-build-push] + if: github.event_name == 'push' || github.event_name == 'release' + runs-on: ubuntu-latest + + steps: + - name: Login to DockerHub + uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@e468171a9de216ec08956ac3ada2f0791b6bd435 # v3.11.1 + + - name: Create and push manifests for push event + if: github.event_name == 'push' + run: | + docker buildx imagetools create \ + -t ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ env.LATEST_TAG }} \ + -t ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ needs.setup.outputs.short-sha }} \ + ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ needs.setup.outputs.short-sha }}-amd64 \ + ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ needs.setup.outputs.short-sha }}-arm64 + + - name: Create and push manifests for release event + if: github.event_name == 'release' + run: | + docker buildx imagetools create \ + -t ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ env.RELEASE_TAG }} \ + -t ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ env.STABLE_TAG }} \ + ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ needs.setup.outputs.short-sha }}-amd64 \ + ${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ needs.setup.outputs.short-sha }}-arm64 + + - name: Install regctl + if: always() + uses: regclient/actions/regctl-installer@main + + - name: Cleanup intermediate architecture tags + if: always() + run: | + echo "Cleaning up intermediate tags..." + regctl tag delete "${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ needs.setup.outputs.short-sha }}-amd64" || true + regctl tag delete "${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ needs.setup.outputs.short-sha }}-arm64" || true + echo "Cleanup completed" + trigger-deployment: if: github.event_name == 'push' needs: [setup, container-build-push] diff --git a/.gitignore b/.gitignore index 7c1333c856..7792a031b4 100644 --- a/.gitignore +++ b/.gitignore @@ -45,21 +45,86 @@ pytest_*.xml .coverage htmlcov/ -# VSCode files +# VSCode files and settings .vscode/ +*.code-workspace +.vscode-test/ -# Cursor files +# VSCode extension settings and workspaces +.history/ +.ionide/ + +# MCP Server Settings (various locations) +**/cline_mcp_settings.json +**/mcp_settings.json +**/mcp-config.json +**/mcpServers.json +.mcp/ + +# AI Coding Assistants - Cursor .cursorignore .cursor/ +.cursorrules -# RooCode files +# AI Coding Assistants - RooCode .roo/ .rooignore .roomodes -# Cline files +# AI Coding Assistants - Cline (formerly Claude Dev) .cline/ .clineignore +.clinerules + +# AI Coding Assistants - Continue +.continue/ +continue.json +.continuerc +.continuerc.json + +# AI Coding Assistants - GitHub Copilot +.copilot/ +.github/copilot/ + +# AI Coding Assistants - Amazon Q Developer (formerly CodeWhisperer) +.aws/ +.codewhisperer/ +.amazonq/ +.aws-toolkit/ + +# AI Coding Assistants - Tabnine +.tabnine/ +tabnine_config.json + +# AI Coding Assistants - Kiro +.kiro/ +.kiroignore +kiro.config.json + +# AI Coding Assistants - Aider +.aider/ +.aider.chat.history.md +.aider.input.history +.aider.tags.cache.v3/ + +# AI Coding Assistants - Windsurf +.windsurf/ +.windsurfignore + +# AI Coding Assistants - Replit Agent +.replit +.replitignore + +# AI Coding Assistants - Supermaven +.supermaven/ + +# AI Coding Assistants - Sourcegraph Cody +.cody/ + +# AI Coding Assistants - General +.ai/ +.aiconfig +ai-config.json # Terraform .terraform* diff --git a/Dockerfile b/Dockerfile index 5884bda9f3..f71c53e008 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,6 +4,10 @@ LABEL maintainer="https://github.com/prowler-cloud/prowler" LABEL org.opencontainers.image.source="https://github.com/prowler-cloud/prowler" ARG POWERSHELL_VERSION=7.5.0 +ENV POWERSHELL_VERSION=${POWERSHELL_VERSION} + +ARG TRIVY_VERSION=0.66.0 +ENV TRIVY_VERSION=${TRIVY_VERSION} # hadolint ignore=DL3008 RUN apt-get update && apt-get install -y --no-install-recommends \ @@ -25,6 +29,24 @@ RUN ARCH=$(uname -m) && \ ln -s /opt/microsoft/powershell/7/pwsh /usr/bin/pwsh && \ rm /tmp/powershell.tar.gz +# Install Trivy for IaC scanning +RUN ARCH=$(uname -m) && \ + if [ "$ARCH" = "x86_64" ]; then \ + TRIVY_ARCH="Linux-64bit" ; \ + elif [ "$ARCH" = "aarch64" ]; then \ + TRIVY_ARCH="Linux-ARM64" ; \ + else \ + echo "Unsupported architecture for Trivy: $ARCH" && exit 1 ; \ + fi && \ + wget --progress=dot:giga "https://github.com/aquasecurity/trivy/releases/download/v${TRIVY_VERSION}/trivy_${TRIVY_VERSION}_${TRIVY_ARCH}.tar.gz" -O /tmp/trivy.tar.gz && \ + tar zxf /tmp/trivy.tar.gz -C /tmp && \ + mv /tmp/trivy /usr/local/bin/trivy && \ + chmod +x /usr/local/bin/trivy && \ + rm /tmp/trivy.tar.gz && \ + # Create trivy cache directory with proper permissions + mkdir -p /tmp/.cache/trivy && \ + chmod 777 /tmp/.cache/trivy + # Add prowler user RUN addgroup --gid 1000 prowler && \ adduser --uid 1000 --gid 1000 --disabled-password --gecos "" prowler diff --git a/README.md b/README.md index 83af8dcfb7..25cc8f6abe 100644 --- a/README.md +++ b/README.md @@ -82,9 +82,9 @@ prowler dashboard | Provider | Checks | Services | [Compliance Frameworks](https://docs.prowler.com/projects/prowler-open-source/en/latest/tutorials/compliance/) | [Categories](https://docs.prowler.com/projects/prowler-open-source/en/latest/tutorials/misc/#categories) | Support | Interface | |---|---|---|---|---|---|---| -| AWS | 576 | 82 | 38 | 10 | Official | UI, API, CLI | -| GCP | 79 | 13 | 12 | 3 | Official | UI, API, CLI | -| Azure | 162 | 19 | 12 | 4 | Official | UI, API, CLI | +| AWS | 576 | 82 | 39 | 10 | Official | UI, API, CLI | +| GCP | 79 | 13 | 13 | 3 | Official | UI, API, CLI | +| Azure | 162 | 19 | 13 | 4 | Official | UI, API, CLI | | Kubernetes | 83 | 7 | 5 | 7 | Official | UI, API, CLI | | GitHub | 17 | 2 | 1 | 0 | Official | Stable | UI, API, CLI | | M365 | 70 | 7 | 3 | 2 | Official | UI, API, CLI | diff --git a/api/CHANGELOG.md b/api/CHANGELOG.md index 5e4720bcf9..ce5d8eed74 100644 --- a/api/CHANGELOG.md +++ b/api/CHANGELOG.md @@ -14,10 +14,29 @@ All notable changes to the **Prowler API** are documented in this file. - Support muting findings based on simple rules with custom reason [(#9051)](https://github.com/prowler-cloud/prowler/pull/9051) - Support C5 compliance framework for the GCP provider [(#9097)](https://github.com/prowler-cloud/prowler/pull/9097) - Support for Amazon Bedrock and OpenAI compatible providers in Lighthouse AI [(#8957)](https://github.com/prowler-cloud/prowler/pull/8957) +- Tenant-wide ThreatScore overview aggregation and snapshot persistence with backfill support [(#9148)](https://github.com/prowler-cloud/prowler/pull/9148) +- Added `metadata`, `details`, and `partition` attributes to `/resources` endpoint & `details`, and `partition` to `/findings` endpoint [(#9098)](https://github.com/prowler-cloud/prowler/pull/9098) - Support for MongoDB Atlas provider [(#9167)](https://github.com/prowler-cloud/prowler/pull/9167) +- Enhanced compliance overview endpoint with provider filtering and latest scan aggregation [(#9244)](https://github.com/prowler-cloud/prowler/pull/9244) + +### Changed +- Optimized database write queries for scan related tasks [(#9190)](https://github.com/prowler-cloud/prowler/pull/9190) +- Date filters are now optional for `GET /api/v1/overviews/services` endpoint; returns latest scan data by default [(#9248)](https://github.com/prowler-cloud/prowler/pull/9248) + +### Fixed +- Scans no longer fail when findings have UIDs exceeding 300 characters; such findings are now skipped with detailed logging [(#9246)](https://github.com/prowler-cloud/prowler/pull/9246) + +### Security +- Django updated to the latest 5.1 security release, 5.1.14, due to problems with potential [SQL injection](https://github.com/prowler-cloud/prowler/security/dependabot/113) and [denial-of-service vulnerability](https://github.com/prowler-cloud/prowler/security/dependabot/114) [(#9176)](https://github.com/prowler-cloud/prowler/pull/9176) --- +## [1.14.2] (Prowler 5.13.2) + +### Fixed +- Update unique constraint for `Provider` model to exclude soft-deleted entries, resolving duplicate errors when re-deleting providers [(#9054)](https://github.com/prowler-cloud/prowler/pull/9054) +- Remove compliance generation for providers without compliance frameworks [(#9208)](https://github.com/prowler-cloud/prowler/pull/9208) + ## [1.14.1] (Prowler 5.13.1) ### Fixed diff --git a/api/poetry.lock b/api/poetry.lock index 40313d9fa5..332d4d9f73 100644 --- a/api/poetry.lock +++ b/api/poetry.lock @@ -1,4 +1,4 @@ -# This file is automatically @generated by Poetry 2.2.0 and should not be changed by hand. +# This file is automatically @generated by Poetry 2.1.4 and should not be changed by hand. [[package]] name = "about-time" @@ -1671,14 +1671,14 @@ with-social = ["django-allauth[socialaccount] (>=64.0.0)"] [[package]] name = "django" -version = "5.1.13" +version = "5.1.14" description = "A high-level Python web framework that encourages rapid development and clean, pragmatic design." optional = false python-versions = ">=3.10" groups = ["main", "dev"] files = [ - {file = "django-5.1.13-py3-none-any.whl", hash = "sha256:06f257f79dc4c17f3f9e23b106a4c5ed1335abecbe731e83c598c941d14fbeed"}, - {file = "django-5.1.13.tar.gz", hash = "sha256:543ff21679f15e80edfc01fe7ea35f8291b6d4ea589433882913626a7c1cf929"}, + {file = "django-5.1.14-py3-none-any.whl", hash = "sha256:2a4b9c20404fd1bf50aaaa5542a19d860594cba1354f688f642feb271b91df27"}, + {file = "django-5.1.14.tar.gz", hash = "sha256:b98409fb31fdd6e8c3a6ba2eef3415cc5c0020057b43b21ba7af6eff5f014831"}, ] [package.dependencies] @@ -6786,4 +6786,4 @@ type = ["pytest-mypy"] [metadata] lock-version = "2.1" python-versions = ">=3.11,<3.13" -content-hash = "3c9164d668d37d6373eb5200bbe768232ead934d9312b9c68046b1df922789f3" +content-hash = "943e2cd6b87229704550d4e140b36509fb9f58896ebb5834b9fbabe28a9ee92f" diff --git a/api/pyproject.toml b/api/pyproject.toml index 22ae14e6a1..ffc8413489 100644 --- a/api/pyproject.toml +++ b/api/pyproject.toml @@ -7,7 +7,7 @@ authors = [{name = "Prowler Engineering", email = "engineering@prowler.com"}] dependencies = [ "celery[pytest] (>=5.4.0,<6.0.0)", "dj-rest-auth[with_social,jwt] (==7.0.1)", - "django (==5.1.13)", + "django (==5.1.14)", "django-allauth[saml] (>=65.8.0,<66.0.0)", "django-celery-beat (>=2.7.0,<3.0.0)", "django-celery-results (>=2.5.1,<3.0.0)", diff --git a/api/src/backend/api/compliance.py b/api/src/backend/api/compliance.py index 291cbb757e..da39fc23bb 100644 --- a/api/src/backend/api/compliance.py +++ b/api/src/backend/api/compliance.py @@ -144,6 +144,7 @@ def generate_scan_compliance( Returns: None: This function modifies the compliance_overview in place. """ + for compliance_id in PROWLER_CHECKS[provider_type][check_id]: for requirement in compliance_overview[compliance_id]["requirements"].values(): if check_id in requirement["checks"]: diff --git a/api/src/backend/api/filters.py b/api/src/backend/api/filters.py index a3cb389351..de1397b117 100644 --- a/api/src/backend/api/filters.py +++ b/api/src/backend/api/filters.py @@ -47,6 +47,7 @@ from api.models import ( StatusChoices, Task, TenantAPIKey, + ThreatScoreSnapshot, User, ) from api.rls import Tenant @@ -760,6 +761,14 @@ class RoleFilter(FilterSet): class ComplianceOverviewFilter(FilterSet): inserted_at = DateFilter(field_name="inserted_at", lookup_expr="date") scan_id = UUIDFilter(field_name="scan_id") + provider_id = UUIDFilter(field_name="scan__provider__id", lookup_expr="exact") + provider_id__in = UUIDInFilter(field_name="scan__provider__id", lookup_expr="in") + provider_type = ChoiceFilter( + field_name="scan__provider__provider", choices=Provider.ProviderChoices.choices + ) + provider_type__in = ChoiceInFilter( + field_name="scan__provider__provider", choices=Provider.ProviderChoices.choices + ) region = CharFilter(field_name="region") class Meta: @@ -859,26 +868,6 @@ class ScanSummarySeverityFilter(ScanSummaryFilter): } -class ServiceOverviewFilter(ScanSummaryFilter): - def is_valid(self): - # Check if at least one of the inserted_at filters is present - inserted_at_filters = [ - self.data.get("inserted_at"), - self.data.get("inserted_at__gte"), - self.data.get("inserted_at__lte"), - ] - if not any(inserted_at_filters): - raise ValidationError( - { - "inserted_at": [ - "At least one of filter[inserted_at], filter[inserted_at__gte], or " - "filter[inserted_at__lte] is required." - ] - } - ) - return super().is_valid() - - class IntegrationFilter(FilterSet): inserted_at = DateFilter(field_name="inserted_at", lookup_expr="date") integration_type = ChoiceFilter(choices=Integration.IntegrationChoices.choices) @@ -998,3 +987,36 @@ class MuteRuleFilter(FilterSet): "inserted_at": ["gte", "lte"], "updated_at": ["gte", "lte"], } + + +class ThreatScoreSnapshotFilter(FilterSet): + """ + Filter for ThreatScore snapshots. + Allows filtering by scan, provider, compliance_id, and date ranges. + """ + + inserted_at = DateFilter(field_name="inserted_at", lookup_expr="date") + scan_id = UUIDFilter(field_name="scan__id", lookup_expr="exact") + scan_id__in = UUIDInFilter(field_name="scan__id", lookup_expr="in") + provider_id = UUIDFilter(field_name="provider__id", lookup_expr="exact") + provider_id__in = UUIDInFilter(field_name="provider__id", lookup_expr="in") + provider_type = ChoiceFilter( + field_name="provider__provider", choices=Provider.ProviderChoices.choices + ) + provider_type__in = ChoiceInFilter( + field_name="provider__provider", + choices=Provider.ProviderChoices.choices, + lookup_expr="in", + ) + compliance_id = CharFilter(field_name="compliance_id", lookup_expr="exact") + compliance_id__in = CharInFilter(field_name="compliance_id", lookup_expr="in") + + class Meta: + model = ThreatScoreSnapshot + fields = { + "scan": ["exact", "in"], + "provider": ["exact", "in"], + "compliance_id": ["exact", "in"], + "inserted_at": ["date", "gte", "lte"], + "overall_score": ["exact", "gte", "lte"], + } diff --git a/api/src/backend/api/migrations/0056_remove_provider_unique_provider_uids_and_more.py b/api/src/backend/api/migrations/0056_remove_provider_unique_provider_uids_and_more.py new file mode 100644 index 0000000000..14cbc4fa47 --- /dev/null +++ b/api/src/backend/api/migrations/0056_remove_provider_unique_provider_uids_and_more.py @@ -0,0 +1,24 @@ +# Generated by Django 5.1.13 on 2025-11-06 09:20 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("api", "0055_mongodbatlas_provider"), + ] + + operations = [ + migrations.RemoveConstraint( + model_name="provider", + name="unique_provider_uids", + ), + migrations.AddConstraint( + model_name="provider", + constraint=models.UniqueConstraint( + condition=models.Q(("is_deleted", False)), + fields=("tenant_id", "provider", "uid"), + name="unique_provider_uids", + ), + ), + ] diff --git a/api/src/backend/api/migrations/0057_threatscoresnapshot.py b/api/src/backend/api/migrations/0057_threatscoresnapshot.py new file mode 100644 index 0000000000..ee3530a5b6 --- /dev/null +++ b/api/src/backend/api/migrations/0057_threatscoresnapshot.py @@ -0,0 +1,170 @@ +# Generated by Django 5.1.13 on 2025-10-31 09:04 + +import uuid + +import django.db.models.deletion +from django.db import migrations, models + +import api.rls + + +class Migration(migrations.Migration): + dependencies = [ + ("api", "0056_remove_provider_unique_provider_uids_and_more"), + ] + + operations = [ + migrations.CreateModel( + name="ThreatScoreSnapshot", + fields=[ + ( + "id", + models.UUIDField( + default=uuid.uuid4, + editable=False, + primary_key=True, + serialize=False, + ), + ), + ("inserted_at", models.DateTimeField(auto_now_add=True)), + ( + "compliance_id", + models.CharField( + help_text="Compliance framework ID (e.g., 'prowler_threatscore_aws')", + max_length=100, + ), + ), + ( + "overall_score", + models.DecimalField( + decimal_places=2, + help_text="Overall ThreatScore percentage (0-100)", + max_digits=5, + ), + ), + ( + "score_delta", + models.DecimalField( + blank=True, + decimal_places=2, + help_text="Score change compared to previous snapshot (positive = improvement)", + max_digits=5, + null=True, + ), + ), + ( + "section_scores", + models.JSONField( + blank=True, + default=dict, + help_text="ThreatScore breakdown by section", + ), + ), + ( + "critical_requirements", + models.JSONField( + blank=True, + default=list, + help_text="List of critical failed requirements (risk >= 4)", + ), + ), + ( + "total_requirements", + models.IntegerField( + default=0, help_text="Total number of requirements evaluated" + ), + ), + ( + "passed_requirements", + models.IntegerField( + default=0, help_text="Number of requirements with PASS status" + ), + ), + ( + "failed_requirements", + models.IntegerField( + default=0, help_text="Number of requirements with FAIL status" + ), + ), + ( + "manual_requirements", + models.IntegerField( + default=0, help_text="Number of requirements with MANUAL status" + ), + ), + ( + "total_findings", + models.IntegerField( + default=0, + help_text="Total number of findings across all requirements", + ), + ), + ( + "passed_findings", + models.IntegerField( + default=0, help_text="Number of findings with PASS status" + ), + ), + ( + "failed_findings", + models.IntegerField( + default=0, help_text="Number of findings with FAIL status" + ), + ), + ( + "provider", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + related_name="threatscore_snapshots", + related_query_name="threatscore_snapshot", + to="api.provider", + ), + ), + ( + "scan", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + related_name="threatscore_snapshots", + related_query_name="threatscore_snapshot", + to="api.scan", + ), + ), + ( + "tenant", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, to="api.tenant" + ), + ), + ], + options={ + "db_table": "threatscore_snapshots", + "abstract": False, + }, + ), + migrations.AddIndex( + model_name="threatscoresnapshot", + index=models.Index( + fields=["tenant_id", "scan_id"], name="threatscore_snap_t_scan_idx" + ), + ), + migrations.AddIndex( + model_name="threatscoresnapshot", + index=models.Index( + fields=["tenant_id", "provider_id"], name="threatscore_snap_t_prov_idx" + ), + ), + migrations.AddIndex( + model_name="threatscoresnapshot", + index=models.Index( + fields=["tenant_id", "inserted_at"], name="threatscore_snap_t_time_idx" + ), + ), + migrations.AddConstraint( + model_name="threatscoresnapshot", + constraint=api.rls.RowLevelSecurityConstraint( + "tenant_id", + name="rls_on_threatscoresnapshot", + statements=["SELECT", "INSERT", "UPDATE", "DELETE"], + ), + ), + ] diff --git a/api/src/backend/api/migrations/0058_drop_redundant_compliance_requirement_indexes.py b/api/src/backend/api/migrations/0058_drop_redundant_compliance_requirement_indexes.py new file mode 100644 index 0000000000..1d2ee35f4d --- /dev/null +++ b/api/src/backend/api/migrations/0058_drop_redundant_compliance_requirement_indexes.py @@ -0,0 +1,25 @@ +from django.contrib.postgres.operations import RemoveIndexConcurrently +from django.db import migrations + + +class Migration(migrations.Migration): + atomic = False + + dependencies = [ + ("api", "0057_threatscoresnapshot"), + ] + + operations = [ + RemoveIndexConcurrently( + model_name="compliancerequirementoverview", + name="cro_tenant_scan_idx", + ), + RemoveIndexConcurrently( + model_name="compliancerequirementoverview", + name="cro_scan_comp_idx", + ), + RemoveIndexConcurrently( + model_name="compliancerequirementoverview", + name="cro_scan_comp_req_idx", + ), + ] diff --git a/api/src/backend/api/migrations/0059_compliance_overview_summary.py b/api/src/backend/api/migrations/0059_compliance_overview_summary.py new file mode 100644 index 0000000000..d2d57a34ae --- /dev/null +++ b/api/src/backend/api/migrations/0059_compliance_overview_summary.py @@ -0,0 +1,75 @@ +# Generated by Django 5.1.13 on 2025-10-30 15:23 + +import uuid + +import django.db.models.deletion +from django.db import migrations, models + +import api.rls + + +class Migration(migrations.Migration): + dependencies = [ + ("api", "0058_drop_redundant_compliance_requirement_indexes"), + ] + + operations = [ + migrations.CreateModel( + name="ComplianceOverviewSummary", + fields=[ + ( + "id", + models.UUIDField( + default=uuid.uuid4, + editable=False, + primary_key=True, + serialize=False, + ), + ), + ("inserted_at", models.DateTimeField(auto_now_add=True)), + ("compliance_id", models.TextField()), + ("requirements_passed", models.IntegerField(default=0)), + ("requirements_failed", models.IntegerField(default=0)), + ("requirements_manual", models.IntegerField(default=0)), + ("total_requirements", models.IntegerField(default=0)), + ( + "scan", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + related_name="compliance_summaries", + related_query_name="compliance_summary", + to="api.scan", + ), + ), + ( + "tenant", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, to="api.tenant" + ), + ), + ], + options={ + "db_table": "compliance_overview_summaries", + "abstract": False, + "indexes": [ + models.Index( + fields=["tenant_id", "scan_id"], name="cos_tenant_scan_idx" + ) + ], + "constraints": [ + models.UniqueConstraint( + fields=("tenant_id", "scan_id", "compliance_id"), + name="unique_compliance_summary_per_scan", + ) + ], + }, + ), + migrations.AddConstraint( + model_name="complianceoverviewsummary", + constraint=api.rls.RowLevelSecurityConstraint( + "tenant_id", + name="rls_on_complianceoverviewsummary", + statements=["SELECT", "INSERT", "UPDATE", "DELETE"], + ), + ), + ] diff --git a/api/src/backend/api/models.py b/api/src/backend/api/models.py index 7ca9594d5e..1191350ac6 100644 --- a/api/src/backend/api/models.py +++ b/api/src/backend/api/models.py @@ -425,7 +425,8 @@ class Provider(RowLevelSecurityProtectedModel): constraints = [ models.UniqueConstraint( - fields=("tenant_id", "provider", "uid", "is_deleted"), + fields=("tenant_id", "provider", "uid"), + condition=Q(is_deleted=False), name="unique_provider_uids", ), RowLevelSecurityConstraint( @@ -1370,35 +1371,70 @@ class ComplianceRequirementOverview(RowLevelSecurityProtectedModel): ), ] indexes = [ - models.Index(fields=["tenant_id", "scan_id"], name="cro_tenant_scan_idx"), - models.Index( - fields=["tenant_id", "scan_id", "compliance_id"], - name="cro_scan_comp_idx", - ), models.Index( fields=["tenant_id", "scan_id", "compliance_id", "region"], name="cro_scan_comp_reg_idx", ), - models.Index( - fields=["tenant_id", "scan_id", "compliance_id", "requirement_id"], - name="cro_scan_comp_req_idx", - ), - models.Index( - fields=[ - "tenant_id", - "scan_id", - "compliance_id", - "requirement_id", - "region", - ], - name="cro_scan_comp_req_reg_idx", - ), ] class JSONAPIMeta: resource_name = "compliance-requirements-overviews" +class ComplianceOverviewSummary(RowLevelSecurityProtectedModel): + """ + Pre-aggregated compliance overview aggregated across ALL regions. + One row per (scan_id, compliance_id) combination. + + This table optimizes the common case where users view overall compliance + without filtering by region. For region-specific views, the detailed + ComplianceRequirementOverview table is used instead. + """ + + id = models.UUIDField(primary_key=True, default=uuid4, editable=False) + inserted_at = models.DateTimeField(auto_now_add=True, editable=False) + + scan = models.ForeignKey( + Scan, + on_delete=models.CASCADE, + related_name="compliance_summaries", + related_query_name="compliance_summary", + ) + + compliance_id = models.TextField(blank=False) + + # Pre-aggregated scores (computed across ALL regions) + requirements_passed = models.IntegerField(default=0) + requirements_failed = models.IntegerField(default=0) + requirements_manual = models.IntegerField(default=0) + total_requirements = models.IntegerField(default=0) + + class Meta(RowLevelSecurityProtectedModel.Meta): + db_table = "compliance_overview_summaries" + + constraints = [ + models.UniqueConstraint( + fields=("tenant_id", "scan_id", "compliance_id"), + name="unique_compliance_summary_per_scan", + ), + RowLevelSecurityConstraint( + field="tenant_id", + name="rls_on_%(class)s", + statements=["SELECT", "INSERT", "DELETE"], + ), + ] + + indexes = [ + models.Index( + fields=["tenant_id", "scan_id"], + name="cos_tenant_scan_idx", + ), + ] + + class JSONAPIMeta: + resource_name = "compliance-overview-summaries" + + class ScanSummary(RowLevelSecurityProtectedModel): objects = ActiveProviderManager() all_objects = models.Manager() @@ -2238,3 +2274,134 @@ class LighthouseProviderModels(RowLevelSecurityProtectedModel): class JSONAPIMeta: resource_name = "lighthouse-models" + + +class ThreatScoreSnapshot(RowLevelSecurityProtectedModel): + """ + Stores historical ThreatScore metrics for a given scan. + Snapshots are created automatically after each ThreatScore report generation. + """ + + id = models.UUIDField(primary_key=True, default=uuid4, editable=False) + inserted_at = models.DateTimeField(auto_now_add=True, editable=False) + + scan = models.ForeignKey( + Scan, + on_delete=models.CASCADE, + related_name="threatscore_snapshots", + related_query_name="threatscore_snapshot", + ) + + provider = models.ForeignKey( + Provider, + on_delete=models.CASCADE, + related_name="threatscore_snapshots", + related_query_name="threatscore_snapshot", + ) + + compliance_id = models.CharField( + max_length=100, + blank=False, + null=False, + help_text="Compliance framework ID (e.g., 'prowler_threatscore_aws')", + ) + + # Overall ThreatScore metrics + overall_score = models.DecimalField( + max_digits=5, + decimal_places=2, + help_text="Overall ThreatScore percentage (0-100)", + ) + + # Score improvement/degradation compared to previous snapshot + score_delta = models.DecimalField( + max_digits=5, + decimal_places=2, + null=True, + blank=True, + help_text="Score change compared to previous snapshot (positive = improvement)", + ) + + # Section breakdown stored as JSON + # Format: {"1. IAM": 85.5, "2. Attack Surface": 92.3, ...} + section_scores = models.JSONField( + default=dict, + blank=True, + help_text="ThreatScore breakdown by section", + ) + + # Critical requirements metadata stored as JSON + # Format: [{"requirement_id": "...", "risk_level": 5, "weight": 150, ...}, ...] + critical_requirements = models.JSONField( + default=list, + blank=True, + help_text="List of critical failed requirements (risk >= 4)", + ) + + # Summary statistics + total_requirements = models.IntegerField( + default=0, + help_text="Total number of requirements evaluated", + ) + + passed_requirements = models.IntegerField( + default=0, + help_text="Number of requirements with PASS status", + ) + + failed_requirements = models.IntegerField( + default=0, + help_text="Number of requirements with FAIL status", + ) + + manual_requirements = models.IntegerField( + default=0, + help_text="Number of requirements with MANUAL status", + ) + + total_findings = models.IntegerField( + default=0, + help_text="Total number of findings across all requirements", + ) + + passed_findings = models.IntegerField( + default=0, + help_text="Number of findings with PASS status", + ) + + failed_findings = models.IntegerField( + default=0, + help_text="Number of findings with FAIL status", + ) + + def __str__(self): + return f"ThreatScore {self.overall_score}% for scan {self.scan_id} ({self.inserted_at})" + + class Meta(RowLevelSecurityProtectedModel.Meta): + db_table = "threatscore_snapshots" + + constraints = [ + RowLevelSecurityConstraint( + field="tenant_id", + name="rls_on_%(class)s", + statements=["SELECT", "INSERT", "UPDATE", "DELETE"], + ), + ] + + indexes = [ + models.Index( + fields=["tenant_id", "scan_id"], + name="threatscore_snap_t_scan_idx", + ), + models.Index( + fields=["tenant_id", "provider_id"], + name="threatscore_snap_t_prov_idx", + ), + models.Index( + fields=["tenant_id", "inserted_at"], + name="threatscore_snap_t_time_idx", + ), + ] + + class JSONAPIMeta: + resource_name = "threatscore-snapshots" diff --git a/api/src/backend/api/specs/v1.yaml b/api/src/backend/api/specs/v1.yaml index e44dba0084..6227d2500e 100644 --- a/api/src/backend/api/specs/v1.yaml +++ b/api/src/backend/api/specs/v1.yaml @@ -283,8 +283,11 @@ paths: /api/v1/compliance-overviews: get: operationId: compliance_overviews_list - description: Retrieve an overview of all the compliance in a given scan. - summary: List compliance overviews for a scan + description: Retrieve an overview of all compliance frameworks. If scan_id is + provided, returns compliance data for that specific scan. If scan_id is omitted, + returns compliance data aggregated from the latest completed scan of each + provider. + summary: List compliance overviews parameters: - in: query name: fields[compliance-overviews] @@ -343,6 +346,32 @@ paths: schema: type: string format: date-time + - in: query + name: filter[provider_id] + schema: + type: string + format: uuid + description: Filter by specific provider ID. + - in: query + name: filter[provider_id__in] + schema: + type: array + items: + type: string + format: uuid + description: Filter by multiple provider IDs (comma-separated). + - in: query + name: filter[provider_type] + schema: + type: string + description: Filter by provider type (e.g., aws, azure, gcp). + - in: query + name: filter[provider_type__in] + schema: + type: array + items: + type: string + description: Filter by multiple provider types (comma-separated). - in: query name: filter[region] schema: @@ -365,8 +394,8 @@ paths: schema: type: string format: uuid - description: Related scan ID. - required: true + description: Optional scan ID. If provided, returns compliance for that scan. + If omitted, returns compliance for the latest completed scan per provider. - name: filter[search] required: false in: query @@ -606,6 +635,77 @@ paths: schema: type: string format: date-time + - in: query + name: filter[provider_id] + schema: + type: string + format: uuid + - in: query + name: filter[provider_id__in] + schema: + type: array + items: + type: string + format: uuid + description: Multiple values may be separated by commas. + explode: false + style: form + - in: query + name: filter[provider_type] + schema: + type: string + x-spec-enum-id: eca8c51e6bd28935 + enum: + - aws + - azure + - gcp + - github + - iac + - kubernetes + - m365 + - mongodbatlas + - oraclecloud + description: |- + * `aws` - AWS + * `azure` - Azure + * `gcp` - GCP + * `kubernetes` - Kubernetes + * `m365` - M365 + * `github` - GitHub + * `mongodbatlas` - MongoDB Atlas + * `iac` - IaC + * `oraclecloud` - Oracle Cloud Infrastructure + - in: query + name: filter[provider_type__in] + schema: + type: array + items: + type: string + x-spec-enum-id: eca8c51e6bd28935 + enum: + - aws + - azure + - gcp + - github + - iac + - kubernetes + - m365 + - mongodbatlas + - oraclecloud + description: |- + Multiple values may be separated by commas. + + * `aws` - AWS + * `azure` - Azure + * `gcp` - GCP + * `kubernetes` - Kubernetes + * `m365` - M365 + * `github` - GitHub + * `mongodbatlas` - MongoDB Atlas + * `iac` - IaC + * `oraclecloud` - Oracle Cloud Infrastructure + explode: false + style: form - in: query name: filter[region] schema: @@ -869,16 +969,16 @@ paths: name: filter[provider_type] schema: type: string - x-spec-enum-id: 7087703783970b51 + x-spec-enum-id: eca8c51e6bd28935 enum: - aws - azure - gcp - github - - mongodbatlas - iac - kubernetes - m365 + - mongodbatlas - oraclecloud description: |- * `aws` - AWS @@ -896,15 +996,16 @@ paths: type: array items: type: string - x-spec-enum-id: 7087703783970b51 + x-spec-enum-id: eca8c51e6bd28935 enum: - aws - azure - gcp - github - - mongodbatlas + - iac - kubernetes - m365 + - mongodbatlas - oraclecloud description: |- Multiple values may be separated by commas. @@ -1407,16 +1508,16 @@ paths: name: filter[provider_type] schema: type: string - x-spec-enum-id: 7087703783970b51 + x-spec-enum-id: eca8c51e6bd28935 enum: - aws - azure - gcp - github - - mongodbatlas - iac - kubernetes - m365 + - mongodbatlas - oraclecloud description: |- * `aws` - AWS @@ -1434,15 +1535,16 @@ paths: type: array items: type: string - x-spec-enum-id: 7087703783970b51 + x-spec-enum-id: eca8c51e6bd28935 enum: - aws - azure - gcp - github - - mongodbatlas + - iac - kubernetes - m365 + - mongodbatlas - oraclecloud description: |- Multiple values may be separated by commas. @@ -1853,16 +1955,16 @@ paths: name: filter[provider_type] schema: type: string - x-spec-enum-id: 7087703783970b51 + x-spec-enum-id: eca8c51e6bd28935 enum: - aws - azure - gcp - github - - mongodbatlas - iac - kubernetes - m365 + - mongodbatlas - oraclecloud description: |- * `aws` - AWS @@ -1880,15 +1982,16 @@ paths: type: array items: type: string - x-spec-enum-id: 7087703783970b51 + x-spec-enum-id: eca8c51e6bd28935 enum: - aws - azure - gcp - github - - mongodbatlas + - iac - kubernetes - m365 + - mongodbatlas - oraclecloud description: |- Multiple values may be separated by commas. @@ -2297,16 +2400,16 @@ paths: name: filter[provider_type] schema: type: string - x-spec-enum-id: 7087703783970b51 + x-spec-enum-id: eca8c51e6bd28935 enum: - aws - azure - gcp - github - - mongodbatlas - iac - kubernetes - m365 + - mongodbatlas - oraclecloud description: |- * `aws` - AWS @@ -2324,15 +2427,16 @@ paths: type: array items: type: string - x-spec-enum-id: 7087703783970b51 + x-spec-enum-id: eca8c51e6bd28935 enum: - aws - azure - gcp - github - - mongodbatlas + - iac - kubernetes - m365 + - mongodbatlas - oraclecloud description: |- Multiple values may be separated by commas. @@ -2729,16 +2833,16 @@ paths: name: filter[provider_type] schema: type: string - x-spec-enum-id: 7087703783970b51 + x-spec-enum-id: eca8c51e6bd28935 enum: - aws - azure - gcp - github - - mongodbatlas - iac - kubernetes - m365 + - mongodbatlas - oraclecloud description: |- * `aws` - AWS @@ -2756,15 +2860,16 @@ paths: type: array items: type: string - x-spec-enum-id: 7087703783970b51 + x-spec-enum-id: eca8c51e6bd28935 enum: - aws - azure - gcp - github - - mongodbatlas + - iac - kubernetes - m365 + - mongodbatlas - oraclecloud description: |- Multiple values may be separated by commas. @@ -4565,16 +4670,16 @@ paths: name: filter[provider_type] schema: type: string - x-spec-enum-id: 7087703783970b51 + x-spec-enum-id: eca8c51e6bd28935 enum: - aws - azure - gcp - github - - mongodbatlas - iac - kubernetes - m365 + - mongodbatlas - oraclecloud description: |- * `aws` - AWS @@ -4592,15 +4697,16 @@ paths: type: array items: type: string - x-spec-enum-id: 7087703783970b51 + x-spec-enum-id: eca8c51e6bd28935 enum: - aws - azure - gcp - github - - mongodbatlas + - iac - kubernetes - m365 + - mongodbatlas - oraclecloud description: |- Multiple values may be separated by commas. @@ -4753,16 +4859,16 @@ paths: name: filter[provider_type] schema: type: string - x-spec-enum-id: 7087703783970b51 + x-spec-enum-id: eca8c51e6bd28935 enum: - aws - azure - gcp - github - - mongodbatlas - iac - kubernetes - m365 + - mongodbatlas - oraclecloud description: |- * `aws` - AWS @@ -4780,15 +4886,16 @@ paths: type: array items: type: string - x-spec-enum-id: 7087703783970b51 + x-spec-enum-id: eca8c51e6bd28935 enum: - aws - azure - gcp - github - - mongodbatlas + - iac - kubernetes - m365 + - mongodbatlas - oraclecloud description: |- Multiple values may be separated by commas. @@ -4949,8 +5056,7 @@ paths: operationId: overviews_services_retrieve description: Retrieve an aggregated summary of findings grouped by service. The response includes the total count of findings for each service, as long - as there are at least one finding for that service. At least one of the `inserted_at` - filters must be provided. + as there are at least one finding for that service. summary: Get findings data by service parameters: - in: query @@ -5007,16 +5113,16 @@ paths: name: filter[provider_type] schema: type: string - x-spec-enum-id: 7087703783970b51 + x-spec-enum-id: eca8c51e6bd28935 enum: - aws - azure - gcp - github - - mongodbatlas - iac - kubernetes - m365 + - mongodbatlas - oraclecloud description: |- * `aws` - AWS @@ -5034,15 +5140,16 @@ paths: type: array items: type: string - x-spec-enum-id: 7087703783970b51 + x-spec-enum-id: eca8c51e6bd28935 enum: - aws - azure - gcp - github - - mongodbatlas + - iac - kubernetes - m365 + - mongodbatlas - oraclecloud description: |- Multiple values may be separated by commas. @@ -5112,6 +5219,90 @@ paths: schema: $ref: '#/components/schemas/OverviewServiceResponse' description: '' + /api/v1/overviews/threatscore: + get: + operationId: overviews_threatscore_retrieve + description: Retrieve ThreatScore metrics. By default, returns the latest snapshot + for each provider. Use snapshot_id to retrieve a specific historical snapshot. + summary: Get ThreatScore snapshots + parameters: + - in: query + name: fields[threatscore-snapshots] + schema: + type: array + items: + type: string + enum: + - id + - inserted_at + - scan + - provider + - compliance_id + - overall_score + - score_delta + - section_scores + - critical_requirements + - total_requirements + - passed_requirements + - failed_requirements + - manual_requirements + - total_findings + - passed_findings + - failed_findings + description: endpoint return only specific fields in the response on a per-type + basis by including a fields[TYPE] query parameter. + explode: false + - in: query + name: include + schema: + type: array + items: + type: string + enum: + - scan + - provider + description: include query parameter to allow the client to customize which + related resources should be returned. + explode: false + - in: query + name: provider_id + schema: + type: string + format: uuid + description: Filter by specific provider ID + - in: query + name: provider_id__in + schema: + type: string + description: Filter by multiple provider IDs (comma-separated UUIDs) + - in: query + name: provider_type + schema: + type: string + description: Filter by provider type (aws, azure, gcp, etc.) + - in: query + name: provider_type__in + schema: + type: string + description: Filter by multiple provider types (comma-separated) + - in: query + name: snapshot_id + schema: + type: string + format: uuid + description: Retrieve a specific snapshot by ID. If not provided, returns + latest snapshots. + tags: + - Overviews + security: + - JWT or API Key: [] + responses: + '200': + content: + application/vnd.api+json: + schema: + $ref: '#/components/schemas/ThreatScoreSnapshotResponse' + description: '' /api/v1/processors: get: operationId: processors_list @@ -5741,16 +5932,16 @@ paths: name: filter[provider] schema: type: string - x-spec-enum-id: 7087703783970b51 + x-spec-enum-id: eca8c51e6bd28935 enum: - aws - azure - gcp - github - - mongodbatlas - iac - kubernetes - m365 + - mongodbatlas - oraclecloud description: |- * `aws` - AWS @@ -5768,15 +5959,16 @@ paths: type: array items: type: string - x-spec-enum-id: 7087703783970b51 + x-spec-enum-id: eca8c51e6bd28935 enum: - aws - azure - gcp - github - - mongodbatlas + - iac - kubernetes - m365 + - mongodbatlas - oraclecloud description: |- Multiple values may be separated by commas. @@ -5788,6 +5980,7 @@ paths: * `m365` - M365 * `github` - GitHub * `mongodbatlas` - MongoDB Atlas + * `iac` - IaC * `oraclecloud` - Oracle Cloud Infrastructure explode: false style: form @@ -5795,14 +5988,16 @@ paths: name: filter[provider_type] schema: type: string - x-spec-enum-id: 7087703783970b51 + x-spec-enum-id: eca8c51e6bd28935 enum: - aws - azure - gcp - github + - iac - kubernetes - m365 + - mongodbatlas - oraclecloud description: |- * `aws` - AWS @@ -5811,6 +6006,8 @@ paths: * `kubernetes` - Kubernetes * `m365` - M365 * `github` - GitHub + * `mongodbatlas` - MongoDB Atlas + * `iac` - IaC * `oraclecloud` - Oracle Cloud Infrastructure - in: query name: filter[provider_type__in] @@ -5818,14 +6015,16 @@ paths: type: array items: type: string - x-spec-enum-id: 7087703783970b51 + x-spec-enum-id: eca8c51e6bd28935 enum: - aws - azure - gcp - github + - iac - kubernetes - m365 + - mongodbatlas - oraclecloud description: |- Multiple values may be separated by commas. @@ -5836,6 +6035,8 @@ paths: * `kubernetes` - Kubernetes * `m365` - M365 * `github` - GitHub + * `mongodbatlas` - MongoDB Atlas + * `iac` - IaC * `oraclecloud` - Oracle Cloud Infrastructure explode: false style: form @@ -6371,6 +6572,9 @@ paths: - findings - failed_findings_count - url + - metadata + - details + - partition - type description: endpoint return only specific fields in the response on a per-type basis by including a fields[TYPE] query parameter. @@ -6434,16 +6638,16 @@ paths: name: filter[provider_type] schema: type: string - x-spec-enum-id: 7087703783970b51 + x-spec-enum-id: eca8c51e6bd28935 enum: - aws - azure - gcp - github - - mongodbatlas - iac - kubernetes - m365 + - mongodbatlas - oraclecloud description: |- * `aws` - AWS @@ -6461,15 +6665,16 @@ paths: type: array items: type: string - x-spec-enum-id: 7087703783970b51 + x-spec-enum-id: eca8c51e6bd28935 enum: - aws - azure - gcp - github - - mongodbatlas + - iac - kubernetes - m365 + - mongodbatlas - oraclecloud description: |- Multiple values may be separated by commas. @@ -6703,6 +6908,9 @@ paths: - findings - failed_findings_count - url + - metadata + - details + - partition - type description: endpoint return only specific fields in the response on a per-type basis by including a fields[TYPE] query parameter. @@ -6762,6 +6970,9 @@ paths: - findings - failed_findings_count - url + - metadata + - details + - partition - type description: endpoint return only specific fields in the response on a per-type basis by including a fields[TYPE] query parameter. @@ -6810,16 +7021,16 @@ paths: name: filter[provider_type] schema: type: string - x-spec-enum-id: 7087703783970b51 + x-spec-enum-id: eca8c51e6bd28935 enum: - aws - azure - gcp - github - - mongodbatlas - iac - kubernetes - m365 + - mongodbatlas - oraclecloud description: |- * `aws` - AWS @@ -6837,15 +7048,16 @@ paths: type: array items: type: string - x-spec-enum-id: 7087703783970b51 + x-spec-enum-id: eca8c51e6bd28935 enum: - aws - azure - gcp - github - - mongodbatlas + - iac - kubernetes - m365 + - mongodbatlas - oraclecloud description: |- Multiple values may be separated by commas. @@ -7087,16 +7299,16 @@ paths: name: filter[provider_type] schema: type: string - x-spec-enum-id: 7087703783970b51 + x-spec-enum-id: eca8c51e6bd28935 enum: - aws - azure - gcp - github - - mongodbatlas - iac - kubernetes - m365 + - mongodbatlas - oraclecloud description: |- * `aws` - AWS @@ -7114,15 +7326,16 @@ paths: type: array items: type: string - x-spec-enum-id: 7087703783970b51 + x-spec-enum-id: eca8c51e6bd28935 enum: - aws - azure - gcp - github - - mongodbatlas + - iac - kubernetes - m365 + - mongodbatlas - oraclecloud description: |- Multiple values may be separated by commas. @@ -7370,16 +7583,16 @@ paths: name: filter[provider_type] schema: type: string - x-spec-enum-id: 7087703783970b51 + x-spec-enum-id: eca8c51e6bd28935 enum: - aws - azure - gcp - github - - mongodbatlas - iac - kubernetes - m365 + - mongodbatlas - oraclecloud description: |- * `aws` - AWS @@ -7397,15 +7610,16 @@ paths: type: array items: type: string - x-spec-enum-id: 7087703783970b51 + x-spec-enum-id: eca8c51e6bd28935 enum: - aws - azure - gcp - github - - mongodbatlas + - iac - kubernetes - m365 + - mongodbatlas - oraclecloud description: |- Multiple values may be separated by commas. @@ -8216,16 +8430,16 @@ paths: name: filter[provider_type] schema: type: string - x-spec-enum-id: 7087703783970b51 + x-spec-enum-id: eca8c51e6bd28935 enum: - aws - azure - gcp - github - - mongodbatlas - iac - kubernetes - m365 + - mongodbatlas - oraclecloud description: |- * `aws` - AWS @@ -8243,15 +8457,16 @@ paths: type: array items: type: string - x-spec-enum-id: 7087703783970b51 + x-spec-enum-id: eca8c51e6bd28935 enum: - aws - azure - gcp - github - - mongodbatlas + - iac - kubernetes - m365 + - mongodbatlas - oraclecloud description: |- Multiple values may be separated by commas. @@ -14285,7 +14500,7 @@ components: type: string description: GitHub OAuth App token for authentication. required: - - oauth_app_token + - oauth_app_token - type: object title: GitHub App Credentials properties: @@ -14298,18 +14513,6 @@ components: required: - github_app_id - github_app_key - - type: object - title: MongoDB Atlas API Key - properties: - atlas_public_key: - type: string - description: MongoDB Atlas API public key. - atlas_private_key: - type: string - description: MongoDB Atlas API private key. - required: - - atlas_public_key - - atlas_private_key - type: object title: IaC Repository Credentials properties: @@ -14354,6 +14557,18 @@ components: - fingerprint - tenancy - region + - type: object + title: MongoDB Atlas API Key + properties: + atlas_public_key: + type: string + description: MongoDB Atlas API public key. + atlas_private_key: + type: string + description: MongoDB Atlas API private key. + required: + - atlas_public_key + - atlas_private_key writeOnly: true required: - secret @@ -15349,6 +15564,7 @@ components: - m365 - github - mongodbatlas + - iac - oraclecloud type: string description: |- @@ -15359,8 +15575,9 @@ components: * `m365` - M365 * `github` - GitHub * `mongodbatlas` - MongoDB Atlas + * `iac` - IaC * `oraclecloud` - Oracle Cloud Infrastructure - x-spec-enum-id: 7087703783970b51 + x-spec-enum-id: eca8c51e6bd28935 uid: type: string title: Unique identifier for the provider, set by the provider @@ -15473,9 +15690,10 @@ components: - m365 - github - mongodbatlas + - iac - oraclecloud type: string - x-spec-enum-id: 7087703783970b51 + x-spec-enum-id: eca8c51e6bd28935 description: |- Type of provider to create. @@ -15486,12 +15704,13 @@ components: * `m365` - M365 * `github` - GitHub * `mongodbatlas` - MongoDB Atlas + * `iac` - IaC * `oraclecloud` - Oracle Cloud Infrastructure uid: type: string title: Unique identifier for the provider, set by the provider description: Unique identifier for the provider, set by the provider, - e.g. AWS account ID, Azure subscription ID, GCP project ID, MongoDB Atlas organization ID, etc. + e.g. AWS account ID, Azure subscription ID, GCP project ID, etc. maxLength: 250 minLength: 3 required: @@ -15531,9 +15750,10 @@ components: - m365 - github - mongodbatlas + - iac - oraclecloud type: string - x-spec-enum-id: 7087703783970b51 + x-spec-enum-id: eca8c51e6bd28935 description: |- Type of provider to create. @@ -15544,13 +15764,14 @@ components: * `m365` - M365 * `github` - GitHub * `mongodbatlas` - MongoDB Atlas + * `iac` - IaC * `oraclecloud` - Oracle Cloud Infrastructure uid: type: string minLength: 3 title: Unique identifier for the provider, set by the provider description: Unique identifier for the provider, set by the provider, - e.g. AWS account ID, Azure subscription ID, GCP project ID, MongoDB Atlas organization ID, etc. + e.g. AWS account ID, Azure subscription ID, GCP project ID, etc. maxLength: 250 required: - uid @@ -16295,6 +16516,18 @@ components: - fingerprint - tenancy - region + - type: object + title: MongoDB Atlas API Key + properties: + atlas_public_key: + type: string + description: MongoDB Atlas API public key. + atlas_private_key: + type: string + description: MongoDB Atlas API private key. + required: + - atlas_public_key + - atlas_private_key writeOnly: true required: - secret_type @@ -16608,6 +16841,18 @@ components: - fingerprint - tenancy - region + - type: object + title: MongoDB Atlas API Key + properties: + atlas_public_key: + type: string + description: MongoDB Atlas API public key. + atlas_private_key: + type: string + description: MongoDB Atlas API private key. + required: + - atlas_public_key + - atlas_private_key writeOnly: true required: - secret_type @@ -16935,6 +17180,18 @@ components: - fingerprint - tenancy - region + - type: object + title: MongoDB Atlas API Key + properties: + atlas_public_key: + type: string + description: MongoDB Atlas API public key. + atlas_private_key: + type: string + description: MongoDB Atlas API private key. + required: + - atlas_public_key + - atlas_private_key writeOnly: true required: - secret @@ -17023,6 +17280,18 @@ components: failed_findings_count: type: integer readOnly: true + metadata: + type: string + readOnly: true + nullable: true + details: + type: string + readOnly: true + nullable: true + partition: + type: string + readOnly: true + nullable: true type: type: string readOnly: true @@ -18495,6 +18764,143 @@ components: $ref: '#/components/schemas/Tenant' required: - data + ThreatScoreSnapshot: + type: object + required: + - type + - id + additionalProperties: false + properties: + type: + type: string + description: The [type](https://jsonapi.org/format/#document-resource-object-identification) + member is used to describe resource objects that share common attributes + and relationships. + enum: + - threatscore-snapshots + id: {} + attributes: + type: object + properties: + id: + type: string + readOnly: true + inserted_at: + type: string + format: date-time + readOnly: true + compliance_id: + type: string + readOnly: true + description: Compliance framework ID (e.g., 'prowler_threatscore_aws') + overall_score: + type: string + format: decimal + pattern: ^-?\d{0,3}(?:\.\d{0,2})?$ + readOnly: true + description: Overall ThreatScore percentage (0-100) + score_delta: + type: string + format: decimal + pattern: ^-?\d{0,3}(?:\.\d{0,2})?$ + readOnly: true + nullable: true + description: Score change compared to previous snapshot (positive = + improvement) + section_scores: + readOnly: true + description: ThreatScore breakdown by section + critical_requirements: + readOnly: true + description: List of critical failed requirements (risk >= 4) + total_requirements: + type: integer + readOnly: true + description: Total number of requirements evaluated + passed_requirements: + type: integer + readOnly: true + description: Number of requirements with PASS status + failed_requirements: + type: integer + readOnly: true + description: Number of requirements with FAIL status + manual_requirements: + type: integer + readOnly: true + description: Number of requirements with MANUAL status + total_findings: + type: integer + readOnly: true + description: Total number of findings across all requirements + passed_findings: + type: integer + readOnly: true + description: Number of findings with PASS status + failed_findings: + type: integer + readOnly: true + description: Number of findings with FAIL status + relationships: + type: object + properties: + scan: + type: object + properties: + data: + type: object + properties: + id: + type: string + format: uuid + type: + type: string + enum: + - scans + title: Resource Type Name + description: The [type](https://jsonapi.org/format/#document-resource-object-identification) + member is used to describe resource objects that share common + attributes and relationships. + required: + - id + - type + required: + - data + description: The identifier of the related object. + title: Resource Identifier + readOnly: true + provider: + type: object + properties: + data: + type: object + properties: + id: + type: string + format: uuid + type: + type: string + enum: + - providers + title: Resource Type Name + description: The [type](https://jsonapi.org/format/#document-resource-object-identification) + member is used to describe resource objects that share common + attributes and relationships. + required: + - id + - type + required: + - data + description: The identifier of the related object. + title: Resource Identifier + readOnly: true + ThreatScoreSnapshotResponse: + type: object + properties: + data: + $ref: '#/components/schemas/ThreatScoreSnapshot' + required: + - data Token: type: object required: diff --git a/api/src/backend/api/tests/test_views.py b/api/src/backend/api/tests/test_views.py index 8822bd9f12..e5eaa2f836 100644 --- a/api/src/backend/api/tests/test_views.py +++ b/api/src/backend/api/tests/test_views.py @@ -4,6 +4,7 @@ import json import os import tempfile from datetime import datetime, timedelta, timezone +from decimal import Decimal from pathlib import Path from types import SimpleNamespace from unittest.mock import ANY, MagicMock, Mock, patch @@ -34,6 +35,8 @@ from rest_framework.response import Response from api.compliance import get_compliance_frameworks from api.db_router import MainRouter from api.models import ( + ComplianceOverviewSummary, + ComplianceRequirementOverview, Finding, Integration, Invitation, @@ -54,8 +57,10 @@ from api.models import ( Scan, ScanSummary, StateChoices, + StatusChoices, Task, TenantAPIKey, + ThreatScoreSnapshot, User, UserRoleRelationship, ) @@ -1171,6 +1176,161 @@ class TestProviderViewSet: assert Provider.objects.get().uid == provider_json_payload["uid"] assert Provider.objects.get().alias == provider_json_payload["alias"] + @pytest.mark.parametrize( + "provider_json_payload", + ( + [ + {"provider": "aws", "uid": "111111111111", "alias": "test"}, + {"provider": "gcp", "uid": "a12322-test54321", "alias": "test"}, + { + "provider": "kubernetes", + "uid": "kubernetes-test-123456789", + "alias": "test", + }, + { + "provider": "kubernetes", + "uid": "arn:aws:eks:us-east-1:111122223333:cluster/test-cluster-long-name-123456789", + "alias": "EKS", + }, + { + "provider": "kubernetes", + "uid": "gke_aaaa-dev_europe-test1_dev-aaaa-test-cluster-long-name-123456789", + "alias": "GKE", + }, + { + "provider": "kubernetes", + "uid": "gke_project/cluster-name", + "alias": "GKE", + }, + { + "provider": "kubernetes", + "uid": "admin@k8s-demo", + "alias": "test", + }, + { + "provider": "azure", + "uid": "8851db6b-42e5-4533-aa9e-30a32d67e875", + "alias": "test", + }, + { + "provider": "m365", + "uid": "TestingPro.onmicrosoft.com", + "alias": "test", + }, + { + "provider": "m365", + "uid": "subdomain.domain.es", + "alias": "test", + }, + { + "provider": "m365", + "uid": "microsoft.net", + "alias": "test", + }, + { + "provider": "m365", + "uid": "subdomain1.subdomain2.subdomain3.subdomain4.domain.net", + "alias": "test", + }, + { + "provider": "github", + "uid": "test-user", + "alias": "test", + }, + { + "provider": "github", + "uid": "test-organization", + "alias": "GitHub Org", + }, + { + "provider": "github", + "uid": "prowler-cloud", + "alias": "Prowler", + }, + { + "provider": "github", + "uid": "microsoft", + "alias": "Microsoft", + }, + { + "provider": "github", + "uid": "a12345678901234567890123456789012345678", + "alias": "Long Username", + }, + ] + ), + ) + @patch("api.v1.views.Task.objects.get") + @patch("api.v1.views.delete_provider_task.delay") + def test_providers_soft_delete( + self, + mock_delete_task, + mock_task_get, + authenticated_client, + provider_json_payload, + tasks_fixture, + ): + # Mock the Celery task response + prowler_task = tasks_fixture[0] + task_mock = Mock() + task_mock.id = prowler_task.id + mock_delete_task.return_value = task_mock + mock_task_get.return_value = prowler_task + + # 1.Create a provider + response = authenticated_client.post( + reverse("provider-list"), data=provider_json_payload, format="json" + ) + assert response.status_code == status.HTTP_201_CREATED + assert Provider.objects.count() == 1 + provider_id = response.json()["data"]["id"] + + # 2. Soft delete the provider using the actual API endpoint + response = authenticated_client.delete( + reverse("provider-detail", kwargs={"pk": provider_id}) + ) + assert response.status_code == status.HTTP_202_ACCEPTED + assert Provider.objects.count() == 0 + assert Provider.all_objects.count() == 1 + + mock_delete_task.assert_called_once_with( + provider_id=str(provider_id), tenant_id=ANY + ) + + # 3. Create a provider with the same UID should succeed (since the old one is soft deleted) + response = authenticated_client.post( + reverse("provider-list"), data=provider_json_payload, format="json" + ) + assert response.status_code == status.HTTP_201_CREATED + assert Provider.objects.count() == 1 + assert Provider.all_objects.count() == 2 + provider_id = response.json()["data"]["id"] + + # 4. Creating another provider with the same UID should fail (duplicate) + response = authenticated_client.post( + reverse("provider-list"), data=provider_json_payload, format="json" + ) + assert response.status_code == status.HTTP_400_BAD_REQUEST + + mock_delete_task.reset_mock() + mock_delete_task.return_value = task_mock + + # 5. Delete the second provider + response = authenticated_client.delete( + reverse("provider-detail", kwargs={"pk": provider_id}) + ) + assert response.status_code == status.HTTP_202_ACCEPTED + assert Provider.objects.count() == 0 + assert Provider.all_objects.count() == 2 + + # 6. Creating a provider with the same UID should succeed again + response = authenticated_client.post( + reverse("provider-list"), data=provider_json_payload, format="json" + ) + assert response.status_code == status.HTTP_201_CREATED + assert Provider.objects.count() == 1 + assert Provider.all_objects.count() == 3 + @pytest.mark.parametrize( "provider_json_payload, error_code, error_pointer", ( @@ -3385,6 +3545,9 @@ class TestResourceViewSet: ) assert response.status_code == status.HTTP_200_OK assert len(response.json()["data"]) == len(resources_fixture) + assert "metadata" in response.json()["data"][0]["attributes"] + assert "details" in response.json()["data"][0]["attributes"] + assert "partition" in response.json()["data"][0]["attributes"] @pytest.mark.parametrize( "include_values, expected_resources", @@ -5657,16 +5820,44 @@ class TestProviderGroupMembershipViewSet: @pytest.mark.django_db class TestComplianceOverviewViewSet: - def test_compliance_overview_list_none(self, authenticated_client): + @pytest.fixture(autouse=True) + def mock_backfill_task(self): + with patch("api.v1.views.backfill_compliance_summaries_task.delay") as mock: + yield mock + + def test_compliance_overview_list_none( + self, + authenticated_client, + tenants_fixture, + providers_fixture, + mock_backfill_task, + ): + tenant = tenants_fixture[0] + provider = providers_fixture[0] + scan = Scan.objects.create( + name="empty-compliance-scan", + provider=provider, + trigger=Scan.TriggerChoices.MANUAL, + state=StateChoices.COMPLETED, + tenant=tenant, + ) + response = authenticated_client.get( reverse("complianceoverview-list"), - {"filter[scan_id]": "8d20ac7d-4cbc-435e-85f4-359be37af821"}, + {"filter[scan_id]": str(scan.id)}, ) assert response.status_code == status.HTTP_200_OK assert len(response.json()["data"]) == 0 + mock_backfill_task.assert_called_once() + _, kwargs = mock_backfill_task.call_args + assert kwargs["scan_id"] == str(scan.id) + assert str(kwargs["tenant_id"]) == str(tenant.id) def test_compliance_overview_list( - self, authenticated_client, compliance_requirements_overviews_fixture + self, + authenticated_client, + compliance_requirements_overviews_fixture, + mock_backfill_task, ): # List compliance overviews with existing data requirement_overview1 = compliance_requirements_overviews_fixture[0] @@ -5696,6 +5887,112 @@ class TestComplianceOverviewViewSet: assert "requirements_failed" in attributes assert "requirements_manual" in attributes assert "total_requirements" in attributes + mock_backfill_task.assert_called_once() + _, kwargs = mock_backfill_task.call_args + assert kwargs["scan_id"] == scan_id + + def test_compliance_overview_list_uses_preaggregated_summaries( + self, + authenticated_client, + tenants_fixture, + providers_fixture, + mock_backfill_task, + ): + tenant = tenants_fixture[0] + provider = providers_fixture[0] + scan = Scan.objects.create( + name="preaggregated-scan", + provider=provider, + trigger=Scan.TriggerChoices.MANUAL, + state=StateChoices.COMPLETED, + tenant=tenant, + ) + + ComplianceRequirementOverview.objects.create( + tenant=tenant, + scan=scan, + compliance_id="cis_1.4_aws", + framework="CIS-1.4-AWS", + version="1.4", + description="CIS AWS Foundations Benchmark v1.4.0", + region="eu-west-1", + requirement_id="framework-metadata", + requirement_status=StatusChoices.PASS, + passed_checks=1, + failed_checks=0, + total_checks=1, + ) + + ComplianceOverviewSummary.objects.create( + tenant=tenant, + scan=scan, + compliance_id="cis_1.4_aws", + requirements_passed=5, + requirements_failed=1, + requirements_manual=2, + total_requirements=8, + ) + + response = authenticated_client.get( + reverse("complianceoverview-list"), + {"filter[scan_id]": str(scan.id)}, + ) + + assert response.status_code == status.HTTP_200_OK + data = response.json()["data"] + assert len(data) == 1 + overview = data[0] + assert overview["id"] == "cis_1.4_aws" + assert overview["attributes"]["requirements_passed"] == 5 + assert overview["attributes"]["requirements_failed"] == 1 + assert overview["attributes"]["requirements_manual"] == 2 + assert overview["attributes"]["total_requirements"] == 8 + assert "framework" in overview["attributes"] + assert "version" in overview["attributes"] + mock_backfill_task.assert_not_called() + + def test_compliance_overview_region_filter_skips_backfill( + self, + authenticated_client, + compliance_requirements_overviews_fixture, + mock_backfill_task, + ): + requirement_overview = compliance_requirements_overviews_fixture[0] + scan_id = str(requirement_overview.scan.id) + + response = authenticated_client.get( + reverse("complianceoverview-list"), + { + "filter[scan_id]": scan_id, + "filter[region]": requirement_overview.region, + }, + ) + + assert response.status_code == status.HTTP_200_OK + assert len(response.json()["data"]) >= 1 + mock_backfill_task.assert_not_called() + + def test_compliance_overview_list_without_scan_id( + self, authenticated_client, compliance_requirements_overviews_fixture + ): + # Ensure the endpoint works without passing a scan filter + response = authenticated_client.get(reverse("complianceoverview-list")) + + assert response.status_code == status.HTTP_200_OK + data = response.json()["data"] + assert len(data) == 3 + + # Validate payload structure + first_item = data[0] + assert "id" in first_item + assert "attributes" in first_item + attributes = first_item["attributes"] + assert "framework" in attributes + assert "version" in attributes + assert "requirements_passed" in attributes + assert "requirements_failed" in attributes + assert "requirements_manual" in attributes + assert "total_requirements" in attributes def test_compliance_overview_metadata( self, authenticated_client, compliance_requirements_overviews_fixture @@ -5849,6 +6146,11 @@ class TestComplianceOverviewViewSet: requirement_overview1 = compliance_requirements_overviews_fixture[0] scan_id = str(requirement_overview1.scan.id) + # Remove existing compliance data so the view falls back to task checks + scan = requirement_overview1.scan + ComplianceOverviewSummary.objects.filter(scan=scan).delete() + ComplianceRequirementOverview.objects.filter(scan=scan).delete() + # Mock a running task with patch.object( ComplianceOverviewViewSet, "get_task_response_if_running" @@ -5876,6 +6178,11 @@ class TestComplianceOverviewViewSet: requirement_overview1 = compliance_requirements_overviews_fixture[0] scan_id = str(requirement_overview1.scan.id) + # Remove existing compliance data so the view falls back to task checks + scan = requirement_overview1.scan + ComplianceOverviewSummary.objects.filter(scan=scan).delete() + ComplianceRequirementOverview.objects.filter(scan=scan).delete() + # Mock a failed task with patch.object( ComplianceOverviewViewSet, "get_task_response_if_running" @@ -5899,6 +6206,8 @@ class TestComplianceOverviewViewSet: ("framework", "framework", 1), ("version", "version", 1), ("region", "region", 1), + ("region__in", "region", 1), + ("region.in", "region", 1), ], ) def test_compliance_overview_filters( @@ -6066,11 +6375,414 @@ class TestOverviewViewSet: for entry in grouped_data: assert "findings" not in entry["attributes"] + def _create_scan(self, tenant, provider, name, started_at=None): + scan_started = started_at or datetime.now(timezone.utc) - timedelta(hours=1) + return Scan.objects.create( + tenant=tenant, + provider=provider, + name=name, + trigger=Scan.TriggerChoices.MANUAL, + state=StateChoices.COMPLETED, + started_at=scan_started, + completed_at=scan_started + timedelta(minutes=30), + ) + + def _create_threatscore_snapshot( + self, + tenant, + scan, + provider, + *, + compliance_id, + overall_score, + score_delta, + section_scores, + critical_requirements, + total_requirements, + passed_requirements, + failed_requirements, + manual_requirements, + total_findings, + passed_findings, + failed_findings, + ): + return ThreatScoreSnapshot.objects.create( + tenant=tenant, + scan=scan, + provider=provider, + compliance_id=compliance_id, + overall_score=Decimal(overall_score), + score_delta=Decimal(score_delta) if score_delta is not None else None, + section_scores=section_scores, + critical_requirements=critical_requirements, + total_requirements=total_requirements, + passed_requirements=passed_requirements, + failed_requirements=failed_requirements, + manual_requirements=manual_requirements, + total_findings=total_findings, + passed_findings=passed_findings, + failed_findings=failed_findings, + ) + + def test_overview_threatscore_returns_weighted_aggregate_snapshot( + self, authenticated_client, tenants_fixture, providers_fixture + ): + tenant = tenants_fixture[0] + provider1, provider2, *_ = providers_fixture + + scan1 = self._create_scan(tenant, provider1, "agg-scan-one") + scan2 = self._create_scan(tenant, provider2, "agg-scan-two") + + snapshot1 = self._create_threatscore_snapshot( + tenant, + scan1, + provider1, + compliance_id="prowler_threatscore_aws", + overall_score="80.00", + score_delta="5.00", + section_scores={"1. IAM": "70.00", "2. Attack Surface": "60.00"}, + critical_requirements=[ + { + "requirement_id": "req_shared", + "title": "Shared requirement (preferred)", + "section": "1. IAM", + "subsection": "Sub IAM", + "risk_level": 5, + "weight": 150, + "passed_findings": 14, + "total_findings": 20, + "description": "Higher risk duplicate", + }, + { + "requirement_id": "req_unique_one", + "title": "Unique provider one", + "section": "2. Attack Surface", + "subsection": "Sub Attack", + "risk_level": 4, + "weight": 90, + "passed_findings": 20, + "total_findings": 30, + "description": "Lower risk", + }, + ], + total_requirements=120, + passed_requirements=90, + failed_requirements=30, + manual_requirements=0, + total_findings=100, + passed_findings=70, + failed_findings=30, + ) + + snapshot2 = self._create_threatscore_snapshot( + tenant, + scan2, + provider2, + compliance_id="prowler_threatscore_aws", + overall_score="20.00", + score_delta="-2.00", + section_scores={ + "1. IAM": "10.00", + "2. Attack Surface": "40.00", + "3. Logging": "30.00", + }, + critical_requirements=[ + { + "requirement_id": "req_shared", + "title": "Shared requirement (secondary)", + "section": "1. IAM", + "subsection": "Sub IAM", + "risk_level": 4, + "weight": 120, + "passed_findings": 8, + "total_findings": 12, + "description": "Lower risk duplicate", + }, + { + "requirement_id": "req_unique_two", + "title": "Unique provider two", + "section": "3. Logging", + "subsection": "Sub Logging", + "risk_level": 5, + "weight": 110, + "passed_findings": 6, + "total_findings": 10, + "description": "Another critical requirement", + }, + ], + total_requirements=80, + passed_requirements=30, + failed_requirements=50, + manual_requirements=0, + total_findings=50, + passed_findings=15, + failed_findings=35, + ) + + older_inserted = datetime(2025, 1, 1, 12, 0, tzinfo=timezone.utc) + newer_inserted = datetime(2025, 1, 2, 12, 0, tzinfo=timezone.utc) + ThreatScoreSnapshot.objects.filter(id=snapshot1.id).update( + inserted_at=older_inserted + ) + ThreatScoreSnapshot.objects.filter(id=snapshot2.id).update( + inserted_at=newer_inserted + ) + snapshot2.refresh_from_db() + + response = authenticated_client.get(reverse("overview-threatscore")) + + assert response.status_code == status.HTTP_200_OK + body = response.json() + assert len(body["data"]) == 1 + aggregated = body["data"][0] + + assert aggregated["id"] == "n/a" + assert aggregated["relationships"]["scan"]["data"] is None + assert aggregated["relationships"]["provider"]["data"] is None + + attrs = aggregated["attributes"] + assert Decimal(attrs["overall_score"]) == Decimal("60.00") + assert Decimal(attrs["score_delta"]) == Decimal("2.67") + assert attrs["inserted_at"] == snapshot2.inserted_at.isoformat().replace( + "+00:00", "Z" + ) + assert attrs["total_findings"] == 150 + assert attrs["passed_findings"] == 85 + assert attrs["failed_findings"] == 65 + assert attrs["total_requirements"] == 200 + assert attrs["passed_requirements"] == 120 + assert attrs["failed_requirements"] == 80 + assert attrs["manual_requirements"] == 0 + + assert attrs["section_scores"] == { + "1. IAM": "50.00", + "2. Attack Surface": "53.33", + "3. Logging": "30.00", + } + + expected_critical = [ + { + "requirement_id": "req_shared", + "title": "Shared requirement (preferred)", + "section": "1. IAM", + "subsection": "Sub IAM", + "risk_level": 5, + "weight": 150, + "passed_findings": 14, + "total_findings": 20, + "description": "Higher risk duplicate", + }, + { + "requirement_id": "req_unique_two", + "title": "Unique provider two", + "section": "3. Logging", + "subsection": "Sub Logging", + "risk_level": 5, + "weight": 110, + "passed_findings": 6, + "total_findings": 10, + "description": "Another critical requirement", + }, + { + "requirement_id": "req_unique_one", + "title": "Unique provider one", + "section": "2. Attack Surface", + "subsection": "Sub Attack", + "risk_level": 4, + "weight": 90, + "passed_findings": 20, + "total_findings": 30, + "description": "Lower risk", + }, + ] + assert attrs["critical_requirements"] == expected_critical + + def test_overview_threatscore_weight_fallback_to_requirements( + self, authenticated_client, tenants_fixture, providers_fixture + ): + tenant = tenants_fixture[0] + provider1, provider2, *_ = providers_fixture + + scan1 = self._create_scan(tenant, provider1, "fallback-scan-1") + scan2 = self._create_scan(tenant, provider2, "fallback-scan-2") + + self._create_threatscore_snapshot( + tenant, + scan1, + provider1, + compliance_id="prowler_threatscore_aws", + overall_score="90.00", + score_delta="4.00", + section_scores={"1. IAM": "90.00"}, + critical_requirements=[], + total_requirements=10, + passed_requirements=8, + failed_requirements=0, + manual_requirements=2, + total_findings=0, + passed_findings=0, + failed_findings=0, + ) + self._create_threatscore_snapshot( + tenant, + scan2, + provider2, + compliance_id="prowler_threatscore_aws", + overall_score="50.00", + score_delta="1.00", + section_scores={"1. IAM": "40.00"}, + critical_requirements=[], + total_requirements=12, + passed_requirements=5, + failed_requirements=7, + manual_requirements=0, + total_findings=10, + passed_findings=4, + failed_findings=6, + ) + + response = authenticated_client.get(reverse("overview-threatscore")) + assert response.status_code == status.HTTP_200_OK + aggregate = response.json()["data"][0]["attributes"] + + assert Decimal(aggregate["overall_score"]) == Decimal("67.78") + assert Decimal(aggregate["score_delta"]) == Decimal("2.33") + assert aggregate["total_findings"] == 10 + assert aggregate["total_requirements"] == 22 + assert aggregate["manual_requirements"] == 2 + assert aggregate["section_scores"] == {"1. IAM": "62.22"} + + def test_overview_threatscore_filter_by_scan_id_returns_snapshot( + self, authenticated_client, tenants_fixture, providers_fixture + ): + tenant = tenants_fixture[0] + provider1, *_ = providers_fixture + scan = self._create_scan(tenant, provider1, "filter-scan") + + snapshot = self._create_threatscore_snapshot( + tenant, + scan, + provider1, + compliance_id="prowler_threatscore_aws", + overall_score="75.00", + score_delta="3.00", + section_scores={"1. IAM": "70.00"}, + critical_requirements=[], + total_requirements=50, + passed_requirements=30, + failed_requirements=20, + manual_requirements=0, + total_findings=25, + passed_findings=15, + failed_findings=10, + ) + + response = authenticated_client.get( + reverse("overview-threatscore"), {"filter[scan_id]": str(scan.id)} + ) + + assert response.status_code == status.HTTP_200_OK + body = response.json() + assert len(body["data"]) == 1 + assert body["data"][0]["id"] == str(snapshot.id) + assert body["data"][0]["attributes"]["overall_score"] == "75.00" + + def test_overview_threatscore_snapshot_id_returns_specific_snapshot( + self, authenticated_client, tenants_fixture, providers_fixture + ): + tenant = tenants_fixture[0] + provider1, *_ = providers_fixture + scan = self._create_scan(tenant, provider1, "snapshot-id-scan") + + snapshot = self._create_threatscore_snapshot( + tenant, + scan, + provider1, + compliance_id="prowler_threatscore_aws", + overall_score="88.50", + score_delta=None, + section_scores={"1. IAM": "80.00"}, + critical_requirements=[], + total_requirements=60, + passed_requirements=45, + failed_requirements=15, + manual_requirements=0, + total_findings=30, + passed_findings=25, + failed_findings=5, + ) + + response = authenticated_client.get( + reverse("overview-threatscore"), {"snapshot_id": str(snapshot.id)} + ) + + assert response.status_code == status.HTTP_200_OK + data = response.json() + assert data["data"]["id"] == str(snapshot.id) + assert data["data"]["attributes"]["score_delta"] is None + + def test_overview_threatscore_provider_filter_returns_unaggregated_snapshot( + self, authenticated_client, tenants_fixture, providers_fixture + ): + tenant = tenants_fixture[0] + provider1, provider2, *_ = providers_fixture + + scan1 = self._create_scan(tenant, provider1, "provider-filter-scan-1") + scan2 = self._create_scan(tenant, provider2, "provider-filter-scan-2") + + snapshot1 = self._create_threatscore_snapshot( + tenant, + scan1, + provider1, + compliance_id="prowler_threatscore_aws", + overall_score="55.55", + score_delta="1.10", + section_scores={"1. IAM": "50.00"}, + critical_requirements=[], + total_requirements=40, + passed_requirements=25, + failed_requirements=15, + manual_requirements=0, + total_findings=12, + passed_findings=7, + failed_findings=5, + ) + self._create_threatscore_snapshot( + tenant, + scan2, + provider2, + compliance_id="prowler_threatscore_aws", + overall_score="44.44", + score_delta="0.80", + section_scores={"1. IAM": "40.00"}, + critical_requirements=[], + total_requirements=30, + passed_requirements=18, + failed_requirements=12, + manual_requirements=0, + total_findings=10, + passed_findings=6, + failed_findings=4, + ) + + response = authenticated_client.get( + reverse("overview-threatscore"), + {"filter[provider_id__in]": str(provider1.id)}, + ) + + assert response.status_code == status.HTTP_200_OK + data = response.json()["data"] + assert len(data) == 1 + assert data[0]["id"] == str(snapshot1.id) + assert data[0]["attributes"]["overall_score"] == "55.55" + def test_overview_services_list_no_required_filters( self, authenticated_client, scan_summaries_fixture ): response = authenticated_client.get(reverse("overview-services")) - assert response.status_code == status.HTTP_400_BAD_REQUEST + assert response.status_code == status.HTTP_200_OK + # Should return services from latest scans + assert len(response.json()["data"]) == 2 def test_overview_services_list(self, authenticated_client, scan_summaries_fixture): response = authenticated_client.get( diff --git a/api/src/backend/api/v1/serializers.py b/api/src/backend/api/v1/serializers.py index c79d305942..b2d95a2609 100644 --- a/api/src/backend/api/v1/serializers.py +++ b/api/src/backend/api/v1/serializers.py @@ -47,6 +47,7 @@ from api.models import ( StatusChoices, Task, TenantAPIKey, + ThreatScoreSnapshot, User, UserRoleRelationship, ) @@ -1166,11 +1167,17 @@ class ResourceSerializer(RLSSerializer): "findings", "failed_findings_count", "url", + "metadata", + "details", + "partition", ] extra_kwargs = { "id": {"read_only": True}, "inserted_at": {"read_only": True}, "updated_at": {"read_only": True}, + "metadata": {"read_only": True}, + "details": {"read_only": True}, + "partition": {"read_only": True}, } included_serializers = { @@ -1227,11 +1234,15 @@ class ResourceIncludeSerializer(RLSSerializer): "service", "type_", "tags", + "details", + "partition", ] extra_kwargs = { "id": {"read_only": True}, "inserted_at": {"read_only": True}, "updated_at": {"read_only": True}, + "details": {"read_only": True}, + "partition": {"read_only": True}, } @extend_schema_field( @@ -3626,3 +3637,64 @@ class MuteRuleUpdateSerializer(BaseWriteSerializer): ): raise ValidationError("A mute rule with this name already exists.") return value + + +# ThreatScore Snapshots + + +class ThreatScoreSnapshotSerializer(RLSSerializer): + """ + Serializer for ThreatScore snapshots. + Read-only serializer for retrieving historical ThreatScore metrics. + """ + + id = serializers.SerializerMethodField() + + class Meta: + model = ThreatScoreSnapshot + fields = [ + "id", + "inserted_at", + "scan", + "provider", + "compliance_id", + "overall_score", + "score_delta", + "section_scores", + "critical_requirements", + "total_requirements", + "passed_requirements", + "failed_requirements", + "manual_requirements", + "total_findings", + "passed_findings", + "failed_findings", + ] + extra_kwargs = { + "id": {"read_only": True}, + "inserted_at": {"read_only": True}, + "scan": {"read_only": True}, + "provider": {"read_only": True}, + "compliance_id": {"read_only": True}, + "overall_score": {"read_only": True}, + "score_delta": {"read_only": True}, + "section_scores": {"read_only": True}, + "critical_requirements": {"read_only": True}, + "total_requirements": {"read_only": True}, + "passed_requirements": {"read_only": True}, + "failed_requirements": {"read_only": True}, + "manual_requirements": {"read_only": True}, + "total_findings": {"read_only": True}, + "passed_findings": {"read_only": True}, + "failed_findings": {"read_only": True}, + } + + included_serializers = { + "scan": "api.v1.serializers.ScanIncludeSerializer", + "provider": "api.v1.serializers.ProviderIncludeSerializer", + } + + def get_id(self, obj): + if getattr(obj, "_aggregated", False): + return "n/a" + return str(obj.id) diff --git a/api/src/backend/api/v1/views.py b/api/src/backend/api/v1/views.py index 2cdbf02c8b..700550e4e4 100644 --- a/api/src/backend/api/v1/views.py +++ b/api/src/backend/api/v1/views.py @@ -3,7 +3,10 @@ import glob import json import logging import os +from collections import defaultdict +from copy import deepcopy from datetime import datetime, timedelta, timezone +from decimal import ROUND_HALF_UP, Decimal, InvalidOperation from urllib.parse import urljoin import sentry_sdk @@ -24,9 +27,23 @@ from django.conf import settings as django_settings from django.contrib.postgres.aggregates import ArrayAgg from django.contrib.postgres.search import SearchQuery from django.db import transaction -from django.db.models import Count, F, Prefetch, Q, Subquery, Sum +from django.db.models import ( + Case, + Count, + DecimalField, + ExpressionWrapper, + F, + IntegerField, + Max, + Prefetch, + Q, + Subquery, + Sum, + Value, + When, +) from django.db.models.functions import Coalesce -from django.http import HttpResponse +from django.http import HttpResponse, QueryDict from django.shortcuts import redirect from django.urls import reverse from django.utils.dateparse import parse_date @@ -58,6 +75,7 @@ from rest_framework_simplejwt.exceptions import InvalidToken, TokenError from tasks.beat import schedule_provider_scan from tasks.jobs.export import get_s3_client from tasks.tasks import ( + backfill_compliance_summaries_task, backfill_scan_resource_summaries_task, check_integration_connection_task, check_lighthouse_connection_task, @@ -101,13 +119,14 @@ from api.filters import ( ScanFilter, ScanSummaryFilter, ScanSummarySeverityFilter, - ServiceOverviewFilter, TaskFilter, TenantApiKeyFilter, TenantFilter, + ThreatScoreSnapshotFilter, UserFilter, ) from api.models import ( + ComplianceOverviewSummary, ComplianceRequirementOverview, Finding, Integration, @@ -138,6 +157,7 @@ from api.models import ( StateChoices, Task, TenantAPIKey, + ThreatScoreSnapshot, User, UserRoleRelationship, ) @@ -218,6 +238,7 @@ from api.v1.serializers import ( TenantApiKeySerializer, TenantApiKeyUpdateSerializer, TenantSerializer, + ThreatScoreSnapshotSerializer, TokenRefreshSerializer, TokenSerializer, TokenSocialLoginSerializer, @@ -3213,15 +3234,50 @@ class RoleProviderGroupRelationshipView(RelationshipView, BaseRLSViewSet): @extend_schema_view( list=extend_schema( tags=["Compliance Overview"], - summary="List compliance overviews for a scan", - description="Retrieve an overview of all the compliance in a given scan.", + summary="List compliance overviews", + description=( + "Retrieve an overview of all compliance frameworks. " + "If scan_id is provided, returns compliance data for that specific scan. " + "If scan_id is omitted, returns compliance data aggregated from the latest completed scan of each provider." + ), parameters=[ OpenApiParameter( name="filter[scan_id]", - required=True, + required=False, type=OpenApiTypes.UUID, location=OpenApiParameter.QUERY, - description="Related scan ID.", + description=( + "Optional scan ID. If provided, returns compliance for that scan. " + "If omitted, returns compliance for the latest completed scan per provider." + ), + ), + OpenApiParameter( + name="filter[provider_id]", + required=False, + type=OpenApiTypes.UUID, + location=OpenApiParameter.QUERY, + description="Filter by specific provider ID.", + ), + OpenApiParameter( + name="filter[provider_id__in]", + required=False, + type={"type": "array", "items": {"type": "string", "format": "uuid"}}, + location=OpenApiParameter.QUERY, + description="Filter by multiple provider IDs (comma-separated).", + ), + OpenApiParameter( + name="filter[provider_type]", + required=False, + type=OpenApiTypes.STR, + location=OpenApiParameter.QUERY, + description="Filter by provider type (e.g., aws, azure, gcp).", + ), + OpenApiParameter( + name="filter[provider_type__in]", + required=False, + type={"type": "array", "items": {"type": "string"}}, + location=OpenApiParameter.QUERY, + description="Filter by multiple provider types (comma-separated).", ), ], responses={ @@ -3378,33 +3434,45 @@ class ComplianceOverviewViewSet(BaseRLSViewSet, TaskManagementMixin): def retrieve(self, request, *args, **kwargs): raise MethodNotAllowed(method="GET") - def list(self, request, *args, **kwargs): - scan_id = request.query_params.get("filter[scan_id]") - if not scan_id: - raise ValidationError( - [ - { - "detail": "This query parameter is required.", - "status": 400, - "source": {"pointer": "filter[scan_id]"}, - "code": "required", - } - ] - ) - try: - if task := self.get_task_response_if_running( - task_name="scan-compliance-overviews", - task_kwargs={"tenant_id": self.request.tenant_id, "scan_id": scan_id}, - raise_on_not_found=False, - ): - return task - except TaskFailedException: - return Response( - {"detail": "Task failed to generate compliance overview data."}, - status=status.HTTP_500_INTERNAL_SERVER_ERROR, - ) - queryset = self.filter_queryset(self.filter_queryset(self.get_queryset())) + def _compliance_summaries_queryset(self, scan_id): + """Return pre-aggregated summaries constrained by RBAC visibility.""" + role = get_role(self.request.user) + unlimited_visibility = getattr( + role, Permissions.UNLIMITED_VISIBILITY.value, False + ) + summaries = ComplianceOverviewSummary.objects.filter( + tenant_id=self.request.tenant_id, + scan_id=scan_id, + ) + if not unlimited_visibility: + providers = Provider.all_objects.filter( + provider_groups__in=role.provider_groups.all() + ).distinct() + summaries = summaries.filter(scan__provider__in=providers) + + return summaries + + def _get_compliance_template(self, *, provider=None, scan_id=None): + """Return the compliance template for the given provider or scan.""" + if provider is None and scan_id is not None: + scan = Scan.all_objects.select_related("provider").get(pk=scan_id) + provider = scan.provider + + if not provider: + return {} + + return PROWLER_COMPLIANCE_OVERVIEW_TEMPLATE.get(provider.provider, {}) + + def _aggregate_compliance_overview(self, queryset, template_metadata=None): + """ + Aggregate requirement rows into compliance overview dictionaries. + + Args: + queryset: ComplianceRequirementOverview queryset already filtered. + template_metadata: Optional dict mapping compliance_id -> metadata. + """ + template_metadata = template_metadata or {} requirement_status_subquery = queryset.values( "compliance_id", "requirement_id" ).annotate( @@ -3414,13 +3482,15 @@ class ComplianceOverviewViewSet(BaseRLSViewSet, TaskManagementMixin): ) compliance_data = {} - framework_info = {} - - for item in queryset.values("compliance_id", "framework", "version").distinct(): - framework_info[item["compliance_id"]] = { + fallback_metadata = { + item["compliance_id"]: { "framework": item["framework"], "version": item["version"], } + for item in queryset.values( + "compliance_id", "framework", "version" + ).distinct() + } for item in requirement_status_subquery: compliance_id = item["compliance_id"] @@ -3432,32 +3502,36 @@ class ComplianceOverviewViewSet(BaseRLSViewSet, TaskManagementMixin): else: req_status = "MANUAL" - if compliance_id not in compliance_data: - compliance_data[compliance_id] = { + compliance_status = compliance_data.setdefault( + compliance_id, + { "total_requirements": 0, "requirements_passed": 0, "requirements_failed": 0, "requirements_manual": 0, - } + }, + ) - compliance_data[compliance_id]["total_requirements"] += 1 + compliance_status["total_requirements"] += 1 if req_status == "PASS": - compliance_data[compliance_id]["requirements_passed"] += 1 + compliance_status["requirements_passed"] += 1 elif req_status == "FAIL": - compliance_data[compliance_id]["requirements_failed"] += 1 + compliance_status["requirements_failed"] += 1 else: - compliance_data[compliance_id]["requirements_manual"] += 1 + compliance_status["requirements_manual"] += 1 response_data = [] for compliance_id, data in compliance_data.items(): - framework = framework_info.get(compliance_id, {}) + template = template_metadata.get(compliance_id, {}) + fallback = fallback_metadata.get(compliance_id, {}) response_data.append( { "id": compliance_id, "compliance_id": compliance_id, - "framework": framework.get("framework", ""), - "version": framework.get("version", ""), + "framework": template.get("framework") + or fallback.get("framework", ""), + "version": template.get("version") or fallback.get("version", ""), "requirements_passed": data["requirements_passed"], "requirements_failed": data["requirements_failed"], "requirements_manual": data["requirements_manual"], @@ -3466,7 +3540,151 @@ class ComplianceOverviewViewSet(BaseRLSViewSet, TaskManagementMixin): ) serializer = self.get_serializer(response_data, many=True) - return Response(serializer.data) + return serializer.data + + def _task_response_if_running(self, scan_id): + """Check for an in-progress task only when no compliance data exists.""" + try: + return self.get_task_response_if_running( + task_name="scan-compliance-overviews", + task_kwargs={"tenant_id": self.request.tenant_id, "scan_id": scan_id}, + raise_on_not_found=False, + ) + except TaskFailedException: + return Response( + {"detail": "Task failed to generate compliance overview data."}, + status=status.HTTP_500_INTERNAL_SERVER_ERROR, + ) + + def _list_with_region_filter(self, scan_id, region_filter): + """ + Fall back to detailed ComplianceRequirementOverview query when region filter is applied. + This uses the original aggregation logic across filtered regions. + """ + regions = region_filter.split(",") if "," in region_filter else [region_filter] + queryset = self.filter_queryset(self.get_queryset()).filter( + scan_id=scan_id, + region__in=regions, + ) + + data = self._aggregate_compliance_overview(queryset) + if data: + return Response(data) + + task_response = self._task_response_if_running(scan_id) + if task_response: + return task_response + + return Response(data) + + def _list_without_region_aggregation(self, scan_id): + """ + Fall back aggregation when compliance summaries don't exist yet. + Aggregates ComplianceRequirementOverview data across ALL regions. + """ + queryset = self.filter_queryset(self.get_queryset()).filter(scan_id=scan_id) + compliance_template = self._get_compliance_template(scan_id=scan_id) + data = self._aggregate_compliance_overview( + queryset, template_metadata=compliance_template + ) + if data: + return Response(data) + + task_response = self._task_response_if_running(scan_id) + if task_response: + return task_response + + return Response(data) + + def list(self, request, *args, **kwargs): + scan_id = request.query_params.get("filter[scan_id]") + tenant_id = self.request.tenant_id + + if scan_id: + # Specific scan requested - use optimized summaries with region support + region_filter = request.query_params.get( + "filter[region]" + ) or request.query_params.get("filter[region__in]") + + if region_filter: + # Fall back to detailed query with region filtering + return self._list_with_region_filter(scan_id, region_filter) + + summaries = list(self._compliance_summaries_queryset(scan_id)) + if not summaries: + # Trigger async backfill for next time + backfill_compliance_summaries_task.delay( + tenant_id=self.request.tenant_id, scan_id=scan_id + ) + # Use fallback aggregation for this request + return self._list_without_region_aggregation(scan_id) + + # Get compliance template for provider to enrich with framework/version + compliance_template = self._get_compliance_template(scan_id=scan_id) + + # Convert to response format with framework/version enrichment + response_data = [] + for summary in summaries: + compliance_metadata = compliance_template.get(summary.compliance_id, {}) + response_data.append( + { + "id": summary.compliance_id, + "compliance_id": summary.compliance_id, + "framework": compliance_metadata.get("framework", ""), + "version": compliance_metadata.get("version", ""), + "requirements_passed": summary.requirements_passed, + "requirements_failed": summary.requirements_failed, + "requirements_manual": summary.requirements_manual, + "total_requirements": summary.total_requirements, + } + ) + + serializer = self.get_serializer(response_data, many=True) + return Response(serializer.data) + else: + # No scan_id provided - use latest scans per provider + # First, check if provider filters are present + provider_id = request.query_params.get("filter[provider_id]") + provider_id__in = request.query_params.get("filter[provider_id__in]") + provider_type = request.query_params.get("filter[provider_type]") + provider_type__in = request.query_params.get("filter[provider_type__in]") + + scan_filters = {"tenant_id": tenant_id, "state": StateChoices.COMPLETED} + + # Apply provider ID filters + if provider_id: + scan_filters["provider_id"] = provider_id + elif provider_id__in: + # Convert comma-separated string to list + provider_ids = [pid.strip() for pid in provider_id__in.split(",")] + scan_filters["provider_id__in"] = provider_ids + + # Apply provider type filters + if provider_type: + scan_filters["provider__provider"] = provider_type + elif provider_type__in: + # Convert comma-separated string to list + provider_types = [pt.strip() for pt in provider_type__in.split(",")] + scan_filters["provider__provider__in"] = provider_types + + latest_scan_ids = ( + Scan.all_objects.filter(**scan_filters) + .order_by("provider_id", "-inserted_at") + .distinct("provider_id") + .values_list("id", flat=True) + ) + + base_queryset = self.get_queryset() + queryset = self.filter_queryset( + base_queryset.filter(scan_id__in=latest_scan_ids) + ) + + # Aggregate compliance data across latest scans + compliance_template = self._get_compliance_template() + data = self._aggregate_compliance_overview( + queryset, template_metadata=compliance_template + ) + return Response(data) @action(detail=False, methods=["get"], url_name="metadata") def metadata(self, request): @@ -3482,18 +3700,6 @@ class ComplianceOverviewViewSet(BaseRLSViewSet, TaskManagementMixin): } ] ) - try: - if task := self.get_task_response_if_running( - task_name="scan-compliance-overviews", - task_kwargs={"tenant_id": self.request.tenant_id, "scan_id": scan_id}, - raise_on_not_found=False, - ): - return task - except TaskFailedException: - return Response( - {"detail": "Task failed to generate compliance overview data."}, - status=status.HTTP_500_INTERNAL_SERVER_ERROR, - ) regions = list( self.get_queryset() .filter(scan_id=scan_id) @@ -3503,6 +3709,15 @@ class ComplianceOverviewViewSet(BaseRLSViewSet, TaskManagementMixin): ) result = {"regions": regions} + if regions: + serializer = self.get_serializer(data=result) + serializer.is_valid(raise_exception=True) + return Response(serializer.data, status=status.HTTP_200_OK) + + task_response = self._task_response_if_running(scan_id) + if task_response: + return task_response + serializer = self.get_serializer(data=result) serializer.is_valid(raise_exception=True) return Response(serializer.data, status=status.HTTP_200_OK) @@ -3535,18 +3750,6 @@ class ComplianceOverviewViewSet(BaseRLSViewSet, TaskManagementMixin): } ] ) - try: - if task := self.get_task_response_if_running( - task_name="scan-compliance-overviews", - task_kwargs={"tenant_id": self.request.tenant_id, "scan_id": scan_id}, - raise_on_not_found=False, - ): - return task - except TaskFailedException: - return Response( - {"detail": "Task failed to generate compliance overview data."}, - status=status.HTTP_500_INTERNAL_SERVER_ERROR, - ) filtered_queryset = self.filter_queryset(self.get_queryset()) all_requirements = filtered_queryset.values( @@ -3606,6 +3809,13 @@ class ComplianceOverviewViewSet(BaseRLSViewSet, TaskManagementMixin): requirements_summary, many=True ) + if requirements_summary: + return Response(serializer.data, status=status.HTTP_200_OK) + + task_response = self._task_response_if_running(scan_id) + if task_response: + return task_response + return Response(serializer.data, status=status.HTTP_200_OK) @action(detail=False, methods=["get"], url_name="attributes") @@ -3624,15 +3834,6 @@ class ComplianceOverviewViewSet(BaseRLSViewSet, TaskManagementMixin): ) provider_type = None - try: - sample_requirement = ( - self.get_queryset().filter(compliance_id=compliance_id).first() - ) - - if sample_requirement: - provider_type = sample_requirement.scan.provider.provider - except Exception: - pass # If we couldn't determine from database, try each provider type if not provider_type: @@ -3735,8 +3936,7 @@ class ComplianceOverviewViewSet(BaseRLSViewSet, TaskManagementMixin): summary="Get findings data by service", description=( "Retrieve an aggregated summary of findings grouped by service. The response includes the total count " - "of findings for each service, as long as there are at least one finding for that service. At least " - "one of the `inserted_at` filters must be provided." + "of findings for each service, as long as there are at least one finding for that service." ), filters=True, ), @@ -3770,6 +3970,8 @@ class OverviewViewSet(BaseRLSViewSet): return OverviewSeveritySerializer elif self.action == "services": return OverviewServiceSerializer + elif self.action == "threatscore": + return ThreatScoreSnapshotSerializer return super().get_serializer_class() def get_filterset_class(self): @@ -3780,7 +3982,7 @@ class OverviewViewSet(BaseRLSViewSet): elif self.action == "findings_severity": return ScanSummarySeverityFilter elif self.action == "services": - return ServiceOverviewFilter + return ScanSummaryFilter return None @extend_schema(exclude=True) @@ -4011,6 +4213,332 @@ class OverviewViewSet(BaseRLSViewSet): return Response(serializer.data, status=status.HTTP_200_OK) + @extend_schema( + summary="Get ThreatScore snapshots", + description=( + "Retrieve ThreatScore metrics. By default, returns the latest snapshot for each provider. " + "Use snapshot_id to retrieve a specific historical snapshot." + ), + tags=["Overviews"], + parameters=[ + OpenApiParameter( + name="snapshot_id", + type=OpenApiTypes.UUID, + location=OpenApiParameter.QUERY, + description="Retrieve a specific snapshot by ID. If not provided, returns latest snapshots.", + ), + OpenApiParameter( + name="provider_id", + type=OpenApiTypes.UUID, + location=OpenApiParameter.QUERY, + description="Filter by specific provider ID", + ), + OpenApiParameter( + name="provider_id__in", + type=OpenApiTypes.STR, + location=OpenApiParameter.QUERY, + description="Filter by multiple provider IDs (comma-separated UUIDs)", + ), + OpenApiParameter( + name="provider_type", + type=OpenApiTypes.STR, + location=OpenApiParameter.QUERY, + description="Filter by provider type (aws, azure, gcp, etc.)", + ), + OpenApiParameter( + name="provider_type__in", + type=OpenApiTypes.STR, + location=OpenApiParameter.QUERY, + description="Filter by multiple provider types (comma-separated)", + ), + ], + ) + @action(detail=False, methods=["get"], url_name="threatscore") + def threatscore(self, request): + """ + Get ThreatScore snapshots. + + Default behavior: Returns the latest snapshot for each provider. + With snapshot_id: Returns the specific snapshot requested. + """ + tenant_id = self.request.tenant_id + snapshot_id = request.query_params.get("snapshot_id") + + # Base queryset with RLS + base_queryset = ThreatScoreSnapshot.objects.filter(tenant_id=tenant_id) + + # Apply RBAC filtering + if hasattr(self, "allowed_providers"): + base_queryset = base_queryset.filter(provider__in=self.allowed_providers) + + # Case 1: Specific snapshot requested + if snapshot_id: + try: + snapshot = base_queryset.get(id=snapshot_id) + serializer = ThreatScoreSnapshotSerializer( + snapshot, context={"request": request} + ) + return Response(serializer.data, status=status.HTTP_200_OK) + except ThreatScoreSnapshot.DoesNotExist: + raise NotFound(detail="ThreatScore snapshot not found") + + # Case 2: Latest snapshot per provider (default) + # Apply filters manually: this @action is outside the standard list endpoint flow, + # so DRF's filter backends don't execute and we must flatten JSON:API params ourselves. + normalized_params = QueryDict(mutable=True) + for param_key, values in request.query_params.lists(): + normalized_key = param_key + if param_key.startswith("filter[") and param_key.endswith("]"): + normalized_key = param_key[7:-1] + if normalized_key == "snapshot_id": + continue + normalized_params.setlist(normalized_key, values) + + filterset = ThreatScoreSnapshotFilter(normalized_params, queryset=base_queryset) + filtered_queryset = filterset.qs + + # Get distinct provider IDs from filtered queryset + # Pick the latest snapshot per provider using Postgres DISTINCT ON pattern. + # This avoids issuing one query per provider (N+1) when the filtered dataset is large. + latest_snapshot_ids = list( + filtered_queryset.order_by("provider_id", "-inserted_at") + .distinct("provider_id") + .values_list("id", flat=True) + ) + latest_snapshot_map = { + snapshot.id: snapshot + for snapshot in filtered_queryset.filter(id__in=latest_snapshot_ids) + } + latest_snapshots = [ + latest_snapshot_map[snapshot_id] + for snapshot_id in latest_snapshot_ids + if snapshot_id in latest_snapshot_map + ] + + if len(latest_snapshots) <= 1: + serializer = ThreatScoreSnapshotSerializer( + latest_snapshots, many=True, context={"request": request} + ) + return Response(serializer.data, status=status.HTTP_200_OK) + + snapshot_ids = [ + snapshot.id for snapshot in latest_snapshots if snapshot and snapshot.id + ] + aggregated_snapshot = self._build_threatscore_overview_snapshot( + snapshot_ids, tenant_id + ) + serializer = ThreatScoreSnapshotSerializer( + [aggregated_snapshot], many=True, context={"request": request} + ) + return Response(serializer.data, status=status.HTTP_200_OK) + + def _build_threatscore_overview_snapshot(self, snapshot_ids, tenant_id): + """ + Aggregate the latest snapshots into a single overview snapshot for the tenant. + """ + if not snapshot_ids: + raise ValueError( + "Snapshot id list cannot be empty when aggregating threatscore overview" + ) + + base_queryset = ThreatScoreSnapshot.objects.filter( + tenant_id=tenant_id, id__in=snapshot_ids + ) + + annotated_queryset = ( + base_queryset.annotate( + active_requirements=ExpressionWrapper( + F("total_requirements") - F("manual_requirements"), + output_field=IntegerField(), + ) + ) + .annotate( + weight=Case( + When(total_findings__gt=0, then=F("total_findings")), + When( + active_requirements__gt=0, + then=F("active_requirements"), + ), + default=Value(1, output_field=IntegerField()), + output_field=IntegerField(), + ) + ) + .order_by() + ) + + aggregated_metrics = annotated_queryset.aggregate( + total_requirements=Sum("total_requirements"), + passed_requirements=Sum("passed_requirements"), + failed_requirements=Sum("failed_requirements"), + manual_requirements=Sum("manual_requirements"), + total_findings=Sum("total_findings"), + passed_findings=Sum("passed_findings"), + failed_findings=Sum("failed_findings"), + weighted_overall_sum=Sum( + ExpressionWrapper( + F("overall_score") * F("weight"), + output_field=DecimalField(max_digits=14, decimal_places=4), + ) + ), + overall_weight=Sum("weight"), + unweighted_overall_sum=Sum("overall_score"), + weighted_delta_sum=Sum( + Case( + When( + score_delta__isnull=False, + then=ExpressionWrapper( + F("score_delta") * F("weight"), + output_field=DecimalField(max_digits=14, decimal_places=4), + ), + ), + default=Value( + Decimal("0"), + output_field=DecimalField(max_digits=14, decimal_places=4), + ), + output_field=DecimalField(max_digits=14, decimal_places=4), + ) + ), + delta_weight=Sum( + Case( + When(score_delta__isnull=False, then=F("weight")), + default=Value(0, output_field=IntegerField()), + output_field=IntegerField(), + ) + ), + provider_count=Count("id"), + latest_inserted_at=Max("inserted_at"), + ) + + total_requirements = aggregated_metrics["total_requirements"] or 0 + passed_requirements = aggregated_metrics["passed_requirements"] or 0 + failed_requirements = aggregated_metrics["failed_requirements"] or 0 + manual_requirements = aggregated_metrics["manual_requirements"] or 0 + total_findings = aggregated_metrics["total_findings"] or 0 + passed_findings = aggregated_metrics["passed_findings"] or 0 + failed_findings = aggregated_metrics["failed_findings"] or 0 + + weighted_overall_sum = aggregated_metrics["weighted_overall_sum"] + if weighted_overall_sum is None: + weighted_overall_sum = Decimal("0") + unweighted_overall_sum = aggregated_metrics["unweighted_overall_sum"] + if unweighted_overall_sum is None: + unweighted_overall_sum = Decimal("0") + + overall_weight = aggregated_metrics["overall_weight"] or 0 + provider_count = aggregated_metrics["provider_count"] or 0 + + weighted_delta_sum = aggregated_metrics["weighted_delta_sum"] + if weighted_delta_sum is None: + weighted_delta_sum = Decimal("0") + delta_weight = aggregated_metrics["delta_weight"] or 0 + + if overall_weight > 0: + overall_score = (weighted_overall_sum / Decimal(overall_weight)).quantize( + Decimal("0.01"), rounding=ROUND_HALF_UP + ) + elif provider_count > 0: + overall_score = (unweighted_overall_sum / Decimal(provider_count)).quantize( + Decimal("0.01"), rounding=ROUND_HALF_UP + ) + else: + overall_score = Decimal("0.00") + + if delta_weight > 0: + score_delta = (weighted_delta_sum / Decimal(delta_weight)).quantize( + Decimal("0.01"), rounding=ROUND_HALF_UP + ) + else: + score_delta = None + + section_weighted_sums = defaultdict(lambda: Decimal("0")) + section_weights = defaultdict(lambda: Decimal("0")) + + combined_critical_requirements = {} + + snapshots_with_weight = list(annotated_queryset) + + for snapshot in snapshots_with_weight: + weight_value = getattr(snapshot, "weight", None) + try: + weight_decimal = Decimal(weight_value) + except (InvalidOperation, TypeError): + weight_decimal = Decimal("1") + if weight_decimal <= 0: + weight_decimal = Decimal("1") + + section_scores = snapshot.section_scores or {} + for section, score in section_scores.items(): + try: + score_decimal = Decimal(str(score)) + except (InvalidOperation, TypeError): + continue + section_weighted_sums[section] += score_decimal * weight_decimal + section_weights[section] += weight_decimal + + for requirement in snapshot.critical_requirements or []: + key = requirement.get("requirement_id") or requirement.get("title") + if not key: + continue + existing = combined_critical_requirements.get(key) + + def requirement_sort_key(item): + return ( + item.get("risk_level") or 0, + item.get("weight") or 0, + ) + + if existing is None or requirement_sort_key( + requirement + ) > requirement_sort_key(existing): + combined_critical_requirements[key] = deepcopy(requirement) + + aggregated_section_scores = {} + for section, total in section_weighted_sums.items(): + weight_total = section_weights[section] + if weight_total > 0: + aggregated_section_scores[section] = str( + (total / weight_total).quantize( + Decimal("0.01"), rounding=ROUND_HALF_UP + ) + ) + + aggregated_section_scores = dict(sorted(aggregated_section_scores.items())) + + aggregated_critical_requirements = sorted( + combined_critical_requirements.values(), + key=lambda item: ( + item.get("risk_level") or 0, + item.get("weight") or 0, + ), + reverse=True, + ) + + aggregated_snapshot = ThreatScoreSnapshot( + tenant_id=tenant_id, + scan=None, + provider=None, + compliance_id="prowler_threatscore_overview", + overall_score=overall_score, + score_delta=score_delta, + section_scores=aggregated_section_scores, + critical_requirements=aggregated_critical_requirements, + total_requirements=total_requirements, + passed_requirements=passed_requirements, + failed_requirements=failed_requirements, + manual_requirements=manual_requirements, + total_findings=total_findings, + passed_findings=passed_findings, + failed_findings=failed_findings, + ) + + latest_inserted_at = aggregated_metrics["latest_inserted_at"] + if latest_inserted_at is not None: + aggregated_snapshot.inserted_at = latest_inserted_at + + aggregated_snapshot._aggregated = True + + return aggregated_snapshot + @extend_schema(tags=["Schedule"]) @extend_schema_view( diff --git a/api/src/backend/tasks/jobs/backfill.py b/api/src/backend/tasks/jobs/backfill.py index 6c83e6a69b..39fcd41fe1 100644 --- a/api/src/backend/tasks/jobs/backfill.py +++ b/api/src/backend/tasks/jobs/backfill.py @@ -1,5 +1,10 @@ +from collections import defaultdict + +from api.db_router import READ_REPLICA_ALIAS from api.db_utils import rls_transaction from api.models import ( + ComplianceOverviewSummary, + ComplianceRequirementOverview, Resource, ResourceFindingMapping, ResourceScanSummary, @@ -9,7 +14,7 @@ from api.models import ( def backfill_resource_scan_summaries(tenant_id: str, scan_id: str): - with rls_transaction(tenant_id): + with rls_transaction(tenant_id, using=READ_REPLICA_ALIAS): if ResourceScanSummary.objects.filter( tenant_id=tenant_id, scan_id=scan_id ).exists(): @@ -59,3 +64,114 @@ def backfill_resource_scan_summaries(tenant_id: str, scan_id: str): ) return {"status": "backfilled", "inserted": len(summaries)} + + +def backfill_compliance_summaries(tenant_id: str, scan_id: str): + """ + Backfill ComplianceOverviewSummary records for a completed scan. + + This function checks if summary records already exist for the scan. + If not, it aggregates compliance requirement data and creates the summaries. + + Args: + tenant_id: Target tenant UUID + scan_id: Scan UUID to backfill + + Returns: + dict: Status indicating whether backfill was performed + """ + with rls_transaction(tenant_id): + if ComplianceOverviewSummary.objects.filter( + tenant_id=tenant_id, scan_id=scan_id + ).exists(): + return {"status": "already backfilled"} + + with rls_transaction(tenant_id): + if not Scan.objects.filter( + tenant_id=tenant_id, + id=scan_id, + state__in=(StateChoices.COMPLETED, StateChoices.FAILED), + ).exists(): + return {"status": "scan is not completed"} + + # Fetch all compliance requirement overview rows for this scan + requirement_rows = ComplianceRequirementOverview.objects.filter( + tenant_id=tenant_id, scan_id=scan_id + ).values( + "compliance_id", + "requirement_id", + "requirement_status", + ) + + if not requirement_rows: + return {"status": "no compliance data to backfill"} + + # Group by (compliance_id, requirement_id) across regions + requirement_statuses = defaultdict( + lambda: {"fail_count": 0, "pass_count": 0, "total_count": 0} + ) + + for row in requirement_rows: + compliance_id = row["compliance_id"] + requirement_id = row["requirement_id"] + requirement_status = row["requirement_status"] + + # Aggregate requirement status across regions + key = (compliance_id, requirement_id) + requirement_statuses[key]["total_count"] += 1 + + if requirement_status == "FAIL": + requirement_statuses[key]["fail_count"] += 1 + elif requirement_status == "PASS": + requirement_statuses[key]["pass_count"] += 1 + + # Determine per-requirement status and aggregate to compliance level + compliance_summaries = defaultdict( + lambda: { + "total_requirements": 0, + "requirements_passed": 0, + "requirements_failed": 0, + "requirements_manual": 0, + } + ) + + for (compliance_id, requirement_id), counts in requirement_statuses.items(): + # Apply business rule: any FAIL → requirement fails + if counts["fail_count"] > 0: + req_status = "FAIL" + elif counts["pass_count"] == counts["total_count"]: + req_status = "PASS" + else: + req_status = "MANUAL" + + # Aggregate to compliance level + compliance_summaries[compliance_id]["total_requirements"] += 1 + if req_status == "PASS": + compliance_summaries[compliance_id]["requirements_passed"] += 1 + elif req_status == "FAIL": + compliance_summaries[compliance_id]["requirements_failed"] += 1 + else: + compliance_summaries[compliance_id]["requirements_manual"] += 1 + + # Create summary objects + summary_objects = [] + for compliance_id, data in compliance_summaries.items(): + summary_objects.append( + ComplianceOverviewSummary( + tenant_id=tenant_id, + scan_id=scan_id, + compliance_id=compliance_id, + requirements_passed=data["requirements_passed"], + requirements_failed=data["requirements_failed"], + requirements_manual=data["requirements_manual"], + total_requirements=data["total_requirements"], + ) + ) + + # Bulk insert summaries + if summary_objects: + ComplianceOverviewSummary.objects.bulk_create( + summary_objects, batch_size=500, ignore_conflicts=True + ) + + return {"status": "backfilled", "inserted": len(summary_objects)} diff --git a/api/src/backend/tasks/jobs/report.py b/api/src/backend/tasks/jobs/report.py index 641fa5757a..4136cd3748 100644 --- a/api/src/backend/tasks/jobs/report.py +++ b/api/src/backend/tasks/jobs/report.py @@ -7,7 +7,6 @@ from shutil import rmtree import matplotlib.pyplot as plt from celery.utils.log import get_task_logger from config.django.base import DJANGO_FINDINGS_BATCH_SIZE, DJANGO_TMP_OUTPUT_DIRECTORY -from django.db.models import Count, Q from reportlab.lib import colors from reportlab.lib.enums import TA_CENTER from reportlab.lib.pagesizes import letter @@ -26,11 +25,22 @@ from reportlab.platypus import ( TableStyle, ) from tasks.jobs.export import _generate_output_directory, _upload_to_s3 +from tasks.jobs.threatscore import compute_threatscore_metrics +from tasks.jobs.threatscore_utils import ( + _aggregate_requirement_statistics_from_database, + _calculate_requirements_data_from_statistics, +) from tasks.utils import batched from api.db_router import READ_REPLICA_ALIAS from api.db_utils import rls_transaction -from api.models import Finding, Provider, ScanSummary, StatusChoices +from api.models import ( + Finding, + Provider, + ScanSummary, + StatusChoices, + ThreatScoreSnapshot, +) from api.utils import initialize_prowler_provider from prowler.lib.check.compliance_models import Compliance from prowler.lib.outputs.finding import Finding as FindingOutput @@ -434,56 +444,6 @@ def _add_pdf_footer(canvas_obj: canvas.Canvas, doc: SimpleDocTemplate) -> None: canvas_obj.drawString(width - text_width - 30, 20, powered_text) -def _aggregate_requirement_statistics_from_database( - tenant_id: str, scan_id: str -) -> dict[str, dict[str, int]]: - """ - Aggregate finding statistics by check_id using database aggregation. - - This function uses Django ORM aggregation to calculate pass/fail statistics - entirely in the database, avoiding the need to load findings into memory. - - Args: - tenant_id (str): The tenant ID for Row-Level Security context. - scan_id (str): The ID of the scan to retrieve findings for. - - Returns: - dict[str, dict[str, int]]: Dictionary mapping check_id to statistics: - - 'passed' (int): Number of passed findings for this check - - 'total' (int): Total number of findings for this check - - Example: - { - 'aws_iam_user_mfa_enabled': {'passed': 10, 'total': 15}, - 'aws_s3_bucket_public_access': {'passed': 0, 'total': 5} - } - """ - requirement_statistics_by_check_id = {} - - with rls_transaction(tenant_id, using=READ_REPLICA_ALIAS): - # Use database aggregation to calculate stats without loading findings into memory - aggregated_statistics_queryset = ( - Finding.all_objects.filter(tenant_id=tenant_id, scan_id=scan_id) - .values("check_id") - .annotate( - total_findings=Count("id"), - passed_findings=Count("id", filter=Q(status=StatusChoices.PASS)), - ) - ) - - for aggregated_stat in aggregated_statistics_queryset: - check_id = aggregated_stat["check_id"] - requirement_statistics_by_check_id[check_id] = { - "passed": aggregated_stat["passed_findings"], - "total": aggregated_stat["total_findings"], - } - - logger.info( - f"Aggregated statistics for {len(requirement_statistics_by_check_id)} unique checks" - ) - return requirement_statistics_by_check_id - - def _load_findings_for_requirement_checks( tenant_id: str, scan_id: str, check_ids: list[str], prowler_provider ) -> dict[str, list[FindingOutput]]: @@ -544,84 +504,6 @@ def _load_findings_for_requirement_checks( return dict(findings_by_check_id) -def _calculate_requirements_data_from_statistics( - compliance_obj, requirement_statistics_by_check_id: dict[str, dict[str, int]] -) -> tuple[dict[str, dict], list[dict]]: - """ - Calculate requirement status and statistics using pre-aggregated database statistics. - - This function uses O(n) lookups with pre-aggregated statistics from the database, - avoiding the need to iterate over all findings for each requirement. - - Args: - compliance_obj: The compliance framework object containing requirements. - requirement_statistics_by_check_id (dict[str, dict[str, int]]): Pre-aggregated statistics - mapping check_id to {'passed': int, 'total': int} counts. - - Returns: - tuple[dict[str, dict], list[dict]]: A tuple containing: - - attributes_by_requirement_id: Dictionary mapping requirement IDs to their attributes. - - requirements_list: List of requirement dictionaries with status and statistics. - """ - attributes_by_requirement_id = {} - requirements_list = [] - - compliance_framework = getattr(compliance_obj, "Framework", "N/A") - compliance_version = getattr(compliance_obj, "Version", "N/A") - - for requirement in compliance_obj.Requirements: - requirement_id = requirement.Id - requirement_description = getattr(requirement, "Description", "") - requirement_checks = getattr(requirement, "Checks", []) - requirement_attributes = getattr(requirement, "Attributes", []) - - # Store requirement metadata for later use - attributes_by_requirement_id[requirement_id] = { - "attributes": { - "req_attributes": requirement_attributes, - "checks": requirement_checks, - }, - "description": requirement_description, - } - - # Calculate aggregated passed and total findings for this requirement - total_passed_findings = 0 - total_findings_count = 0 - - for check_id in requirement_checks: - if check_id in requirement_statistics_by_check_id: - check_statistics = requirement_statistics_by_check_id[check_id] - total_findings_count += check_statistics["total"] - total_passed_findings += check_statistics["passed"] - - # Determine overall requirement status based on findings - if total_findings_count > 0: - if total_passed_findings == total_findings_count: - requirement_status = StatusChoices.PASS - else: - # Partial pass or complete fail both count as FAIL - requirement_status = StatusChoices.FAIL - else: - # No findings means manual review required - requirement_status = StatusChoices.MANUAL - - requirements_list.append( - { - "id": requirement_id, - "attributes": { - "framework": compliance_framework, - "version": compliance_version, - "status": requirement_status, - "description": requirement_description, - "passed_findings": total_passed_findings, - "total_findings": total_findings_count, - }, - } - ) - - return attributes_by_requirement_id, requirements_list - - def generate_threatscore_report( tenant_id: str, scan_id: str, @@ -1262,8 +1144,9 @@ def generate_threatscore_report_job( 2. Checks provider type compatibility 3. Generates the output directory 4. Calls generate_threatscore_report to create the PDF - 5. Uploads the PDF to S3 - 6. Cleans up temporary files + 5. Computes and stores ThreatScore metrics snapshot + 6. Uploads the PDF to S3 + 7. Cleans up temporary files Args: tenant_id (str): The tenant ID for Row-Level Security context. @@ -1317,6 +1200,66 @@ def generate_threatscore_report_job( min_risk_level=4, ) + # Compute and store ThreatScore metrics snapshot + logger.info(f"Computing ThreatScore metrics for scan {scan_id}") + try: + metrics = compute_threatscore_metrics( + tenant_id=tenant_id, + scan_id=scan_id, + provider_id=provider_id, + compliance_id=compliance_id, + min_risk_level=4, + ) + + # Create snapshot in database + with rls_transaction(tenant_id): + # Get previous snapshot for the same provider to calculate delta + previous_snapshot = ( + ThreatScoreSnapshot.objects.filter( + tenant_id=tenant_id, + provider_id=provider_id, + compliance_id=compliance_id, + ) + .order_by("-inserted_at") + .first() + ) + + # Calculate score delta (improvement) + score_delta = None + if previous_snapshot: + score_delta = metrics["overall_score"] - float( + previous_snapshot.overall_score + ) + + snapshot = ThreatScoreSnapshot.objects.create( + tenant_id=tenant_id, + scan_id=scan_id, + provider_id=provider_id, + compliance_id=compliance_id, + overall_score=metrics["overall_score"], + score_delta=score_delta, + section_scores=metrics["section_scores"], + critical_requirements=metrics["critical_requirements"], + total_requirements=metrics["total_requirements"], + passed_requirements=metrics["passed_requirements"], + failed_requirements=metrics["failed_requirements"], + manual_requirements=metrics["manual_requirements"], + total_findings=metrics["total_findings"], + passed_findings=metrics["passed_findings"], + failed_findings=metrics["failed_findings"], + ) + + delta_msg = ( + f" (delta: {score_delta:+.2f}%)" if score_delta is not None else "" + ) + logger.info( + f"ThreatScore snapshot created with ID {snapshot.id} " + f"(score: {snapshot.overall_score}%{delta_msg})" + ) + except Exception as e: + # Log error but don't fail the job if snapshot creation fails + logger.error(f"Error creating ThreatScore snapshot: {e}") + upload_uri = _upload_to_s3( tenant_id, scan_id, diff --git a/api/src/backend/tasks/jobs/scan.py b/api/src/backend/tasks/jobs/scan.py index cdfaf9e0e3..c4cf413301 100644 --- a/api/src/backend/tasks/jobs/scan.py +++ b/api/src/backend/tasks/jobs/scan.py @@ -1,23 +1,21 @@ import csv import io import json +import re import time import uuid from collections import defaultdict -from copy import deepcopy from datetime import datetime, timezone from typing import Any from celery.utils.log import get_task_logger +from config.env import env from config.settings.celery import CELERY_DEADLOCK_ATTEMPTS from django.db import IntegrityError, OperationalError from django.db.models import Case, Count, IntegerField, Prefetch, Sum, When from tasks.utils import CustomEncoder -from api.compliance import ( - PROWLER_COMPLIANCE_OVERVIEW_TEMPLATE, - generate_scan_compliance, -) +from api.compliance import PROWLER_COMPLIANCE_OVERVIEW_TEMPLATE from api.db_router import READ_REPLICA_ALIAS, MainRouter from api.db_utils import ( POSTGRES_TENANT_VAR, @@ -28,12 +26,14 @@ from api.db_utils import ( ) from api.exceptions import ProviderConnectionError from api.models import ( + ComplianceOverviewSummary, ComplianceRequirementOverview, Finding, MuteRule, Processor, Provider, Resource, + ResourceFindingMapping, ResourceScanSummary, ResourceTag, Scan, @@ -69,6 +69,10 @@ COMPLIANCE_REQUIREMENT_COPY_COLUMNS = ( "total_findings", "scan_id", ) +# Controls how many findings we process per micro-batch before flushing to DB writes +FINDINGS_MICRO_BATCH_SIZE = env.int("DJANGO_FINDINGS_MICRO_BATCH_SIZE", default=3000) +# Controls how many rows each ORM bulk_create/bulk_update call sends to Postgres +SCAN_DB_BATCH_SIZE = env.int("DJANGO_SCAN_DB_BATCH_SIZE", default=500) def _create_finding_delta( @@ -201,25 +205,43 @@ def _copy_compliance_requirement_rows( def _persist_compliance_requirement_rows( - tenant_id: str, rows: list[dict[str, Any]] + tenant_id: str, rows: list[dict[str, Any]], batch_size: int = 10000 ) -> None: - """Persist compliance requirement rows using COPY with ORM fallback. + """Persist compliance requirement rows using batched COPY with ORM fallback. + + Splits large row sets into batches to reduce lock duration and improve concurrency. Args: tenant_id: Target tenant UUID. rows: Precomputed row dictionaries that reflect the compliance overview state for a scan. + batch_size: Number of rows per COPY batch (default: 10000). """ if not rows: return + total_rows = len(rows) + total_batches = (total_rows + batch_size - 1) // batch_size + try: - _copy_compliance_requirement_rows(tenant_id, rows) + # Process rows in batches to reduce lock duration + for batch_num in range(total_batches): + start_idx = batch_num * batch_size + end_idx = min(start_idx + batch_size, total_rows) + batch = rows[start_idx:end_idx] + + _copy_compliance_requirement_rows(tenant_id, batch) + + logger.info( + f"Compliance COPY batch {batch_num + 1}/{total_batches}: " + f"inserted {len(batch)} rows ({start_idx + len(batch)}/{total_rows} total)" + ) except Exception as error: logger.exception( "COPY bulk insert for compliance requirements failed; falling back to ORM bulk_create", exc_info=error, ) + # Fallback: use ORM bulk_create for all remaining rows fallback_objects = [ ComplianceRequirementOverview( id=row["id"], @@ -247,12 +269,367 @@ def _persist_compliance_requirement_rows( ) +def _create_compliance_summaries( + tenant_id: str, scan_id: str, requirement_statuses: dict +) -> None: + """ + Create pre-aggregated compliance summaries from pre-computed requirement statuses. + + This computes the overall compliance scores across all regions for fast + lookup in the main compliance overview endpoint. + + Args: + tenant_id: Target tenant UUID + scan_id: Scan UUID + requirement_statuses: Pre-computed dict of {(compliance_id, requirement_id): {fail_count, pass_count, total_count}} + """ + # Determine per-requirement status and aggregate to compliance level + compliance_summaries = defaultdict( + lambda: { + "total_requirements": 0, + "requirements_passed": 0, + "requirements_failed": 0, + "requirements_manual": 0, + } + ) + + for (compliance_id, requirement_id), counts in requirement_statuses.items(): + # Apply business rule: any FAIL → requirement fails + if counts["fail_count"] > 0: + req_status = "FAIL" + elif counts["pass_count"] == counts["total_count"]: + req_status = "PASS" + else: + req_status = "MANUAL" + + # Aggregate to compliance level + compliance_summaries[compliance_id]["total_requirements"] += 1 + if req_status == "PASS": + compliance_summaries[compliance_id]["requirements_passed"] += 1 + elif req_status == "FAIL": + compliance_summaries[compliance_id]["requirements_failed"] += 1 + else: + compliance_summaries[compliance_id]["requirements_manual"] += 1 + + # Create summary objects + summary_objects = [] + for compliance_id, data in compliance_summaries.items(): + summary_objects.append( + ComplianceOverviewSummary( + tenant_id=tenant_id, + scan_id=scan_id, + compliance_id=compliance_id, + requirements_passed=data["requirements_passed"], + requirements_failed=data["requirements_failed"], + requirements_manual=data["requirements_manual"], + total_requirements=data["total_requirements"], + ) + ) + + # Bulk insert summaries + if summary_objects: + with rls_transaction(tenant_id): + ComplianceOverviewSummary.objects.bulk_create( + summary_objects, batch_size=500 + ) + + def _normalized_compliance_key(framework: str | None, version: str | None) -> str: """Return normalized identifier used to group compliance totals.""" - normalized_framework = (framework or "").lower().replace("-", "").replace("_", "") - normalized_version = (version or "").lower().replace("-", "").replace("_", "") - return f"{normalized_framework}{normalized_version}" + def _normalize(value: str | None) -> str: + if not value: + return "" + return re.sub(r"[^a-z0-9]", "", value.lower()) + + return f"{_normalize(framework)}{_normalize(version)}" + + +def _process_finding_micro_batch( + tenant_id: str, + findings_batch: list[ProwlerFinding], + scan_instance: Scan, + provider_instance: Provider, + resource_cache: dict, + tag_cache: dict, + last_status_cache: dict, + resource_failed_findings_cache: dict, + unique_resources: set, + scan_resource_cache: set, + mute_rules_cache: dict, +) -> None: + """ + Process a micro-batch of findings and persist them using bulk operations. + + Each batch reuses caches (resources, tags, last statuses, mute rules) to avoid + redundant queries, updates denormalized resource data, and writes findings plus + resource mappings in as few transactions as possible. + + Args: + tenant_id: Tenant owning the scan. + findings_batch: Findings yielded by the Prowler scanner for this slice. + scan_instance: Scan ORM instance being updated. + provider_instance: Provider tied to the scan. + resource_cache: In-memory cache of provider resources indexed by UID. + tag_cache: Cache of `ResourceTag` instances keyed by (key, value). + last_status_cache: Cache of prior finding statuses keyed by finding UID. + resource_failed_findings_cache: Mutable counter of failed findings per resource. + unique_resources: Set tracking (uid, region) pairs seen in the scan. + scan_resource_cache: Set of tuples used to create `ResourceScanSummary` rows. + mute_rules_cache: Map of finding UID -> mute reason gathered before the scan. + """ + # Accumulate objects for bulk operations + findings_to_create = [] + mappings_to_create = [] + dirty_resources = {} + resource_denormalized_data = [] # (finding_instance, resource_instance) pairs + skipped_findings_count = 0 # Track findings skipped due to UID length + + # Prefetch last statuses for all findings in this batch + # TEMPORARY WORKAROUND: Filter out UIDs > 300 chars to avoid query errors + finding_uids = [ + f.uid for f in findings_batch if f is not None and len(f.uid) <= 300 + ] + with rls_transaction(tenant_id, using=READ_REPLICA_ALIAS): + last_statuses = { + item["uid"]: (item["status"], item["first_seen_at"]) + for item in Finding.all_objects.filter( + tenant_id=tenant_id, uid__in=finding_uids + ) + .values("uid", "status", "first_seen_at") + .order_by("uid", "-inserted_at") + .distinct("uid") + } + # Update cache + for uid, data in last_statuses.items(): + if uid not in last_status_cache: + last_status_cache[uid] = data + + # Process each finding in the batch + for finding in findings_batch: + if finding is None: + logger.error(f"None finding detected on scan {scan_instance.id}.") + continue + + # Process resource with deadlock retry + for attempt in range(CELERY_DEADLOCK_ATTEMPTS): + try: + with rls_transaction(tenant_id): + resource_uid = finding.resource_uid + if resource_uid not in resource_cache: + resource_instance, _ = Resource.objects.get_or_create( + tenant_id=tenant_id, + provider=provider_instance, + uid=resource_uid, + defaults={ + "region": finding.region, + "service": finding.service_name, + "type": finding.resource_type, + "name": finding.resource_name, + }, + ) + resource_cache[resource_uid] = resource_instance + resource_failed_findings_cache[resource_uid] = 0 + else: + resource_instance = resource_cache[resource_uid] + break + except (OperationalError, IntegrityError) as db_err: + if attempt < CELERY_DEADLOCK_ATTEMPTS - 1: + logger.warning( + f"{'Deadlock error' if isinstance(db_err, OperationalError) else 'Integrity error'} " + f"detected when processing resource {resource_uid} on scan {scan_instance.id}. Retrying..." + ) + time.sleep(0.1 * (2**attempt)) + continue + else: + raise db_err + + # Track resource field changes (defer save) + updated = False + if finding.region and resource_instance.region != finding.region: + resource_instance.region = finding.region + updated = True + if resource_instance.service != finding.service_name: + resource_instance.service = finding.service_name + updated = True + if resource_instance.type != finding.resource_type: + resource_instance.type = finding.resource_type + updated = True + if resource_instance.metadata != finding.resource_metadata: + resource_instance.metadata = json.dumps( + finding.resource_metadata, cls=CustomEncoder + ) + updated = True + if resource_instance.details != finding.resource_details: + resource_instance.details = finding.resource_details + updated = True + if resource_instance.partition != finding.partition: + resource_instance.partition = finding.partition + updated = True + + if updated: + dirty_resources[resource_uid] = resource_instance + + # Process tags + tags = [] + with rls_transaction(tenant_id): + for key, value in finding.resource_tags.items(): + tag_key = (key, value) + if tag_key not in tag_cache: + tag_instance, _ = ResourceTag.objects.get_or_create( + tenant_id=tenant_id, key=key, value=value + ) + tag_cache[tag_key] = tag_instance + else: + tag_instance = tag_cache[tag_key] + tags.append(tag_instance) + resource_instance.upsert_or_delete_tags(tags=tags) + + unique_resources.add((resource_instance.uid, resource_instance.region)) + + # Prepare finding data + finding_uid = finding.uid + + # TEMPORARY WORKAROUND: Skip findings with UID > 300 chars + # TODO: Remove this after implementing text field migration for finding.uid + if len(finding_uid) > 300: + skipped_findings_count += 1 + logger.warning( + f"Skipping finding with UID exceeding 300 characters. " + f"Length: {len(finding_uid)}, " + f"Check: {finding.check_id}, " + f"Resource: {finding.resource_name}, " + f"UID: {finding_uid}" + ) + continue + + last_status, last_first_seen_at = last_status_cache.get( + finding_uid, (None, None) + ) + + status = FindingStatus[finding.status] + delta = _create_finding_delta(last_status, status) + + if not last_first_seen_at: + last_first_seen_at = datetime.now(tz=timezone.utc) + + # Determine if finding should be muted and why + # Priority: mutelist processor (highest) > manual mute rules + is_muted = False + muted_reason = None + + # Check mutelist processor first (highest priority) + if finding.muted: + is_muted = True + muted_reason = "Muted by mutelist" + # If not muted by mutelist, check manual mute rules + elif finding_uid in mute_rules_cache: + is_muted = True + muted_reason = mute_rules_cache[finding_uid] + + # Increment failed_findings_count cache if needed + if status == FindingStatus.FAIL and not is_muted: + resource_failed_findings_cache[resource_uid] += 1 + + # Create finding object (don't save yet) + finding_instance = Finding( + tenant_id=tenant_id, + uid=finding_uid, + delta=delta, + check_metadata=finding.get_metadata(), + status=status, + status_extended=finding.status_extended, + severity=finding.severity, + impact=finding.severity, + raw_result=finding.raw, + check_id=finding.check_id, + scan=scan_instance, + first_seen_at=last_first_seen_at, + muted=is_muted, + muted_at=datetime.now(tz=timezone.utc) if is_muted else None, + muted_reason=muted_reason, + compliance=finding.compliance, + ) + findings_to_create.append(finding_instance) + resource_denormalized_data.append((finding_instance, resource_instance)) + + # Track for scan summary + scan_resource_cache.add( + ( + str(resource_instance.id), + resource_instance.service, + resource_instance.region, + resource_instance.type, + ) + ) + + # Bulk operations within single transaction + with rls_transaction(tenant_id): + # Bulk create findings + if findings_to_create: + Finding.objects.bulk_create( + findings_to_create, batch_size=SCAN_DB_BATCH_SIZE + ) + + # Bulk create resource-finding mappings + for finding_instance, resource_instance in resource_denormalized_data: + mappings_to_create.append( + ResourceFindingMapping( + tenant_id=tenant_id, + resource=resource_instance, + finding=finding_instance, + ) + ) + + if mappings_to_create: + ResourceFindingMapping.objects.bulk_create( + mappings_to_create, + batch_size=SCAN_DB_BATCH_SIZE, + ignore_conflicts=True, + ) + + # Update finding denormalized arrays + findings_to_update = [] + for finding_instance, resource_instance in resource_denormalized_data: + if not finding_instance.resource_regions: + finding_instance.resource_regions = [] + if not finding_instance.resource_services: + finding_instance.resource_services = [] + if not finding_instance.resource_types: + finding_instance.resource_types = [] + + if resource_instance.region not in finding_instance.resource_regions: + finding_instance.resource_regions.append(resource_instance.region) + if resource_instance.service not in finding_instance.resource_services: + finding_instance.resource_services.append(resource_instance.service) + if resource_instance.type not in finding_instance.resource_types: + finding_instance.resource_types.append(resource_instance.type) + + findings_to_update.append(finding_instance) + + if findings_to_update: + Finding.objects.bulk_update( + findings_to_update, + ["resource_regions", "resource_services", "resource_types"], + batch_size=SCAN_DB_BATCH_SIZE, + ) + + # Bulk update dirty resources + if dirty_resources: + update_objects_in_batches( + tenant_id=tenant_id, + model=Resource, + objects=list(dirty_resources.values()), + fields=["metadata", "details", "partition", "region", "service", "type"], + batch_size=1000, + ) + + # Log skipped findings summary + if skipped_findings_count > 0: + logger.warning( + f"Scan {scan_instance.id}: Skipped {skipped_findings_count} finding(s) " + f"due to UID length exceeding 300 characters in this micro-batch." + ) def perform_prowler_scan( @@ -262,20 +639,25 @@ def perform_prowler_scan( checks_to_execute: list[str] | None = None, ): """ - Perform a scan using Prowler and store the findings and resources in the database. + Run a Prowler scan and persist all generated resources, findings, and summaries. + + The scan stream is processed in micro-batches to keep memory bounded while still + benefiting from bulk writes. When the scan completes we also derive + `ResourceScanSummary` rows and return the serialized `Scan` payload used by the + API layer. Args: - tenant_id (str): The ID of the tenant for which the scan is performed. - scan_id (str): The ID of the scan instance. - provider_id (str): The ID of the provider to scan. - checks_to_execute (list[str], optional): A list of specific checks to execute. Defaults to None. + tenant_id: Tenant that owns the scan. + scan_id: UUID of the `Scan` row being executed. + provider_id: Provider to authenticate against. + checks_to_execute: Optional subset of check IDs to run. Returns: - dict: Serialized data of the completed scan instance. + Serialized `ScanTaskSerializer` data for the updated scan. Raises: - ValueError: If the provider cannot be connected. - + ProviderConnectionError: If the provider cannot be validated before scanning. + Exception: Any downstream persistence/processing error (re-raised after cleanup). """ exception = None unique_resources = set() @@ -316,6 +698,7 @@ def perform_prowler_scan( except Exception as e: logger.error(f"Error loading mute rules: {e}") mute_rules_cache = {} + try: with rls_transaction(tenant_id): try: @@ -348,171 +731,26 @@ def perform_prowler_scan( resource_failed_findings_cache = defaultdict(int) for progress, findings in prowler_scan.scan(): - for finding in findings: - if finding is None: - logger.error(f"None finding detected on scan {scan_id}.") - continue - for attempt in range(CELERY_DEADLOCK_ATTEMPTS): - try: - with rls_transaction(tenant_id): - # Process resource - resource_uid = finding.resource_uid - if resource_uid not in resource_cache: - # Get or create the resource - resource_instance, _ = Resource.objects.get_or_create( - tenant_id=tenant_id, - provider=provider_instance, - uid=resource_uid, - defaults={ - "region": finding.region, - "service": finding.service_name, - "type": finding.resource_type, - "name": finding.resource_name, - }, - ) - resource_cache[resource_uid] = resource_instance + # Process findings in micro-batches + findings_list = list(findings) + total_findings = len(findings_list) - # Initialize all processed resources in the cache - resource_failed_findings_cache[resource_uid] = 0 - else: - resource_instance = resource_cache[resource_uid] + # Chunk findings into micro-batches + for i in range(0, total_findings, FINDINGS_MICRO_BATCH_SIZE): + micro_batch = findings_list[i : i + FINDINGS_MICRO_BATCH_SIZE] - # Update resource fields if necessary - updated_fields = [] - if ( - finding.region - and resource_instance.region != finding.region - ): - resource_instance.region = finding.region - updated_fields.append("region") - if resource_instance.service != finding.service_name: - resource_instance.service = finding.service_name - updated_fields.append("service") - if resource_instance.type != finding.resource_type: - resource_instance.type = finding.resource_type - updated_fields.append("type") - if resource_instance.metadata != finding.resource_metadata: - resource_instance.metadata = json.dumps( - finding.resource_metadata, cls=CustomEncoder - ) - updated_fields.append("metadata") - if resource_instance.details != finding.resource_details: - resource_instance.details = finding.resource_details - updated_fields.append("details") - if resource_instance.partition != finding.partition: - resource_instance.partition = finding.partition - updated_fields.append("partition") - if updated_fields: - with rls_transaction(tenant_id): - resource_instance.save(update_fields=updated_fields) - except (OperationalError, IntegrityError) as db_err: - if attempt < CELERY_DEADLOCK_ATTEMPTS - 1: - logger.warning( - f"{'Deadlock error' if isinstance(db_err, OperationalError) else 'Integrity error'} " - f"detected when processing resource {resource_uid} on scan {scan_id}. Retrying..." - ) - time.sleep(0.1 * (2**attempt)) - continue - else: - raise db_err - - # Update tags - tags = [] - with rls_transaction(tenant_id): - for key, value in finding.resource_tags.items(): - tag_key = (key, value) - if tag_key not in tag_cache: - tag_instance, _ = ResourceTag.objects.get_or_create( - tenant_id=tenant_id, key=key, value=value - ) - tag_cache[tag_key] = tag_instance - else: - tag_instance = tag_cache[tag_key] - tags.append(tag_instance) - resource_instance.upsert_or_delete_tags(tags=tags) - - unique_resources.add((resource_instance.uid, resource_instance.region)) - - # Process finding - with rls_transaction(tenant_id, using=READ_REPLICA_ALIAS): - finding_uid = finding.uid - last_first_seen_at = None - if finding_uid not in last_status_cache: - most_recent_finding = ( - Finding.all_objects.filter( - tenant_id=tenant_id, uid=finding_uid - ) - .order_by("-inserted_at") - .values("status", "first_seen_at") - .first() - ) - last_status = None - if most_recent_finding: - last_status = most_recent_finding["status"] - last_first_seen_at = most_recent_finding["first_seen_at"] - last_status_cache[finding_uid] = last_status, last_first_seen_at - else: - last_status, last_first_seen_at = last_status_cache[finding_uid] - - status = FindingStatus[finding.status] - delta = _create_finding_delta(last_status, status) - # For the findings prior to the change, when a first finding is found with delta!="new" it will be - # assigned a current date as first_seen_at and the successive findings with the same UID will - # always get the date of the previous finding. - # For new findings, when a finding (delta="new") is found for the first time, the first_seen_at - # attribute will be assigned the current date, the following findings will get that date. - if not last_first_seen_at: - last_first_seen_at = datetime.now(tz=timezone.utc) - - # Determine if finding should be muted and why - # Priority: mutelist processor (highest) > manual mute rules - is_muted = False - muted_reason = None - - # Check mutelist processor first (highest priority) - if finding.muted: - is_muted = True - muted_reason = "Muted by mutelist" - # If not muted by mutelist, check manual mute rules - elif finding_uid in mute_rules_cache: - is_muted = True - muted_reason = mute_rules_cache[finding_uid] - - # Increment failed_findings_count cache if the finding status is FAIL and not muted - if status == FindingStatus.FAIL and not is_muted: - resource_uid = finding.resource_uid - resource_failed_findings_cache[resource_uid] += 1 - - with rls_transaction(tenant_id): - # Create the finding - finding_instance = Finding.objects.create( - tenant_id=tenant_id, - uid=finding_uid, - delta=delta, - check_metadata=finding.get_metadata(), - status=status, - status_extended=finding.status_extended, - severity=finding.severity, - impact=finding.severity, - raw_result=finding.raw, - check_id=finding.check_id, - scan=scan_instance, - first_seen_at=last_first_seen_at, - muted=is_muted, - muted_at=datetime.now(tz=timezone.utc) if is_muted else None, - muted_reason=muted_reason, - compliance=finding.compliance, - ) - finding_instance.add_resources([resource_instance]) - - # Update scan resource summaries - scan_resource_cache.add( - ( - str(resource_instance.id), - resource_instance.service, - resource_instance.region, - resource_instance.type, - ) + _process_finding_micro_batch( + tenant_id=tenant_id, + findings_batch=micro_batch, + scan_instance=scan_instance, + provider_instance=provider_instance, + resource_cache=resource_cache, + tag_cache=tag_cache, + last_status_cache=last_status_cache, + resource_failed_findings_cache=resource_failed_findings_cache, + unique_resources=unique_resources, + scan_resource_cache=scan_resource_cache, + mute_rules_cache=mute_rules_cache, ) # Update scan progress @@ -585,34 +823,15 @@ def perform_prowler_scan( def aggregate_findings(tenant_id: str, scan_id: str): """ - Aggregates findings for a given scan and stores the results in the ScanSummary table. + Aggregate findings for a scan and populate `ScanSummary` rows. - This function retrieves all findings associated with a given `scan_id` and calculates various - metrics such as counts of failed, passed, and muted findings, as well as their deltas (new, - changed, unchanged). The results are grouped by `check_id`, `service`, `severity`, and `region`. - These aggregated metrics are then stored in the `ScanSummary` table. - - Additionally, it updates the failed_findings_count field for each resource based on the most - recent findings for each finding.uid. + We group findings by check/service/severity/region and compute pass/fail/muted + totals plus delta counts (new/changed/unchanged). The summary dataset feeds the + overview API and dashboards, so it is recomputed every time a scan finishes. Args: - tenant_id (str): The ID of the tenant to which the scan belongs. - scan_id (str): The ID of the scan for which findings need to be aggregated. - - Aggregated Metrics: - - fail: Total number of failed findings. - - _pass: Total number of passed findings. - - muted: Total number of muted findings. - - total: Total number of findings. - - new: Total number of new findings. - - changed: Total number of changed findings. - - unchanged: Total number of unchanged findings. - - fail_new: Failed findings with a delta of 'new'. - - fail_changed: Failed findings with a delta of 'changed'. - - pass_new: Passed findings with a delta of 'new'. - - pass_changed: Passed findings with a delta of 'changed'. - - muted_new: Muted findings with a delta of 'new'. - - muted_changed: Muted findings with a delta of 'changed'. + tenant_id: Tenant that owns the scan. + scan_id: Scan UUID whose findings should be aggregated. """ with rls_transaction(tenant_id, using=READ_REPLICA_ALIAS): findings = Finding.objects.filter(tenant_id=tenant_id, scan_id=scan_id) @@ -738,50 +957,34 @@ def aggregate_findings(tenant_id: str, scan_id: str): ScanSummary.objects.bulk_create(scan_aggregations, batch_size=3000) -def create_compliance_requirements(tenant_id: str, scan_id: str): +def _aggregate_findings_by_region( + tenant_id: str, scan_id: str, modeled_threatscore_compliance_id: str +) -> tuple[dict, dict]: """ - Create detailed compliance requirement overview records for a scan. + Aggregate findings by region using optimized ORM queries. - This function processes the compliance data collected during a scan and creates - individual records for each compliance requirement in each region. These detailed - records provide a granular view of compliance status. + Replaces nested Python loops with efficient queries and aggregation. Args: - tenant_id (str): The ID of the tenant for which to create records. - scan_id (str): The ID of the scan for which to create records. + tenant_id: Tenant UUID + scan_id: Scan UUID + modeled_threatscore_compliance_id: ID for ThreatScore compliance framework Returns: - dict: A dictionary containing the number of requirements created and the regions processed. - - Raises: - ValidationError: If tenant_id is not a valid UUID. + tuple: (check_status_by_region, findings_count_by_compliance) + - check_status_by_region: {region: {check_id: status}} + - findings_count_by_compliance: {region: {normalized_id: {requirement_id: {total, pass}}}} """ - try: - with rls_transaction(tenant_id, using=READ_REPLICA_ALIAS): - scan_instance = Scan.objects.get(pk=scan_id) - provider_instance = scan_instance.provider - prowler_provider = return_prowler_provider(provider_instance) + check_status_by_region = {} + findings_count_by_compliance = {} - compliance_template = PROWLER_COMPLIANCE_OVERVIEW_TEMPLATE[ - provider_instance.provider - ] - modeled_threatscore_compliance_id = "ProwlerThreatScore-1.0" - threatscore_requirements_by_check: dict[str, set[str]] = {} - threatscore_framework = compliance_template.get( - modeled_threatscore_compliance_id - ) - if threatscore_framework: - for requirement_id, requirement in threatscore_framework[ - "requirements" - ].items(): - for check_id in requirement["checks"]: - threatscore_requirements_by_check.setdefault(check_id, set()).add( - requirement_id - ) - - # Get check status data by region from findings + with rls_transaction(tenant_id, using=READ_REPLICA_ALIAS): + # Fetch findings with resources in a single efficient query + # Use select_related for finding fields and prefetch_related for many-to-many resources findings = ( - Finding.all_objects.filter(scan_id=scan_id, muted=False) + Finding.all_objects.filter( + tenant_id=tenant_id, scan_id=scan_id, muted=False + ) .only("id", "check_id", "status", "compliance") .prefetch_related( Prefetch( @@ -790,117 +993,198 @@ def create_compliance_requirements(tenant_id: str, scan_id: str): to_attr="small_resources", ) ) - .iterator(chunk_size=1000) ) - findings_count_by_compliance = {} - check_status_by_region = {} + # Process findings in a single pass (more efficient than original nested loops) + normalized_id = re.sub( + r"[^a-z0-9]", "", modeled_threatscore_compliance_id.lower() + ) + + for finding in findings: + for resource in finding.small_resources: + region = resource.region + + # Aggregate check status by region + current_status = check_status_by_region.setdefault(region, {}) + # Priority: FAIL > any other status + if current_status.get(finding.check_id) != "FAIL": + current_status[finding.check_id] = finding.status + + # Aggregate ThreatScore compliance counts + if modeled_threatscore_compliance_id in (finding.compliance or {}): + compliance_key = findings_count_by_compliance.setdefault( + region, {} + ).setdefault(normalized_id, {}) + + for requirement_id in finding.compliance[ + modeled_threatscore_compliance_id + ]: + requirement_stats = compliance_key.setdefault( + requirement_id, {"total": 0, "pass": 0} + ) + requirement_stats["total"] += 1 + if finding.status == "PASS": + requirement_stats["pass"] += 1 + + return check_status_by_region, findings_count_by_compliance + + +def create_compliance_requirements(tenant_id: str, scan_id: str): + """ + Materialize per-requirement compliance rows (and summaries) for a scan. + + Using the provider’s compliance template plus the scan’s findings, we compute a + row per (region, compliance, requirement) and write it to + `ComplianceRequirementOverview` via COPY. The same pass tally requirement + statuses so we can persist `ComplianceOverviewSummary` records for the fast + overview endpoint. + + Args: + tenant_id: Tenant running the scan. + scan_id: Scan identifier whose findings should be translated into compliance data. + + Returns: + dict: Counts/metadata about the generated rows (e.g., frameworks touched, regions processed). + """ + try: with rls_transaction(tenant_id, using=READ_REPLICA_ALIAS): - for finding in findings: - for resource in finding.small_resources: - region = resource.region - current_status = check_status_by_region.setdefault(region, {}) - if current_status.get(finding.check_id) != "FAIL": - current_status[finding.check_id] = finding.status - if modeled_threatscore_compliance_id in finding.compliance: - for requirement_id in finding.compliance[ - modeled_threatscore_compliance_id - ]: - compliance_key = findings_count_by_compliance.setdefault( - region, {} - ).setdefault( - modeled_threatscore_compliance_id.lower().replace( - "-", "" - ), - {}, - ) - if requirement_id not in compliance_key: - compliance_key[requirement_id] = { - "total": 0, - "pass": 0, - } + scan_instance = Scan.objects.get(pk=scan_id) + provider_instance = scan_instance.provider + return_prowler_provider(provider_instance) - compliance_key[requirement_id]["total"] += 1 - if finding.status == "PASS": - compliance_key[requirement_id]["pass"] += 1 + compliance_template = PROWLER_COMPLIANCE_OVERVIEW_TEMPLATE[ + provider_instance.provider + ] + modeled_threatscore_compliance_id = "ProwlerThreatScore-1.0" - try: - # Try to get regions from provider - regions = prowler_provider.get_regions() - except (AttributeError, Exception): - # If not available, use regions from findings - regions = set(check_status_by_region.keys()) - - # Create compliance data by region - compliance_overview_by_region = { - region: deepcopy(compliance_template) for region in regions - } - - # Apply check statuses to compliance data - for region, check_status in check_status_by_region.items(): - compliance_data = compliance_overview_by_region.setdefault( - region, deepcopy(compliance_template) - ) - for check_name, status in check_status.items(): - generate_scan_compliance( - compliance_data, - provider_instance.provider, - check_name, - status, - ) - - # Prepare compliance requirement rows - compliance_requirement_rows: list[dict[str, Any]] = [] - utc_datetime_now = datetime.now(tz=timezone.utc) - for region, compliance_data in compliance_overview_by_region.items(): - for compliance_id, compliance in compliance_data.items(): - modeled_compliance_id = _normalized_compliance_key( - compliance["framework"], compliance["version"] - ) - # Create an overview record for each requirement within each compliance framework - for requirement_id, requirement in compliance["requirements"].items(): - checks_status = requirement["checks_status"] - compliance_requirement_rows.append( - { - "id": uuid.uuid4(), - "tenant_id": tenant_id, - "inserted_at": utc_datetime_now, - "compliance_id": compliance_id, - "framework": compliance["framework"], - "version": compliance["version"] or "", - "description": requirement.get("description") or "", - "region": region, - "requirement_id": requirement_id, - "requirement_status": requirement["status"], - "passed_checks": checks_status["pass"], - "failed_checks": checks_status["fail"], - "total_checks": checks_status["total"], - "scan_id": scan_instance.id, - "passed_findings": findings_count_by_compliance.get( - region, {} - ) - .get(modeled_compliance_id, {}) - .get(requirement_id, {}) - .get("pass", 0), - "total_findings": findings_count_by_compliance.get( - region, {} - ) - .get(modeled_compliance_id, {}) - .get(requirement_id, {}) - .get("total", 0), - } + requirement_lookup: dict[str, list[tuple[str, str]]] = {} + for compliance_id, compliance in compliance_template.items(): + for requirement_id, requirement in compliance["requirements"].items(): + for check_id in requirement["checks"].keys(): + requirement_lookup.setdefault(check_id, []).append( + (compliance_id, requirement_id) ) - # Bulk create requirement records using PostgreSQL COPY - _persist_compliance_requirement_rows(tenant_id, compliance_requirement_rows) + compliance_requirement_rows: list[dict[str, Any]] = [] + regions = [] + requirement_statuses = defaultdict( + lambda: {"fail_count": 0, "pass_count": 0, "total_count": 0} + ) + + # Skip if provider has no compliance frameworks + if compliance_template: + # Aggregate findings by region using SQL for optimal performance + check_status_by_region, findings_count_by_compliance = ( + _aggregate_findings_by_region( + tenant_id, scan_id, modeled_threatscore_compliance_id + ) + ) + + # Only process regions that have findings (optimization: reduces row count) + regions = list(check_status_by_region.keys()) + + region_requirement_stats: dict[ + str, dict[str, dict[str, dict[str, int]]] + ] = defaultdict(lambda: defaultdict(dict)) + for region, check_status in check_status_by_region.items(): + for check_name, status in check_status.items(): + targets = requirement_lookup.get(check_name) + if not targets: + continue + status_lower = (status or "").lower() + if status_lower not in {"pass", "fail"}: + continue + for compliance_id, requirement_id in targets: + compliance_stats = region_requirement_stats[region].setdefault( + compliance_id, {} + ) + requirement_stats = compliance_stats.setdefault( + requirement_id, {"passed_checks": 0, "failed_checks": 0} + ) + if status_lower == "pass": + requirement_stats["passed_checks"] += 1 + else: + requirement_stats["failed_checks"] += 1 + + # Prepare compliance requirement rows and compute summaries in single pass + utc_datetime_now = datetime.now(tz=timezone.utc) + + # Pre-compute shared strings (optimization: reduces string conversions) + tenant_id_str = str(tenant_id) + scan_id_str = str(scan_instance.id) + + for region in regions: + region_stats = region_requirement_stats.get(region, {}) + for compliance_id, compliance in compliance_template.items(): + modeled_compliance_id = _normalized_compliance_key( + compliance["framework"], compliance["version"] + ) + compliance_stats = region_stats.get(compliance_id, {}) + # Create an overview record for each requirement within each compliance framework + for requirement_id, requirement in compliance[ + "requirements" + ].items(): + stats = compliance_stats.get(requirement_id) + passed_checks = stats["passed_checks"] if stats else 0 + failed_checks = stats["failed_checks"] if stats else 0 + total_checks = len(requirement["checks"]) + if total_checks == 0: + requirement_status = "MANUAL" + elif failed_checks > 0: + requirement_status = "FAIL" + else: + requirement_status = "PASS" + + compliance_requirement_rows.append( + { + "id": uuid.uuid4(), + "tenant_id": tenant_id_str, + "inserted_at": utc_datetime_now, + "compliance_id": compliance_id, + "framework": compliance["framework"], + "version": compliance["version"] or "", + "description": requirement.get("description") or "", + "region": region, + "requirement_id": requirement_id, + "requirement_status": requirement_status, + "passed_checks": passed_checks, + "failed_checks": failed_checks, + "total_checks": total_checks, + "scan_id": scan_id_str, + "passed_findings": findings_count_by_compliance.get( + region, {} + ) + .get(modeled_compliance_id, {}) + .get(requirement_id, {}) + .get("pass", 0), + "total_findings": findings_count_by_compliance.get( + region, {} + ) + .get(modeled_compliance_id, {}) + .get(requirement_id, {}) + .get("total", 0), + } + ) + + # Update summary tracking (single-pass optimization) + key = (compliance_id, requirement_id) + requirement_statuses[key]["total_count"] += 1 + if requirement_status == "FAIL": + requirement_statuses[key]["fail_count"] += 1 + elif requirement_status == "PASS": + requirement_statuses[key]["pass_count"] += 1 + + # Bulk create requirement records using PostgreSQL COPY + _persist_compliance_requirement_rows(tenant_id, compliance_requirement_rows) + + # Create pre-aggregated summaries for fast compliance overview lookups + _create_compliance_summaries(tenant_id, scan_id, requirement_statuses) return { "requirements_created": len(compliance_requirement_rows), "regions_processed": list(regions), "compliance_frameworks": ( - list(compliance_overview_by_region.get(list(regions)[0], {}).keys()) - if regions - else [] + list(compliance_template.keys()) if regions else [] ), } diff --git a/api/src/backend/tasks/jobs/threatscore.py b/api/src/backend/tasks/jobs/threatscore.py new file mode 100644 index 0000000000..414f2d20f2 --- /dev/null +++ b/api/src/backend/tasks/jobs/threatscore.py @@ -0,0 +1,214 @@ +from celery.utils.log import get_task_logger +from tasks.jobs.threatscore_utils import ( + _aggregate_requirement_statistics_from_database, + _calculate_requirements_data_from_statistics, +) + +from api.db_router import READ_REPLICA_ALIAS +from api.db_utils import rls_transaction +from api.models import Provider, StatusChoices +from prowler.lib.check.compliance_models import Compliance + +logger = get_task_logger(__name__) + + +def compute_threatscore_metrics( + tenant_id: str, + scan_id: str, + provider_id: str, + compliance_id: str, + min_risk_level: int = 4, +) -> dict: + """ + Compute ThreatScore metrics for a given scan. + + This function calculates all the metrics needed for a ThreatScore snapshot: + - Overall ThreatScore percentage + - Section-by-section scores + - Critical failed requirements (risk >= min_risk_level) + - Summary statistics (requirements and findings counts) + + Args: + tenant_id (str): The tenant ID for Row-Level Security context. + scan_id (str): The ID of the scan to analyze. + provider_id (str): The ID of the provider used in the scan. + compliance_id (str): Compliance framework ID (e.g., "prowler_threatscore_aws"). + min_risk_level (int): Minimum risk level for critical requirements. Defaults to 4. + + Returns: + dict: A dictionary containing: + - overall_score (float): Overall ThreatScore percentage (0-100) + - section_scores (dict): Section name -> score percentage mapping + - critical_requirements (list): List of critical failed requirement dicts + - total_requirements (int): Total number of requirements + - passed_requirements (int): Number of PASS requirements + - failed_requirements (int): Number of FAIL requirements + - manual_requirements (int): Number of MANUAL requirements + - total_findings (int): Total findings count + - passed_findings (int): Passed findings count + - failed_findings (int): Failed findings count + + Example: + >>> metrics = compute_threatscore_metrics( + ... tenant_id="tenant-123", + ... scan_id="scan-456", + ... provider_id="provider-789", + ... compliance_id="prowler_threatscore_aws" + ... ) + >>> print(f"Overall ThreatScore: {metrics['overall_score']:.2f}%") + """ + # Get provider and compliance information + with rls_transaction(tenant_id, using=READ_REPLICA_ALIAS): + provider_obj = Provider.objects.get(id=provider_id) + provider_type = provider_obj.provider + + frameworks_bulk = Compliance.get_bulk(provider_type) + compliance_obj = frameworks_bulk[compliance_id] + + # Aggregate requirement statistics from database + requirement_statistics_by_check_id = ( + _aggregate_requirement_statistics_from_database(tenant_id, scan_id) + ) + + # Calculate requirements data using aggregated statistics + attributes_by_requirement_id, requirements_list = ( + _calculate_requirements_data_from_statistics( + compliance_obj, requirement_statistics_by_check_id + ) + ) + + # Initialize metrics + overall_numerator = 0 + overall_denominator = 0 + overall_has_findings = False + + sections_data = {} + + total_requirements = len(requirements_list) + passed_requirements = 0 + failed_requirements = 0 + manual_requirements = 0 + total_findings = 0 + passed_findings = 0 + failed_findings = 0 + + critical_requirements_list = [] + + # Process each requirement + for requirement in requirements_list: + requirement_id = requirement["id"] + requirement_status = requirement["attributes"]["status"] + requirement_attributes = attributes_by_requirement_id.get(requirement_id, {}) + + # Count requirements by status + if requirement_status == StatusChoices.PASS: + passed_requirements += 1 + elif requirement_status == StatusChoices.FAIL: + failed_requirements += 1 + elif requirement_status == StatusChoices.MANUAL: + manual_requirements += 1 + + # Get findings data + req_passed_findings = requirement["attributes"].get("passed_findings", 0) + req_total_findings = requirement["attributes"].get("total_findings", 0) + + # Accumulate findings counts + total_findings += req_total_findings + passed_findings += req_passed_findings + failed_findings += req_total_findings - req_passed_findings + + # Skip requirements with no findings + if req_total_findings == 0: + continue + + overall_has_findings = True + + # Get requirement metadata + metadata = requirement_attributes.get("attributes", {}).get( + "req_attributes", [] + ) + if not metadata or len(metadata) == 0: + continue + + m = metadata[0] + risk_level = getattr(m, "LevelOfRisk", 0) + weight = getattr(m, "Weight", 0) + section = getattr(m, "Section", "Unknown") + + # Calculate ThreatScore components using formula from UI + rate_i = req_passed_findings / req_total_findings + rfac_i = 1 + 0.25 * risk_level + + # Update overall score + overall_numerator += rate_i * req_total_findings * weight * rfac_i + overall_denominator += req_total_findings * weight * rfac_i + + # Update section scores + if section not in sections_data: + sections_data[section] = { + "numerator": 0, + "denominator": 0, + "has_findings": False, + } + + sections_data[section]["has_findings"] = True + sections_data[section]["numerator"] += ( + rate_i * req_total_findings * weight * rfac_i + ) + sections_data[section]["denominator"] += req_total_findings * weight * rfac_i + + # Identify critical failed requirements + if requirement_status == StatusChoices.FAIL and risk_level >= min_risk_level: + critical_requirements_list.append( + { + "requirement_id": requirement_id, + "title": getattr(m, "Title", "N/A"), + "section": section, + "subsection": getattr(m, "SubSection", "N/A"), + "risk_level": risk_level, + "weight": weight, + "passed_findings": req_passed_findings, + "total_findings": req_total_findings, + "description": getattr(m, "AttributeDescription", "N/A"), + } + ) + + # Calculate overall ThreatScore + if not overall_has_findings: + overall_score = 100.0 + elif overall_denominator > 0: + overall_score = (overall_numerator / overall_denominator) * 100 + else: + overall_score = 0.0 + + # Calculate section scores + section_scores = {} + for section, data in sections_data.items(): + if data["has_findings"] and data["denominator"] > 0: + section_scores[section] = (data["numerator"] / data["denominator"]) * 100 + else: + section_scores[section] = 100.0 + + # Sort critical requirements by risk level (desc) and weight (desc) + critical_requirements_list.sort( + key=lambda x: (x["risk_level"], x["weight"]), reverse=True + ) + + logger.info( + f"ThreatScore computed: {overall_score:.2f}% " + f"({passed_requirements}/{total_requirements} requirements passed, " + f"{len(critical_requirements_list)} critical failures)" + ) + + return { + "overall_score": round(overall_score, 2), + "section_scores": {k: round(v, 2) for k, v in section_scores.items()}, + "critical_requirements": critical_requirements_list, + "total_requirements": total_requirements, + "passed_requirements": passed_requirements, + "failed_requirements": failed_requirements, + "manual_requirements": manual_requirements, + "total_findings": total_findings, + "passed_findings": passed_findings, + "failed_findings": failed_findings, + } diff --git a/api/src/backend/tasks/jobs/threatscore_utils.py b/api/src/backend/tasks/jobs/threatscore_utils.py new file mode 100644 index 0000000000..bc2cb009a2 --- /dev/null +++ b/api/src/backend/tasks/jobs/threatscore_utils.py @@ -0,0 +1,127 @@ +from celery.utils.log import get_task_logger +from django.db.models import Count, Q + +from api.db_router import READ_REPLICA_ALIAS +from api.db_utils import rls_transaction +from api.models import Finding, StatusChoices + +logger = get_task_logger(__name__) + + +def _aggregate_requirement_statistics_from_database( + tenant_id: str, scan_id: str +) -> dict[str, dict[str, int]]: + """ + Aggregate finding statistics by check_id using database aggregation. + + This function uses Django ORM aggregation to calculate pass/fail statistics + entirely in the database, avoiding the need to load findings into memory. + + Args: + tenant_id (str): The tenant ID for Row-Level Security context. + scan_id (str): The ID of the scan to retrieve findings for. + + Returns: + dict[str, dict[str, int]]: Dictionary mapping check_id to statistics: + - 'passed' (int): Number of passed findings for this check + - 'total' (int): Total number of findings for this check + + Example: + { + 'aws_iam_user_mfa_enabled': {'passed': 10, 'total': 15}, + 'aws_s3_bucket_public_access': {'passed': 0, 'total': 5} + } + """ + requirement_statistics_by_check_id = {} + + with rls_transaction(tenant_id, using=READ_REPLICA_ALIAS): + aggregated_statistics_queryset = ( + Finding.all_objects.filter(tenant_id=tenant_id, scan_id=scan_id) + .values("check_id") + .annotate( + total_findings=Count("id"), + passed_findings=Count("id", filter=Q(status=StatusChoices.PASS)), + ) + ) + + for aggregated_stat in aggregated_statistics_queryset: + check_id = aggregated_stat["check_id"] + requirement_statistics_by_check_id[check_id] = { + "passed": aggregated_stat["passed_findings"], + "total": aggregated_stat["total_findings"], + } + + logger.info( + f"Aggregated statistics for {len(requirement_statistics_by_check_id)} unique checks" + ) + return requirement_statistics_by_check_id + + +def _calculate_requirements_data_from_statistics( + compliance_obj, requirement_statistics_by_check_id: dict[str, dict[str, int]] +) -> tuple[dict[str, dict], list[dict]]: + """ + Calculate requirement status and statistics using pre-aggregated database statistics. + + Args: + compliance_obj: The compliance framework object containing requirements. + requirement_statistics_by_check_id (dict[str, dict[str, int]]): Pre-aggregated statistics + mapping check_id to {'passed': int, 'total': int} counts. + + Returns: + tuple[dict[str, dict], list[dict]]: A tuple containing: + - attributes_by_requirement_id: Dictionary mapping requirement IDs to their attributes. + - requirements_list: List of requirement dictionaries with status and statistics. + """ + attributes_by_requirement_id = {} + requirements_list = [] + + compliance_framework = getattr(compliance_obj, "Framework", "N/A") + compliance_version = getattr(compliance_obj, "Version", "N/A") + + for requirement in compliance_obj.Requirements: + requirement_id = requirement.Id + requirement_description = getattr(requirement, "Description", "") + requirement_checks = getattr(requirement, "Checks", []) + requirement_attributes = getattr(requirement, "Attributes", []) + + attributes_by_requirement_id[requirement_id] = { + "attributes": { + "req_attributes": requirement_attributes, + "checks": requirement_checks, + }, + "description": requirement_description, + } + + total_passed_findings = 0 + total_findings_count = 0 + + for check_id in requirement_checks: + if check_id in requirement_statistics_by_check_id: + check_statistics = requirement_statistics_by_check_id[check_id] + total_findings_count += check_statistics["total"] + total_passed_findings += check_statistics["passed"] + + if total_findings_count > 0: + if total_passed_findings == total_findings_count: + requirement_status = StatusChoices.PASS + else: + requirement_status = StatusChoices.FAIL + else: + requirement_status = StatusChoices.MANUAL + + requirements_list.append( + { + "id": requirement_id, + "attributes": { + "framework": compliance_framework, + "version": compliance_version, + "status": requirement_status, + "description": requirement_description, + "passed_findings": total_passed_findings, + "total_findings": total_findings_count, + }, + } + ) + + return attributes_by_requirement_id, requirements_list diff --git a/api/src/backend/tasks/tasks.py b/api/src/backend/tasks/tasks.py index 799427cd19..9524a1b985 100644 --- a/api/src/backend/tasks/tasks.py +++ b/api/src/backend/tasks/tasks.py @@ -8,7 +8,10 @@ from celery.utils.log import get_task_logger from config.celery import RLSTask from config.django.base import DJANGO_FINDINGS_BATCH_SIZE, DJANGO_TMP_OUTPUT_DIRECTORY from django_celery_beat.models import PeriodicTask -from tasks.jobs.backfill import backfill_resource_scan_summaries +from tasks.jobs.backfill import ( + backfill_compliance_summaries, + backfill_resource_scan_summaries, +) from tasks.jobs.connection import ( check_integration_connection, check_lighthouse_connection, @@ -494,6 +497,21 @@ def backfill_scan_resource_summaries_task(tenant_id: str, scan_id: str): return backfill_resource_scan_summaries(tenant_id=tenant_id, scan_id=scan_id) +@shared_task(name="backfill-compliance-summaries", queue="backfill") +def backfill_compliance_summaries_task(tenant_id: str, scan_id: str): + """ + Tries to backfill compliance overview summaries for a completed scan. + + This task aggregates compliance requirement data across regions + to create pre-computed summary records for fast compliance overview queries. + + Args: + tenant_id (str): The tenant identifier. + scan_id (str): The scan identifier. + """ + return backfill_compliance_summaries(tenant_id=tenant_id, scan_id=scan_id) + + @shared_task(base=RLSTask, name="scan-compliance-overviews", queue="compliance") def create_compliance_requirements_task(tenant_id: str, scan_id: str): """ diff --git a/api/src/backend/tasks/tests/test_backfill.py b/api/src/backend/tasks/tests/test_backfill.py index b436f13151..13fa481b2e 100644 --- a/api/src/backend/tasks/tests/test_backfill.py +++ b/api/src/backend/tasks/tests/test_backfill.py @@ -1,43 +1,53 @@ from uuid import uuid4 import pytest -from tasks.jobs.backfill import backfill_resource_scan_summaries +from tasks.jobs.backfill import ( + backfill_compliance_summaries, + backfill_resource_scan_summaries, +) -from api.models import ResourceScanSummary, Scan, StateChoices +from api.models import ( + ComplianceOverviewSummary, + ResourceScanSummary, + Scan, + StateChoices, +) + + +@pytest.fixture(scope="function") +def resource_scan_summary_data(scans_fixture): + scan = scans_fixture[0] + return ResourceScanSummary.objects.create( + tenant_id=scan.tenant_id, + scan_id=scan.id, + resource_id=str(uuid4()), + service="aws", + region="us-east-1", + resource_type="instance", + ) + + +@pytest.fixture(scope="function") +def get_not_completed_scans(providers_fixture): + provider_id = providers_fixture[0].id + tenant_id = providers_fixture[0].tenant_id + scan_1 = Scan.objects.create( + tenant_id=tenant_id, + trigger=Scan.TriggerChoices.MANUAL, + state=StateChoices.EXECUTING, + provider_id=provider_id, + ) + scan_2 = Scan.objects.create( + tenant_id=tenant_id, + trigger=Scan.TriggerChoices.MANUAL, + state=StateChoices.AVAILABLE, + provider_id=provider_id, + ) + return scan_1, scan_2 @pytest.mark.django_db class TestBackfillResourceScanSummaries: - @pytest.fixture(scope="function") - def resource_scan_summary_data(self, scans_fixture): - scan = scans_fixture[0] - return ResourceScanSummary.objects.create( - tenant_id=scan.tenant_id, - scan_id=scan.id, - resource_id=str(uuid4()), - service="aws", - region="us-east-1", - resource_type="instance", - ) - - @pytest.fixture(scope="function") - def get_not_completed_scans(self, providers_fixture): - provider_id = providers_fixture[0].id - tenant_id = providers_fixture[0].tenant_id - scan_1 = Scan.objects.create( - tenant_id=tenant_id, - trigger=Scan.TriggerChoices.MANUAL, - state=StateChoices.EXECUTING, - provider_id=provider_id, - ) - scan_2 = Scan.objects.create( - tenant_id=tenant_id, - trigger=Scan.TriggerChoices.MANUAL, - state=StateChoices.AVAILABLE, - provider_id=provider_id, - ) - return scan_1, scan_2 - def test_already_backfilled(self, resource_scan_summary_data): tenant_id = resource_scan_summary_data.tenant_id scan_id = resource_scan_summary_data.scan_id @@ -77,3 +87,88 @@ class TestBackfillResourceScanSummaries: assert summary.service == resource.service assert summary.region == resource.region assert summary.resource_type == resource.type + + def test_no_resources_to_backfill(self, scans_fixture): + scan = scans_fixture[1] # Failed scan with no findings/resources + tenant_id = str(scan.tenant_id) + scan_id = str(scan.id) + + result = backfill_resource_scan_summaries(tenant_id, scan_id) + + assert result == {"status": "no resources to backfill"} + + +@pytest.mark.django_db +class TestBackfillComplianceSummaries: + def test_already_backfilled(self, scans_fixture): + scan = scans_fixture[0] + tenant_id = str(scan.tenant_id) + ComplianceOverviewSummary.objects.create( + tenant_id=scan.tenant_id, + scan=scan, + compliance_id="aws_account_security_onboarding_aws", + requirements_passed=1, + requirements_failed=0, + requirements_manual=0, + total_requirements=1, + ) + + result = backfill_compliance_summaries(tenant_id, str(scan.id)) + + assert result == {"status": "already backfilled"} + + def test_not_completed_scan(self, get_not_completed_scans): + for scan in get_not_completed_scans: + result = backfill_compliance_summaries(str(scan.tenant_id), str(scan.id)) + assert result == {"status": "scan is not completed"} + + def test_no_compliance_data(self, scans_fixture): + scan = scans_fixture[1] # Failed scan with no compliance rows + + result = backfill_compliance_summaries(str(scan.tenant_id), str(scan.id)) + + assert result == {"status": "no compliance data to backfill"} + + def test_backfill_creates_compliance_summaries( + self, tenants_fixture, scans_fixture, compliance_requirements_overviews_fixture + ): + tenant = tenants_fixture[0] + scan = scans_fixture[0] + + result = backfill_compliance_summaries(str(tenant.id), str(scan.id)) + + expected = { + "aws_account_security_onboarding_aws": { + "requirements_passed": 1, + "requirements_failed": 1, + "requirements_manual": 1, + "total_requirements": 3, + }, + "cis_1.4_aws": { + "requirements_passed": 0, + "requirements_failed": 1, + "requirements_manual": 0, + "total_requirements": 1, + }, + "mitre_attack_aws": { + "requirements_passed": 0, + "requirements_failed": 1, + "requirements_manual": 0, + "total_requirements": 1, + }, + } + + assert result == {"status": "backfilled", "inserted": len(expected)} + + summaries = ComplianceOverviewSummary.objects.filter( + tenant_id=str(tenant.id), scan_id=str(scan.id) + ) + assert summaries.count() == len(expected) + + for summary in summaries: + assert summary.compliance_id in expected + expected_counts = expected[summary.compliance_id] + assert summary.requirements_passed == expected_counts["requirements_passed"] + assert summary.requirements_failed == expected_counts["requirements_failed"] + assert summary.requirements_manual == expected_counts["requirements_manual"] + assert summary.total_requirements == expected_counts["total_requirements"] diff --git a/api/src/backend/tasks/tests/test_report.py b/api/src/backend/tasks/tests/test_report.py index a472067b2d..91d3b1145d 100644 --- a/api/src/backend/tasks/tests/test_report.py +++ b/api/src/backend/tasks/tests/test_report.py @@ -1,19 +1,25 @@ import uuid +from datetime import timedelta +from decimal import Decimal from pathlib import Path from unittest.mock import MagicMock, patch import matplotlib import pytest +from django.utils import timezone +from freezegun import freeze_time from tasks.jobs.report import ( - _aggregate_requirement_statistics_from_database, - _calculate_requirements_data_from_statistics, _load_findings_for_requirement_checks, generate_threatscore_report, generate_threatscore_report_job, ) +from tasks.jobs.threatscore_utils import ( + _aggregate_requirement_statistics_from_database, + _calculate_requirements_data_from_statistics, +) from tasks.tasks import generate_threatscore_report_task -from api.models import Finding, StatusChoices +from api.models import Finding, Scan, StateChoices, StatusChoices, ThreatScoreSnapshot from prowler.lib.check.models import Severity matplotlib.use("Agg") # Use non-interactive backend for tests @@ -39,6 +45,7 @@ class TestGenerateThreatscoreReport: assert result == {"upload": False} mock_filter.assert_called_once_with(scan_id=self.scan_id) + @patch("tasks.jobs.report.ThreatScoreSnapshot.objects.create") @patch("tasks.jobs.report.rmtree") @patch("tasks.jobs.report._upload_to_s3") @patch("tasks.jobs.report.generate_threatscore_report") @@ -53,6 +60,7 @@ class TestGenerateThreatscoreReport: mock_generate_report, mock_upload, mock_rmtree, + mock_snapshot_create, ): mock_scan_summary_filter.return_value.exists.return_value = True @@ -95,8 +103,10 @@ class TestGenerateThreatscoreReport: Path("/tmp/threatscore_path_threatscore_report.pdf").parent, ignore_errors=True, ) + mock_snapshot_create.assert_called_once() - def test_generate_threatscore_report_fails_upload(self): + @patch("tasks.jobs.report.ThreatScoreSnapshot.objects.create") + def test_generate_threatscore_report_fails_upload(self, mock_snapshot_create): with ( patch("tasks.jobs.report.ScanSummary.objects.filter") as mock_filter, patch("tasks.jobs.report.Provider.objects.get") as mock_provider_get, @@ -125,8 +135,12 @@ class TestGenerateThreatscoreReport: ) assert result == {"upload": False} + mock_snapshot_create.assert_called_once() - def test_generate_threatscore_report_logs_rmtree_exception(self, caplog): + @patch("tasks.jobs.report.ThreatScoreSnapshot.objects.create") + def test_generate_threatscore_report_logs_rmtree_exception( + self, mock_snapshot_create, caplog + ): with ( patch("tasks.jobs.report.ScanSummary.objects.filter") as mock_filter, patch("tasks.jobs.report.Provider.objects.get") as mock_provider_get, @@ -160,8 +174,10 @@ class TestGenerateThreatscoreReport: provider_id=self.provider_id, ) assert "Error deleting output files" in caplog.text + mock_snapshot_create.assert_called_once() - def test_generate_threatscore_report_azure_provider(self): + @patch("tasks.jobs.report.ThreatScoreSnapshot.objects.create") + def test_generate_threatscore_report_azure_provider(self, mock_snapshot_create): with ( patch("tasks.jobs.report.ScanSummary.objects.filter") as mock_filter, patch("tasks.jobs.report.Provider.objects.get") as mock_provider_get, @@ -200,6 +216,135 @@ class TestGenerateThreatscoreReport: only_failed=True, min_risk_level=4, ) + mock_snapshot_create.assert_called_once() + + @patch("tasks.jobs.report.rmtree") + @patch( + "tasks.jobs.report._upload_to_s3", + return_value="s3://bucket/threatscore/threatscore_report.pdf", + ) + @patch("tasks.jobs.report.generate_threatscore_report") + @patch("tasks.jobs.report._generate_output_directory") + @patch("tasks.jobs.report.ScanSummary.objects.filter") + @patch("tasks.jobs.report.compute_threatscore_metrics") + @pytest.mark.django_db + @freeze_time("2025-01-10T12:00:00Z") + def test_generate_threatscore_report_persists_snapshot_and_delta( + self, + mock_compute_metrics, + mock_scan_summary_filter, + mock_generate_output_directory, + mock_generate_report, + mock_upload, + mock_rmtree, + tenants_fixture, + providers_fixture, + ): + tenant = tenants_fixture[0] + provider = providers_fixture[0] + + scan_previous = Scan.objects.create( + tenant=tenant, + provider=provider, + name="previous-threatscore-scan", + trigger=Scan.TriggerChoices.MANUAL, + state=StateChoices.COMPLETED, + started_at=timezone.now() - timedelta(hours=4), + completed_at=timezone.now() - timedelta(hours=3), + ) + ThreatScoreSnapshot.objects.create( + tenant=tenant, + scan=scan_previous, + provider=provider, + compliance_id="prowler_threatscore_aws", + overall_score=Decimal("70.00"), + score_delta=None, + section_scores={"1. IAM": "65.00"}, + critical_requirements=[], + total_requirements=50, + passed_requirements=35, + failed_requirements=15, + manual_requirements=0, + total_findings=40, + passed_findings=25, + failed_findings=15, + ) + + scan_current = Scan.objects.create( + tenant=tenant, + provider=provider, + name="current-threatscore-scan", + trigger=Scan.TriggerChoices.MANUAL, + state=StateChoices.COMPLETED, + started_at=timezone.now() - timedelta(hours=2), + completed_at=timezone.now() - timedelta(hours=1), + ) + + mock_scan_summary_filter.return_value.exists.return_value = True + mock_generate_output_directory.return_value = ( + "/tmp/output", + "/tmp/compressed", + "/tmp/threatscore_path", + ) + + metrics = { + "overall_score": 85.5, + "score_delta": 10.0, + "section_scores": {"1. IAM": 82.3, "2. Attack Surface": 60.0}, + "critical_requirements": [ + { + "requirement_id": "req_new", + "title": "New high-risk requirement", + "section": "1. IAM", + "subsection": "Root Account", + "risk_level": 5, + "weight": 150, + "passed_findings": 7, + "total_findings": 10, + "description": "Critical requirement description", + } + ], + "total_requirements": 140, + "passed_requirements": 100, + "failed_requirements": 40, + "manual_requirements": 0, + "total_findings": 200, + "passed_findings": 150, + "failed_findings": 50, + } + mock_compute_metrics.return_value = metrics + + result = generate_threatscore_report_job( + tenant_id=str(tenant.id), + scan_id=str(scan_current.id), + provider_id=str(provider.id), + ) + + assert result == {"upload": True} + mock_compute_metrics.assert_called_once_with( + tenant_id=str(tenant.id), + scan_id=str(scan_current.id), + provider_id=str(provider.id), + compliance_id="prowler_threatscore_aws", + min_risk_level=4, + ) + mock_generate_report.assert_called_once() + mock_upload.assert_called_once() + mock_rmtree.assert_called_once() + + snapshots = ThreatScoreSnapshot.objects.filter( + tenant=tenant, provider=provider + ).order_by("inserted_at") + assert snapshots.count() == 2 + + new_snapshot = ThreatScoreSnapshot.objects.get(scan=scan_current) + assert new_snapshot.compliance_id == "prowler_threatscore_aws" + assert Decimal(new_snapshot.overall_score) == Decimal("85.50") + assert Decimal(new_snapshot.score_delta) == Decimal("15.50") + assert new_snapshot.section_scores == metrics["section_scores"] + assert new_snapshot.critical_requirements == metrics["critical_requirements"] + assert new_snapshot.total_requirements == metrics["total_requirements"] + assert new_snapshot.total_findings == metrics["total_findings"] @pytest.mark.django_db diff --git a/api/src/backend/tasks/tests/test_scan.py b/api/src/backend/tasks/tests/test_scan.py index e1c938f9f1..f2724de4e6 100644 --- a/api/src/backend/tasks/tests/test_scan.py +++ b/api/src/backend/tasks/tests/test_scan.py @@ -1,16 +1,23 @@ import csv import json +import re import uuid +from contextlib import contextmanager from datetime import datetime, timezone from io import StringIO from unittest.mock import MagicMock, patch import pytest from tasks.jobs.scan import ( + _aggregate_findings_by_region, _copy_compliance_requirement_rows, + _create_compliance_summaries, _create_finding_delta, + _normalized_compliance_key, _persist_compliance_requirement_rows, + _process_finding_micro_batch, _store_resources, + aggregate_findings, create_compliance_requirements, perform_prowler_scan, ) @@ -28,6 +35,30 @@ from api.models import ( StatusChoices, ) from prowler.lib.check.models import Severity +from prowler.lib.outputs.finding import Status + + +@contextmanager +def noop_rls_transaction(*args, **kwargs): + yield + + +class FakeFinding: + def __init__(self, **attrs): + self.metadata = attrs.pop("metadata", {}) + for key, value in attrs.items(): + setattr(self, key, value) + + self.resource_tags = getattr(self, "resource_tags", {}) + self.resource_metadata = getattr(self, "resource_metadata", {}) + self.resource_details = getattr(self, "resource_details", {}) + self.compliance = getattr(self, "compliance", {}) + self.raw = getattr(self, "raw", {}) + self.partition = getattr(self, "partition", "") + self.muted = getattr(self, "muted", False) + + def get_metadata(self): + return self.metadata @pytest.mark.django_db @@ -1306,6 +1337,315 @@ class TestPerformScan: # TODO Add tests for aggregations +@pytest.mark.django_db +class TestProcessFindingMicroBatch: + def test_process_finding_micro_batch_creates_records_and_updates_caches( + self, tenants_fixture, scans_fixture + ): + tenant = tenants_fixture[0] + scan = scans_fixture[0] + provider = scan.provider + + finding = FakeFinding( + uid="finding-new", + status=StatusChoices.PASS, + status_extended="all good", + severity=Severity.low, + check_id="s3_public_buckets", + resource_uid="arn:aws:s3:::bucket-1", + resource_name="bucket-1", + region="us-east-1", + service_name="s3", + resource_type="bucket", + resource_tags={"env": "dev", "team": "security"}, + resource_metadata={"owner": "secops"}, + resource_details={"arn": "arn:aws:s3:::bucket-1"}, + partition="aws", + raw={"status": "PASS"}, + compliance={"cis": {"1.1": "PASS"}}, + metadata={"source": "prowler"}, + muted=False, + ) + + resource_cache = {} + tag_cache = {} + last_status_cache = {} + resource_failed_findings_cache = {} + unique_resources: set[tuple[str, str]] = set() + scan_resource_cache: set[tuple[str, str, str, str]] = set() + mute_rules_cache = {} + + with ( + patch("tasks.jobs.scan.rls_transaction", new=noop_rls_transaction), + patch("api.db_utils.rls_transaction", new=noop_rls_transaction), + ): + _process_finding_micro_batch( + str(tenant.id), + [finding], + scan, + provider, + resource_cache, + tag_cache, + last_status_cache, + resource_failed_findings_cache, + unique_resources, + scan_resource_cache, + mute_rules_cache, + ) + + created_finding = Finding.objects.get(uid=finding.uid) + resource = Resource.objects.get(uid=finding.resource_uid) + + assert created_finding.scan_id == scan.id + assert created_finding.status == StatusChoices.PASS + assert created_finding.delta == Finding.DeltaChoices.NEW + assert created_finding.muted is False + assert created_finding.check_metadata == finding.metadata + assert created_finding.resource_regions == [finding.region] + assert created_finding.resource_services == [finding.service_name] + assert created_finding.resource_types == [finding.resource_type] + assert created_finding.first_seen_at is not None + assert created_finding.compliance == finding.compliance + + assert resource.provider_id == provider.id + assert resource.region == finding.region + assert resource.service == finding.service_name + assert resource.type == finding.resource_type + assert resource.name == finding.resource_name + assert resource.metadata == json.dumps( + finding.resource_metadata, cls=CustomEncoder + ) + assert resource.details == f"{finding.resource_details}" + assert resource.partition == finding.partition + assert set(resource.tags.values_list("key", "value")) == set( + finding.resource_tags.items() + ) + assert resource.findings.filter(uid=finding.uid).exists() + + assert resource_cache[finding.resource_uid].id == resource.id + assert resource_failed_findings_cache[finding.resource_uid] == 0 + assert (resource.uid, resource.region) in unique_resources + assert ( + str(resource.id), + resource.service, + resource.region, + resource.type, + ) in scan_resource_cache + assert set(tag_cache.keys()) == set(finding.resource_tags.items()) + + def test_process_finding_micro_batch_manual_mute_and_dirty_resources( + self, tenants_fixture, scans_fixture + ): + tenant = tenants_fixture[0] + scan = scans_fixture[0] + provider = scan.provider + + existing_resource = Resource.objects.create( + tenant_id=tenant.id, + provider=provider, + uid="arn:aws:ec2:us-east-1:123456789012:instance/i-001", + name="i-001", + region="us-east-1", + service="ec2", + type="instance", + metadata=json.dumps({"old": "meta"}), + details="old-details", + partition="aws-old", + ) + + previous_first_seen = datetime(2024, 1, 1, tzinfo=timezone.utc) + + finding = FakeFinding( + uid="finding-muted", + status=StatusChoices.FAIL, + status_extended="failing", + severity=Severity.high, + check_id="ec2_public_instance", + resource_uid=existing_resource.uid, + resource_name=existing_resource.name, + region="eu-west-1", + service_name="eks", + resource_type="cluster", + resource_tags={"team": "devsec"}, + resource_metadata={"owner": "platform"}, + resource_details={"id": existing_resource.name}, + partition="aws", + raw={"status": "FAIL"}, + compliance={"cis": {"1.2": "FAIL"}}, + metadata={"source": "prowler"}, + muted=False, + ) + + resource_cache = {existing_resource.uid: existing_resource} + tag_cache = {} + last_status_cache = {finding.uid: (StatusChoices.PASS, previous_first_seen)} + resource_failed_findings_cache = {existing_resource.uid: 2} + unique_resources: set[tuple[str, str]] = set() + scan_resource_cache: set[tuple[str, str, str, str]] = set() + mute_rules_cache = {finding.uid: "Muted via rule"} + + with ( + patch("tasks.jobs.scan.rls_transaction", new=noop_rls_transaction), + patch("api.db_utils.rls_transaction", new=noop_rls_transaction), + ): + _process_finding_micro_batch( + str(tenant.id), + [finding], + scan, + provider, + resource_cache, + tag_cache, + last_status_cache, + resource_failed_findings_cache, + unique_resources, + scan_resource_cache, + mute_rules_cache, + ) + + existing_resource.refresh_from_db() + created_finding = Finding.objects.get(uid=finding.uid) + + assert created_finding.delta == Finding.DeltaChoices.CHANGED + assert created_finding.status == StatusChoices.FAIL + assert created_finding.muted is True + assert created_finding.muted_reason == "Muted via rule" + assert created_finding.muted_at is not None + assert created_finding.first_seen_at == previous_first_seen + assert created_finding.compliance == finding.compliance + assert created_finding.resource_regions == [finding.region] + assert created_finding.resource_services == [finding.service_name] + assert created_finding.resource_types == [finding.resource_type] + assert created_finding.scan_id == scan.id + + assert resource_failed_findings_cache[finding.resource_uid] == 2 + assert (finding.resource_uid, finding.region) in unique_resources + assert ( + str(existing_resource.id), + finding.service_name, + finding.region, + finding.resource_type, + ) in scan_resource_cache + + assert existing_resource.region == finding.region + assert existing_resource.service == finding.service_name + assert existing_resource.type == finding.resource_type + assert existing_resource.metadata == json.dumps( + finding.resource_metadata, cls=CustomEncoder + ) + assert existing_resource.details == f"{finding.resource_details}" + assert existing_resource.partition == finding.partition + assert set(existing_resource.tags.values_list("key", "value")) == { + ("team", "devsec") + } + assert existing_resource.findings.filter(uid=finding.uid).exists() + + assert resource_cache[finding.resource_uid].region == finding.region + assert resource_cache[finding.resource_uid].service == finding.service_name + assert tag_cache.keys() == {("team", "devsec")} + + def test_process_finding_micro_batch_skips_long_uid( + self, tenants_fixture, scans_fixture + ): + """Test that findings with UID > 300 chars are skipped (temporary workaround).""" + tenant = tenants_fixture[0] + scan = scans_fixture[0] + provider = scan.provider + + # Create a finding with UID > 300 chars + long_uid = ( + "prowler-aws-ec2_instance_public_ip-123456789012-us-east-1-" + "x" * 250 + ) + assert len(long_uid) > 300 + + finding_with_long_uid = FakeFinding( + uid=long_uid, + status=StatusChoices.FAIL, + status_extended="public instance", + severity=Severity.high, + check_id="ec2_instance_public_ip", + resource_uid="arn:aws:ec2:us-east-1:123456789012:instance/i-long", + resource_name="i-long-uid-instance", + region="us-east-1", + service_name="ec2", + resource_type="instance", + resource_tags={}, + resource_metadata={}, + resource_details={}, + partition="aws", + raw={}, + compliance={}, + metadata={}, + muted=False, + ) + + # Create a normal finding that should be processed + normal_finding = FakeFinding( + uid="finding-normal", + status=StatusChoices.PASS, + status_extended="all good", + severity=Severity.low, + check_id="s3_bucket_encryption", + resource_uid="arn:aws:s3:::bucket-normal", + resource_name="bucket-normal", + region="us-east-1", + service_name="s3", + resource_type="bucket", + resource_tags={}, + resource_metadata={}, + resource_details={}, + partition="aws", + raw={}, + compliance={}, + metadata={}, + muted=False, + ) + + resource_cache = {} + tag_cache = {} + last_status_cache = {} + resource_failed_findings_cache = {} + unique_resources: set[tuple[str, str]] = set() + scan_resource_cache: set[tuple[str, str, str, str]] = set() + mute_rules_cache = {} + + with ( + patch("tasks.jobs.scan.rls_transaction", new=noop_rls_transaction), + patch("api.db_utils.rls_transaction", new=noop_rls_transaction), + patch("tasks.jobs.scan.logger") as mock_logger, + ): + _process_finding_micro_batch( + str(tenant.id), + [finding_with_long_uid, normal_finding], + scan, + provider, + resource_cache, + tag_cache, + last_status_cache, + resource_failed_findings_cache, + unique_resources, + scan_resource_cache, + mute_rules_cache, + ) + + # Verify the long UID finding was NOT created + assert not Finding.objects.filter(uid=long_uid).exists() + + # Verify the normal finding WAS created + assert Finding.objects.filter(uid=normal_finding.uid).exists() + + # Verify logging was called for skipped finding + assert mock_logger.warning.called + warning_calls = [str(call) for call in mock_logger.warning.call_args_list] + assert any( + "Skipping finding with UID exceeding 300 characters" in str(call) + for call in warning_calls + ) + assert any( + f"Scan {scan.id}: Skipped 1 finding(s)" in str(call) + for call in warning_calls + ) + + @pytest.mark.django_db class TestCreateComplianceRequirements: def test_create_compliance_requirements_success( @@ -1316,12 +1656,9 @@ class TestCreateComplianceRequirements: findings_fixture, resources_fixture, ): - with ( - patch( - "tasks.jobs.scan.PROWLER_COMPLIANCE_OVERVIEW_TEMPLATE" - ) as mock_compliance_template, - patch("tasks.jobs.scan.generate_scan_compliance"), - ): + with patch( + "tasks.jobs.scan.PROWLER_COMPLIANCE_OVERVIEW_TEMPLATE" + ) as mock_compliance_template: tenant_id = str(tenants_fixture[0].id) scan_id = str(scans_fixture[0].id) @@ -1332,6 +1669,7 @@ class TestCreateComplianceRequirements: "requirements": { "1.1": { "description": "Ensure root access key does not exist", + "checks": {"test_check_id": None}, "checks_status": { "pass": 0, "fail": 0, @@ -1342,6 +1680,7 @@ class TestCreateComplianceRequirements: }, "1.2": { "description": "Ensure MFA is enabled for root account", + "checks": {"test_check_id": None}, "checks_status": { "pass": 0, "fail": 1, @@ -1367,12 +1706,9 @@ class TestCreateComplianceRequirements: providers_fixture, findings_fixture, ): - with ( - patch( - "tasks.jobs.scan.PROWLER_COMPLIANCE_OVERVIEW_TEMPLATE" - ) as mock_compliance_template, - patch("tasks.jobs.scan.generate_scan_compliance"), - ): + with patch( + "tasks.jobs.scan.PROWLER_COMPLIANCE_OVERVIEW_TEMPLATE" + ) as mock_compliance_template: tenant_id = str(tenants_fixture[0].id) scan_id = str(scans_fixture[0].id) @@ -1383,6 +1719,7 @@ class TestCreateComplianceRequirements: "requirements": { "req_1": { "description": "Test Requirement 1", + "checks": {"test_check_id": None}, "checks_status": { "pass": 2, "fail": 1, @@ -1406,12 +1743,9 @@ class TestCreateComplianceRequirements: providers_fixture, findings_fixture, ): - with ( - patch( - "tasks.jobs.scan.PROWLER_COMPLIANCE_OVERVIEW_TEMPLATE" - ) as mock_compliance_template, - patch("tasks.jobs.scan.generate_scan_compliance"), - ): + with patch( + "tasks.jobs.scan.PROWLER_COMPLIANCE_OVERVIEW_TEMPLATE" + ) as mock_compliance_template: tenant = tenants_fixture[0] scan = scans_fixture[0] provider = providers_fixture[0] @@ -1431,6 +1765,7 @@ class TestCreateComplianceRequirements: "requirements": { "1.1": { "description": "Test requirement", + "checks": {"test_check_id": None}, "checks_status": { "pass": 0, "fail": 0, @@ -1454,12 +1789,9 @@ class TestCreateComplianceRequirements: providers_fixture, findings_fixture, ): - with ( - patch( - "tasks.jobs.scan.PROWLER_COMPLIANCE_OVERVIEW_TEMPLATE" - ) as mock_compliance_template, - patch("tasks.jobs.scan.generate_scan_compliance"), - ): + with patch( + "tasks.jobs.scan.PROWLER_COMPLIANCE_OVERVIEW_TEMPLATE" + ) as mock_compliance_template: tenant_id = str(tenants_fixture[0].id) scan_id = str(scans_fixture[0].id) @@ -1488,18 +1820,41 @@ class TestCreateComplianceRequirements: create_compliance_requirements(tenant_id, scan_id) def test_create_compliance_requirements_check_status_priority( - self, tenants_fixture, scans_fixture, providers_fixture, findings_fixture + self, tenants_fixture, scans_fixture, findings_fixture ): with ( patch( "tasks.jobs.scan.PROWLER_COMPLIANCE_OVERVIEW_TEMPLATE" ) as mock_compliance_template, patch( - "tasks.jobs.scan.generate_scan_compliance" - ) as mock_generate_compliance, + "tasks.jobs.scan._persist_compliance_requirement_rows" + ) as mock_persist, + patch("tasks.jobs.scan._create_compliance_summaries"), ): tenant_id = str(tenants_fixture[0].id) - scan_id = str(scans_fixture[0].id) + scan = scans_fixture[0] + scan_id = str(scan.id) + existing_finding = findings_fixture[0] + + pass_finding = Finding.objects.create( + tenant_id=scan.tenant_id, + uid="pass-finding", + scan=scan, + delta=None, + status=Status.PASS, + status_extended="pass status", + impact=Severity.low, + impact_extended="", + severity=Severity.low, + raw_result={"status": Status.PASS}, + tags={}, + check_id=existing_finding.check_id, + check_metadata={"CheckId": existing_finding.check_id}, + first_seen_at=datetime.now(timezone.utc), + muted=False, + ) + resource = existing_finding.resources.first() + pass_finding.add_resources([resource]) mock_compliance_template.__getitem__.return_value = { "cis_1.4_aws": { @@ -1508,6 +1863,7 @@ class TestCreateComplianceRequirements: "requirements": { "1.1": { "description": "Test requirement", + "checks": {existing_finding.check_id: None}, "checks_status": { "pass": 0, "fail": 0, @@ -1522,7 +1878,12 @@ class TestCreateComplianceRequirements: create_compliance_requirements(tenant_id, scan_id) - assert mock_generate_compliance.call_count == 1 + mock_persist.assert_called_once() + persisted_rows = mock_persist.call_args[0][1] + requirement_row = next( + row for row in persisted_rows if row["requirement_id"] == "1.1" + ) + assert requirement_row["requirement_status"] == "FAIL" def test_create_compliance_requirements_multiple_regions( self, @@ -1531,12 +1892,9 @@ class TestCreateComplianceRequirements: providers_fixture, findings_fixture, ): - with ( - patch( - "tasks.jobs.scan.PROWLER_COMPLIANCE_OVERVIEW_TEMPLATE" - ) as mock_compliance_template, - patch("tasks.jobs.scan.generate_scan_compliance"), - ): + with patch( + "tasks.jobs.scan.PROWLER_COMPLIANCE_OVERVIEW_TEMPLATE" + ) as mock_compliance_template: tenant_id = str(tenants_fixture[0].id) scan_id = str(scans_fixture[0].id) @@ -1547,6 +1905,7 @@ class TestCreateComplianceRequirements: "requirements": { "req_1": { "description": "Test Requirement 1", + "checks": {"test_check_id": None}, "checks_status": { "pass": 2, "fail": 0, @@ -1571,12 +1930,9 @@ class TestCreateComplianceRequirements: providers_fixture, findings_fixture, ): - with ( - patch( - "tasks.jobs.scan.PROWLER_COMPLIANCE_OVERVIEW_TEMPLATE" - ) as mock_compliance_template, - patch("tasks.jobs.scan.generate_scan_compliance"), - ): + with patch( + "tasks.jobs.scan.PROWLER_COMPLIANCE_OVERVIEW_TEMPLATE" + ) as mock_compliance_template: tenant_id = str(tenants_fixture[0].id) scan_id = str(scans_fixture[0].id) @@ -1587,6 +1943,7 @@ class TestCreateComplianceRequirements: "requirements": { "req_1": { "description": "Test Requirement 1", + "checks": {"test_check_id": None}, "checks_status": { "pass": 2, "fail": 0, @@ -1597,6 +1954,7 @@ class TestCreateComplianceRequirements: }, "req_2": { "description": "Test Requirement 2", + "checks": {"test_check_id": None}, "checks_status": { "pass": 1, "fail": 1, @@ -2383,3 +2741,733 @@ class TestComplianceRequirementCopy: assert obj.failed_checks == 5 assert obj.total_checks == 15 assert obj.scan_id == scan_id + + +@pytest.mark.django_db +class TestCreateComplianceSummaries: + """Test _create_compliance_summaries function.""" + + @patch("tasks.jobs.scan.ComplianceOverviewSummary.objects.bulk_create") + @patch("tasks.jobs.scan.rls_transaction") + def test_create_compliance_summaries_mixed_statuses( + self, mock_rls_transaction, mock_bulk_create + ): + """Test creating summaries with mixed requirement statuses (PASS/FAIL/MANUAL).""" + tenant_id = str(uuid.uuid4()) + scan_id = str(uuid.uuid4()) + + # Simulate pre-computed requirement statuses + requirement_statuses = { + ("compliance1", "req1"): { + "fail_count": 0, + "pass_count": 5, + "total_count": 5, + }, + ("compliance1", "req2"): { + "fail_count": 2, + "pass_count": 3, + "total_count": 5, + }, + ("compliance1", "req3"): { + "fail_count": 0, + "pass_count": 3, + "total_count": 5, + }, + ("compliance2", "req1"): { + "fail_count": 1, + "pass_count": 0, + "total_count": 5, + }, + } + + ctx = MagicMock() + ctx.__enter__.return_value = None + ctx.__exit__.return_value = False + mock_rls_transaction.return_value = ctx + + _create_compliance_summaries(tenant_id, scan_id, requirement_statuses) + + mock_rls_transaction.assert_called_once_with(tenant_id) + mock_bulk_create.assert_called_once() + + args, kwargs = mock_bulk_create.call_args + objects = args[0] + assert len(objects) == 2 + assert kwargs["batch_size"] == 500 + + # Find compliance1 and compliance2 summaries + comp1 = next(obj for obj in objects if obj.compliance_id == "compliance1") + comp2 = next(obj for obj in objects if obj.compliance_id == "compliance2") + + # compliance1: req1=PASS, req2=FAIL (has fail_count), req3=MANUAL (pass < total) + assert comp1.total_requirements == 3 + assert comp1.requirements_passed == 1 + assert comp1.requirements_failed == 1 + assert comp1.requirements_manual == 1 + + # compliance2: req1=FAIL (has fail_count) + assert comp2.total_requirements == 1 + assert comp2.requirements_passed == 0 + assert comp2.requirements_failed == 1 + assert comp2.requirements_manual == 0 + + @patch("tasks.jobs.scan.ComplianceOverviewSummary.objects.bulk_create") + @patch("tasks.jobs.scan.rls_transaction") + def test_create_compliance_summaries_empty_input( + self, mock_rls_transaction, mock_bulk_create + ): + """Test with empty requirement_statuses dict - should not create any summaries.""" + tenant_id = str(uuid.uuid4()) + scan_id = str(uuid.uuid4()) + requirement_statuses = {} + + ctx = MagicMock() + ctx.__enter__.return_value = None + ctx.__exit__.return_value = False + mock_rls_transaction.return_value = ctx + + _create_compliance_summaries(tenant_id, scan_id, requirement_statuses) + + # Should not call bulk_create with empty list + mock_bulk_create.assert_not_called() + + @patch("tasks.jobs.scan.ComplianceOverviewSummary.objects.bulk_create") + @patch("tasks.jobs.scan.rls_transaction") + def test_create_compliance_summaries_all_pass( + self, mock_rls_transaction, mock_bulk_create + ): + """Test creating summaries when all requirements pass.""" + tenant_id = str(uuid.uuid4()) + scan_id = str(uuid.uuid4()) + + requirement_statuses = { + ("comp1", "req1"): {"fail_count": 0, "pass_count": 10, "total_count": 10}, + ("comp1", "req2"): {"fail_count": 0, "pass_count": 5, "total_count": 5}, + } + + ctx = MagicMock() + ctx.__enter__.return_value = None + ctx.__exit__.return_value = False + mock_rls_transaction.return_value = ctx + + _create_compliance_summaries(tenant_id, scan_id, requirement_statuses) + + args, kwargs = mock_bulk_create.call_args + objects = args[0] + assert len(objects) == 1 + + obj = objects[0] + assert obj.compliance_id == "comp1" + assert obj.total_requirements == 2 + assert obj.requirements_passed == 2 + assert obj.requirements_failed == 0 + assert obj.requirements_manual == 0 + + @patch("tasks.jobs.scan.ComplianceOverviewSummary.objects.bulk_create") + @patch("tasks.jobs.scan.rls_transaction") + def test_create_compliance_summaries_all_fail( + self, mock_rls_transaction, mock_bulk_create + ): + """Test creating summaries when all requirements fail.""" + tenant_id = str(uuid.uuid4()) + scan_id = str(uuid.uuid4()) + + requirement_statuses = { + ("comp1", "req1"): {"fail_count": 3, "pass_count": 7, "total_count": 10}, + ("comp1", "req2"): {"fail_count": 1, "pass_count": 4, "total_count": 5}, + } + + ctx = MagicMock() + ctx.__enter__.return_value = None + ctx.__exit__.return_value = False + mock_rls_transaction.return_value = ctx + + _create_compliance_summaries(tenant_id, scan_id, requirement_statuses) + + args, kwargs = mock_bulk_create.call_args + objects = args[0] + assert len(objects) == 1 + + obj = objects[0] + assert obj.compliance_id == "comp1" + assert obj.total_requirements == 2 + assert obj.requirements_passed == 0 + assert obj.requirements_failed == 2 + assert obj.requirements_manual == 0 + + @patch("tasks.jobs.scan.ComplianceOverviewSummary.objects.bulk_create") + @patch("tasks.jobs.scan.rls_transaction") + def test_create_compliance_summaries_correct_aggregation( + self, mock_rls_transaction, mock_bulk_create + ): + """Test that requirements are correctly aggregated to compliance level.""" + tenant_id = str(uuid.uuid4()) + scan_id = str(uuid.uuid4()) + + requirement_statuses = { + ("compliance_a", "req1"): { + "fail_count": 0, + "pass_count": 10, + "total_count": 10, + }, + ("compliance_a", "req2"): { + "fail_count": 1, + "pass_count": 9, + "total_count": 10, + }, + ("compliance_a", "req3"): { + "fail_count": 0, + "pass_count": 5, + "total_count": 10, + }, + ("compliance_b", "req1"): { + "fail_count": 0, + "pass_count": 8, + "total_count": 8, + }, + } + + ctx = MagicMock() + ctx.__enter__.return_value = None + ctx.__exit__.return_value = False + mock_rls_transaction.return_value = ctx + + _create_compliance_summaries(tenant_id, scan_id, requirement_statuses) + + args, kwargs = mock_bulk_create.call_args + objects = args[0] + assert len(objects) == 2 + + comp_a = next(obj for obj in objects if obj.compliance_id == "compliance_a") + comp_b = next(obj for obj in objects if obj.compliance_id == "compliance_b") + + # compliance_a: req1=PASS, req2=FAIL, req3=MANUAL + assert comp_a.total_requirements == 3 + assert comp_a.requirements_passed == 1 + assert comp_a.requirements_failed == 1 + assert comp_a.requirements_manual == 1 + + # compliance_b: req1=PASS + assert comp_b.total_requirements == 1 + assert comp_b.requirements_passed == 1 + assert comp_b.requirements_failed == 0 + assert comp_b.requirements_manual == 0 + + +@pytest.mark.django_db +class TestNormalizedComplianceKey: + """Test _normalized_compliance_key function.""" + + def test_normalized_compliance_key_normal_strings(self): + """Test normalization with normal framework and version strings.""" + result = _normalized_compliance_key("AWS-Foundational-Security", "2.0") + assert result == "awsfoundationalsecurity20" + + def test_normalized_compliance_key_with_underscores(self): + """Test normalization removes underscores.""" + result = _normalized_compliance_key("CIS_AWS_Foundations", "1_5_0") + assert result == "cisawsfoundations150" + + def test_normalized_compliance_key_none_framework(self): + """Test normalization with None framework.""" + result = _normalized_compliance_key(None, "1.0") + assert result == "10" + + def test_normalized_compliance_key_none_version(self): + """Test normalization with None version.""" + result = _normalized_compliance_key("AWS-Security", None) + assert result == "awssecurity" + + def test_normalized_compliance_key_both_none(self): + """Test normalization with both framework and version as None.""" + result = _normalized_compliance_key(None, None) + assert result == "" + + def test_normalized_compliance_key_empty_strings(self): + """Test normalization with empty strings.""" + result = _normalized_compliance_key("", "") + assert result == "" + + def test_normalized_compliance_key_mixed_case(self): + """Test normalization lowercases strings.""" + result = _normalized_compliance_key("AWS-FOUNDATIONAL", "V2.0") + assert result == "awsfoundationalv20" + + def test_normalized_compliance_key_complex_pattern(self): + """Test normalization with complex patterns.""" + result = _normalized_compliance_key("PCI-DSS_v3-2-1", "2023-Update") + assert result == "pcidssv3212023update" + + +@pytest.mark.django_db +class TestAggregateFindings: + """Test aggregate_findings function.""" + + @patch("tasks.jobs.scan.ScanSummary.objects.bulk_create") + @patch("tasks.jobs.scan.rls_transaction") + def test_aggregate_findings_creates_scan_summaries( + self, + mock_rls_transaction, + mock_bulk_create, + tenants_fixture, + scans_fixture, + findings_fixture, + ): + """Test that aggregate_findings creates ScanSummary records.""" + tenant = tenants_fixture[0] + scan = scans_fixture[0] + + ctx = MagicMock() + ctx.__enter__.return_value = None + ctx.__exit__.return_value = False + mock_rls_transaction.return_value = ctx + + aggregate_findings(str(tenant.id), str(scan.id)) + + mock_rls_transaction.assert_called() + mock_bulk_create.assert_called_once() + + args, kwargs = mock_bulk_create.call_args + objects = args[0] + assert kwargs["batch_size"] == 3000 + # Should have created at least one summary + assert len(objects) > 0 + + @patch("tasks.jobs.scan.Finding.objects.filter") + @patch("tasks.jobs.scan.ScanSummary.objects.bulk_create") + @patch("tasks.jobs.scan.rls_transaction") + def test_aggregate_findings_excludes_muted_from_counts( + self, mock_rls_transaction, mock_bulk_create, mock_findings_filter + ): + """Test that muted findings are excluded from fail/pass counts but counted separately.""" + tenant_id = str(uuid.uuid4()) + scan_id = str(uuid.uuid4()) + + # Mock findings queryset + mock_queryset = MagicMock() + mock_queryset.values.return_value = mock_queryset + mock_queryset.annotate.return_value = [ + { + "check_id": "check1", + "resources__service": "s3", + "severity": "high", + "resources__region": "us-east-1", + "fail": 5, + "_pass": 10, + "muted_count": 3, + "total": 18, + "new": 2, + "changed": 1, + "unchanged": 12, + "fail_new": 1, + "fail_changed": 0, + "pass_new": 1, + "pass_changed": 0, + "muted_new": 0, + "muted_changed": 1, + } + ] + + ctx = MagicMock() + ctx.__enter__.return_value = None + ctx.__exit__.return_value = False + mock_rls_transaction.return_value = ctx + mock_findings_filter.return_value = mock_queryset + + aggregate_findings(tenant_id, scan_id) + + mock_bulk_create.assert_called_once() + args, kwargs = mock_bulk_create.call_args + objects = args[0] + + summary = list(objects)[0] + assert summary.fail == 5 + assert summary._pass == 10 + assert summary.muted == 3 + assert summary.total == 18 + + @patch("tasks.jobs.scan.Finding.objects.filter") + @patch("tasks.jobs.scan.ScanSummary.objects.bulk_create") + @patch("tasks.jobs.scan.rls_transaction") + def test_aggregate_findings_computes_deltas_correctly( + self, mock_rls_transaction, mock_bulk_create, mock_findings_filter + ): + """Test that delta counts (new, changed, unchanged) are computed correctly.""" + tenant_id = str(uuid.uuid4()) + scan_id = str(uuid.uuid4()) + + mock_queryset = MagicMock() + mock_queryset.values.return_value = mock_queryset + mock_queryset.annotate.return_value = [ + { + "check_id": "check1", + "resources__service": "ec2", + "severity": "critical", + "resources__region": "us-west-2", + "fail": 8, + "_pass": 12, + "muted_count": 2, + "total": 22, + "new": 5, + "changed": 3, + "unchanged": 12, + "fail_new": 3, + "fail_changed": 2, + "pass_new": 2, + "pass_changed": 1, + "muted_new": 1, + "muted_changed": 0, + } + ] + + ctx = MagicMock() + ctx.__enter__.return_value = None + ctx.__exit__.return_value = False + mock_rls_transaction.return_value = ctx + mock_findings_filter.return_value = mock_queryset + + aggregate_findings(tenant_id, scan_id) + + args, kwargs = mock_bulk_create.call_args + objects = args[0] + + summary = list(objects)[0] + assert summary.new == 5 + assert summary.changed == 3 + assert summary.unchanged == 12 + assert summary.fail_new == 3 + assert summary.fail_changed == 2 + assert summary.pass_new == 2 + assert summary.pass_changed == 1 + assert summary.muted_new == 1 + assert summary.muted_changed == 0 + + @patch("tasks.jobs.scan.Finding.objects.filter") + @patch("tasks.jobs.scan.ScanSummary.objects.bulk_create") + @patch("tasks.jobs.scan.rls_transaction") + def test_aggregate_findings_groups_by_dimensions( + self, mock_rls_transaction, mock_bulk_create, mock_findings_filter + ): + """Test that findings are grouped by check_id, service, severity, and region.""" + tenant_id = str(uuid.uuid4()) + scan_id = str(uuid.uuid4()) + + mock_queryset = MagicMock() + mock_queryset.values.return_value = mock_queryset + mock_queryset.annotate.return_value = [ + { + "check_id": "check1", + "resources__service": "s3", + "severity": "high", + "resources__region": "us-east-1", + "fail": 5, + "_pass": 10, + "muted_count": 0, + "total": 15, + "new": 2, + "changed": 1, + "unchanged": 12, + "fail_new": 1, + "fail_changed": 0, + "pass_new": 1, + "pass_changed": 1, + "muted_new": 0, + "muted_changed": 0, + }, + { + "check_id": "check1", + "resources__service": "s3", + "severity": "high", + "resources__region": "us-west-2", + "fail": 3, + "_pass": 7, + "muted_count": 1, + "total": 11, + "new": 1, + "changed": 0, + "unchanged": 9, + "fail_new": 1, + "fail_changed": 0, + "pass_new": 0, + "pass_changed": 0, + "muted_new": 0, + "muted_changed": 1, + }, + ] + + ctx = MagicMock() + ctx.__enter__.return_value = None + ctx.__exit__.return_value = False + mock_rls_transaction.return_value = ctx + mock_findings_filter.return_value = mock_queryset + + aggregate_findings(tenant_id, scan_id) + + args, kwargs = mock_bulk_create.call_args + objects = args[0] + + # Should create 2 summaries (different regions) + assert len(list(objects)) == 2 + + summaries = list(objects) + assert all(s.check_id == "check1" for s in summaries) + assert all(s.service == "s3" for s in summaries) + assert all(s.severity == "high" for s in summaries) + + regions = {s.region for s in summaries} + assert regions == {"us-east-1", "us-west-2"} + + +@pytest.mark.django_db +class TestAggregateFindingsByRegion: + """Test _aggregate_findings_by_region function.""" + + @patch("tasks.jobs.scan.Finding.all_objects.filter") + @patch("tasks.jobs.scan.rls_transaction") + def test_aggregate_findings_by_region_returns_correct_structure( + self, mock_rls_transaction, mock_findings_filter + ): + """Test function returns correct data structure.""" + tenant_id = str(uuid.uuid4()) + scan_id = str(uuid.uuid4()) + modeled_threatscore_compliance_id = "ProwlerThreatScore-1.0" + + # Mock findings with resources + mock_finding1 = MagicMock() + mock_finding1.check_id = "check1" + mock_finding1.status = "FAIL" + mock_finding1.compliance = {modeled_threatscore_compliance_id: ["req1", "req2"]} + + mock_resource1 = MagicMock() + mock_resource1.region = "us-east-1" + mock_finding1.small_resources = [mock_resource1] + + mock_queryset = MagicMock() + mock_queryset.only.return_value = mock_queryset + mock_queryset.prefetch_related.return_value = [mock_finding1] + + ctx = MagicMock() + ctx.__enter__.return_value = None + ctx.__exit__.return_value = False + mock_rls_transaction.return_value = ctx + mock_findings_filter.return_value = mock_queryset + + check_status_by_region, findings_count_by_compliance = ( + _aggregate_findings_by_region( + tenant_id, scan_id, modeled_threatscore_compliance_id + ) + ) + + # Verify structure of check_status_by_region + assert isinstance(check_status_by_region, dict) + assert "us-east-1" in check_status_by_region + assert "check1" in check_status_by_region["us-east-1"] + assert check_status_by_region["us-east-1"]["check1"] == "FAIL" + + # Verify structure of findings_count_by_compliance + assert isinstance(findings_count_by_compliance, dict) + + @patch("tasks.jobs.scan.Finding.all_objects.filter") + @patch("tasks.jobs.scan.rls_transaction") + def test_aggregate_findings_by_region_fail_status_priority( + self, mock_rls_transaction, mock_findings_filter + ): + """Test that FAIL status takes priority over other statuses.""" + tenant_id = str(uuid.uuid4()) + scan_id = str(uuid.uuid4()) + modeled_threatscore_compliance_id = "ProwlerThreatScore-1.0" + + # First finding with PASS status + mock_finding1 = MagicMock() + mock_finding1.check_id = "check1" + mock_finding1.status = "PASS" + mock_finding1.compliance = {} + mock_resource1 = MagicMock() + mock_resource1.region = "us-east-1" + mock_finding1.small_resources = [mock_resource1] + + # Second finding with FAIL status for same check/region + mock_finding2 = MagicMock() + mock_finding2.check_id = "check1" + mock_finding2.status = "FAIL" + mock_finding2.compliance = {} + mock_resource2 = MagicMock() + mock_resource2.region = "us-east-1" + mock_finding2.small_resources = [mock_resource2] + + mock_queryset = MagicMock() + mock_queryset.only.return_value = mock_queryset + mock_queryset.prefetch_related.return_value = [mock_finding1, mock_finding2] + + ctx = MagicMock() + ctx.__enter__.return_value = None + ctx.__exit__.return_value = False + mock_rls_transaction.return_value = ctx + mock_findings_filter.return_value = mock_queryset + + check_status_by_region, _ = _aggregate_findings_by_region( + tenant_id, scan_id, modeled_threatscore_compliance_id + ) + + # FAIL should override PASS + assert check_status_by_region["us-east-1"]["check1"] == "FAIL" + + @patch("tasks.jobs.scan.Finding.all_objects.filter") + @patch("tasks.jobs.scan.rls_transaction") + def test_aggregate_findings_by_region_filters_muted( + self, mock_rls_transaction, mock_findings_filter + ): + """Test that muted findings are filtered out (muted=False in query).""" + tenant_id = str(uuid.uuid4()) + scan_id = str(uuid.uuid4()) + modeled_threatscore_compliance_id = "ProwlerThreatScore-1.0" + + mock_queryset = MagicMock() + mock_queryset.only.return_value = mock_queryset + mock_queryset.prefetch_related.return_value = [] + + ctx = MagicMock() + ctx.__enter__.return_value = None + ctx.__exit__.return_value = False + mock_rls_transaction.return_value = ctx + mock_findings_filter.return_value = mock_queryset + + _aggregate_findings_by_region( + tenant_id, scan_id, modeled_threatscore_compliance_id + ) + + # Verify filter was called with muted=False + mock_findings_filter.assert_called_once_with( + tenant_id=tenant_id, scan_id=scan_id, muted=False + ) + + @patch("tasks.jobs.scan.Finding.all_objects.filter") + @patch("tasks.jobs.scan.rls_transaction") + def test_aggregate_findings_by_region_processes_compliance_counts( + self, mock_rls_transaction, mock_findings_filter + ): + """Test that ThreatScore compliance counts are processed correctly.""" + tenant_id = str(uuid.uuid4()) + scan_id = str(uuid.uuid4()) + modeled_threatscore_compliance_id = "ProwlerThreatScore-1.0" + + # Finding with PASS status + mock_finding1 = MagicMock() + mock_finding1.check_id = "check1" + mock_finding1.status = "PASS" + mock_finding1.compliance = {modeled_threatscore_compliance_id: ["req1"]} + mock_resource1 = MagicMock() + mock_resource1.region = "us-east-1" + mock_finding1.small_resources = [mock_resource1] + + # Finding with FAIL status + mock_finding2 = MagicMock() + mock_finding2.check_id = "check2" + mock_finding2.status = "FAIL" + mock_finding2.compliance = {modeled_threatscore_compliance_id: ["req1"]} + mock_resource2 = MagicMock() + mock_resource2.region = "us-east-1" + mock_finding2.small_resources = [mock_resource2] + + mock_queryset = MagicMock() + mock_queryset.only.return_value = mock_queryset + mock_queryset.prefetch_related.return_value = [mock_finding1, mock_finding2] + + ctx = MagicMock() + ctx.__enter__.return_value = None + ctx.__exit__.return_value = False + mock_rls_transaction.return_value = ctx + mock_findings_filter.return_value = mock_queryset + + _, findings_count_by_compliance = _aggregate_findings_by_region( + tenant_id, scan_id, modeled_threatscore_compliance_id + ) + + # Verify compliance counts + normalized_id = re.sub( + r"[^a-z0-9]", "", modeled_threatscore_compliance_id.lower() + ) + assert "us-east-1" in findings_count_by_compliance + assert normalized_id in findings_count_by_compliance["us-east-1"] + assert "req1" in findings_count_by_compliance["us-east-1"][normalized_id] + + req_stats = findings_count_by_compliance["us-east-1"][normalized_id]["req1"] + assert req_stats["total"] == 2 + assert req_stats["pass"] == 1 + + @patch("tasks.jobs.scan.Finding.all_objects.filter") + @patch("tasks.jobs.scan.rls_transaction") + def test_aggregate_findings_by_region_multiple_regions( + self, mock_rls_transaction, mock_findings_filter + ): + """Test aggregation across multiple regions.""" + tenant_id = str(uuid.uuid4()) + scan_id = str(uuid.uuid4()) + modeled_threatscore_compliance_id = "ProwlerThreatScore-1.0" + + # Finding in us-east-1 + mock_finding1 = MagicMock() + mock_finding1.check_id = "check1" + mock_finding1.status = "FAIL" + mock_finding1.compliance = {} + mock_resource1 = MagicMock() + mock_resource1.region = "us-east-1" + mock_finding1.small_resources = [mock_resource1] + + # Finding in us-west-2 + mock_finding2 = MagicMock() + mock_finding2.check_id = "check1" + mock_finding2.status = "PASS" + mock_finding2.compliance = {} + mock_resource2 = MagicMock() + mock_resource2.region = "us-west-2" + mock_finding2.small_resources = [mock_resource2] + + mock_queryset = MagicMock() + mock_queryset.only.return_value = mock_queryset + mock_queryset.prefetch_related.return_value = [mock_finding1, mock_finding2] + + ctx = MagicMock() + ctx.__enter__.return_value = None + ctx.__exit__.return_value = False + mock_rls_transaction.return_value = ctx + mock_findings_filter.return_value = mock_queryset + + check_status_by_region, _ = _aggregate_findings_by_region( + tenant_id, scan_id, modeled_threatscore_compliance_id + ) + + # Verify both regions are present with correct statuses + assert "us-east-1" in check_status_by_region + assert "us-west-2" in check_status_by_region + assert check_status_by_region["us-east-1"]["check1"] == "FAIL" + assert check_status_by_region["us-west-2"]["check1"] == "PASS" + + @patch("tasks.jobs.scan.Finding.all_objects.filter") + @patch("tasks.jobs.scan.rls_transaction") + def test_aggregate_findings_by_region_empty_findings( + self, mock_rls_transaction, mock_findings_filter + ): + """Test with no findings - should return empty dicts.""" + tenant_id = str(uuid.uuid4()) + scan_id = str(uuid.uuid4()) + modeled_threatscore_compliance_id = "ProwlerThreatScore-1.0" + + mock_queryset = MagicMock() + mock_queryset.only.return_value = mock_queryset + mock_queryset.prefetch_related.return_value = [] + + ctx = MagicMock() + ctx.__enter__.return_value = None + ctx.__exit__.return_value = False + mock_rls_transaction.return_value = ctx + mock_findings_filter.return_value = mock_queryset + + check_status_by_region, findings_count_by_compliance = ( + _aggregate_findings_by_region( + tenant_id, scan_id, modeled_threatscore_compliance_id + ) + ) + + assert check_status_by_region == {} + assert findings_count_by_compliance == {} diff --git a/dashboard/compliance/fedramp_20x_ksi_low_aws.py b/dashboard/compliance/fedramp_20x_ksi_low_aws.py new file mode 100644 index 0000000000..5ca220301f --- /dev/null +++ b/dashboard/compliance/fedramp_20x_ksi_low_aws.py @@ -0,0 +1,46 @@ +import warnings + +from dashboard.common_methods import get_section_containers_cis + +warnings.filterwarnings("ignore") + + +def get_table(data): + aux = data[ + [ + "REQUIREMENTS_ID", + "REQUIREMENTS_DESCRIPTION", + "REQUIREMENTS_ATTRIBUTES_SECTION", + "CHECKID", + "STATUS", + "REGION", + "ACCOUNTID", + "RESOURCEID", + ] + ].copy() + + # Shorten the long FedRAMP KSI descriptions for better display + ksi_short_names = { + "A secure cloud service offering will protect user data, control access, and apply zero trust principles": "Identity and Access Management", + "A secure cloud service offering will use cloud native architecture and design principles to enforce and enhance the Confidentiality, Integrity and Availability of the system": "Cloud Native Architecture", + "A secure cloud service provider will ensure that all system changes are properly documented and configuration baselines are updated accordingly": "Change Management", + "A secure cloud service provider will continuously educate their employees on cybersecurity measures, testing them regularly": "Cybersecurity Education", + "A secure cloud service offering will document, report, and analyze security incidents to ensure regulatory compliance and continuous security improvement": "Incident Reporting", + "A secure cloud service offering will monitor, log, and audit all important events, activity, and changes": "Monitoring, Logging, and Auditing", + "A secure cloud service offering will have intentional, organized, universal guidance for how every information resource, including personnel, is secured": "Policy and Inventory", + "A secure cloud service offering will define, maintain, and test incident response plan(s) and recovery capabilities to ensure minimal service disruption and data loss": "Recovery Planning", + "A secure cloud service offering will follow FedRAMP encryption policies, continuously verify information resource integrity, and restrict access to third-party information resources": "Service Configuration", + "A secure cloud service offering will understand, monitor, and manage supply chain risks from third-party information resources": "Third-Party Information Resources", + } + + # Replace long descriptions with short names - use contains for partial matching + if not aux.empty: + for long_desc, short_name in ksi_short_names.items(): + mask = aux["REQUIREMENTS_DESCRIPTION"].str.contains( + long_desc, na=False, regex=False + ) + aux.loc[mask, "REQUIREMENTS_DESCRIPTION"] = short_name + + return get_section_containers_cis( + aux, "REQUIREMENTS_ID", "REQUIREMENTS_ATTRIBUTES_SECTION" + ) diff --git a/dashboard/compliance/fedramp_20x_ksi_low_azure.py b/dashboard/compliance/fedramp_20x_ksi_low_azure.py new file mode 100644 index 0000000000..5ca220301f --- /dev/null +++ b/dashboard/compliance/fedramp_20x_ksi_low_azure.py @@ -0,0 +1,46 @@ +import warnings + +from dashboard.common_methods import get_section_containers_cis + +warnings.filterwarnings("ignore") + + +def get_table(data): + aux = data[ + [ + "REQUIREMENTS_ID", + "REQUIREMENTS_DESCRIPTION", + "REQUIREMENTS_ATTRIBUTES_SECTION", + "CHECKID", + "STATUS", + "REGION", + "ACCOUNTID", + "RESOURCEID", + ] + ].copy() + + # Shorten the long FedRAMP KSI descriptions for better display + ksi_short_names = { + "A secure cloud service offering will protect user data, control access, and apply zero trust principles": "Identity and Access Management", + "A secure cloud service offering will use cloud native architecture and design principles to enforce and enhance the Confidentiality, Integrity and Availability of the system": "Cloud Native Architecture", + "A secure cloud service provider will ensure that all system changes are properly documented and configuration baselines are updated accordingly": "Change Management", + "A secure cloud service provider will continuously educate their employees on cybersecurity measures, testing them regularly": "Cybersecurity Education", + "A secure cloud service offering will document, report, and analyze security incidents to ensure regulatory compliance and continuous security improvement": "Incident Reporting", + "A secure cloud service offering will monitor, log, and audit all important events, activity, and changes": "Monitoring, Logging, and Auditing", + "A secure cloud service offering will have intentional, organized, universal guidance for how every information resource, including personnel, is secured": "Policy and Inventory", + "A secure cloud service offering will define, maintain, and test incident response plan(s) and recovery capabilities to ensure minimal service disruption and data loss": "Recovery Planning", + "A secure cloud service offering will follow FedRAMP encryption policies, continuously verify information resource integrity, and restrict access to third-party information resources": "Service Configuration", + "A secure cloud service offering will understand, monitor, and manage supply chain risks from third-party information resources": "Third-Party Information Resources", + } + + # Replace long descriptions with short names - use contains for partial matching + if not aux.empty: + for long_desc, short_name in ksi_short_names.items(): + mask = aux["REQUIREMENTS_DESCRIPTION"].str.contains( + long_desc, na=False, regex=False + ) + aux.loc[mask, "REQUIREMENTS_DESCRIPTION"] = short_name + + return get_section_containers_cis( + aux, "REQUIREMENTS_ID", "REQUIREMENTS_ATTRIBUTES_SECTION" + ) diff --git a/dashboard/compliance/fedramp_20x_ksi_low_gcp.py b/dashboard/compliance/fedramp_20x_ksi_low_gcp.py new file mode 100644 index 0000000000..5ca220301f --- /dev/null +++ b/dashboard/compliance/fedramp_20x_ksi_low_gcp.py @@ -0,0 +1,46 @@ +import warnings + +from dashboard.common_methods import get_section_containers_cis + +warnings.filterwarnings("ignore") + + +def get_table(data): + aux = data[ + [ + "REQUIREMENTS_ID", + "REQUIREMENTS_DESCRIPTION", + "REQUIREMENTS_ATTRIBUTES_SECTION", + "CHECKID", + "STATUS", + "REGION", + "ACCOUNTID", + "RESOURCEID", + ] + ].copy() + + # Shorten the long FedRAMP KSI descriptions for better display + ksi_short_names = { + "A secure cloud service offering will protect user data, control access, and apply zero trust principles": "Identity and Access Management", + "A secure cloud service offering will use cloud native architecture and design principles to enforce and enhance the Confidentiality, Integrity and Availability of the system": "Cloud Native Architecture", + "A secure cloud service provider will ensure that all system changes are properly documented and configuration baselines are updated accordingly": "Change Management", + "A secure cloud service provider will continuously educate their employees on cybersecurity measures, testing them regularly": "Cybersecurity Education", + "A secure cloud service offering will document, report, and analyze security incidents to ensure regulatory compliance and continuous security improvement": "Incident Reporting", + "A secure cloud service offering will monitor, log, and audit all important events, activity, and changes": "Monitoring, Logging, and Auditing", + "A secure cloud service offering will have intentional, organized, universal guidance for how every information resource, including personnel, is secured": "Policy and Inventory", + "A secure cloud service offering will define, maintain, and test incident response plan(s) and recovery capabilities to ensure minimal service disruption and data loss": "Recovery Planning", + "A secure cloud service offering will follow FedRAMP encryption policies, continuously verify information resource integrity, and restrict access to third-party information resources": "Service Configuration", + "A secure cloud service offering will understand, monitor, and manage supply chain risks from third-party information resources": "Third-Party Information Resources", + } + + # Replace long descriptions with short names - use contains for partial matching + if not aux.empty: + for long_desc, short_name in ksi_short_names.items(): + mask = aux["REQUIREMENTS_DESCRIPTION"].str.contains( + long_desc, na=False, regex=False + ) + aux.loc[mask, "REQUIREMENTS_DESCRIPTION"] = short_name + + return get_section_containers_cis( + aux, "REQUIREMENTS_ID", "REQUIREMENTS_ATTRIBUTES_SECTION" + ) diff --git a/dashboard/compliance/nist_csf_2_0_aws.py b/dashboard/compliance/nist_csf_2_0_aws.py new file mode 100644 index 0000000000..07b956b104 --- /dev/null +++ b/dashboard/compliance/nist_csf_2_0_aws.py @@ -0,0 +1,24 @@ +import warnings + +from dashboard.common_methods import get_section_containers_format3 + +warnings.filterwarnings("ignore") + + +def get_table(data): + aux = data[ + [ + "REQUIREMENTS_ID", + "REQUIREMENTS_ATTRIBUTES_SECTION", + "REQUIREMENTS_DESCRIPTION", + "CHECKID", + "STATUS", + "REGION", + "ACCOUNTID", + "RESOURCEID", + ] + ].copy() + + return get_section_containers_format3( + aux, "REQUIREMENTS_ATTRIBUTES_SECTION", "REQUIREMENTS_ID" + ) diff --git a/docs/developer-guide/documentation.mdx b/docs/developer-guide/documentation.mdx index a7a4e97d4e..f1fae30d35 100644 --- a/docs/developer-guide/documentation.mdx +++ b/docs/developer-guide/documentation.mdx @@ -4,7 +4,26 @@ title: 'Contributing to Documentation' Prowler documentation is built using [Mintlify](https://www.mintlify.com/docs), allowing contributors to easily add or enhance documentation. -## Installation and Setup +## Documentation Structure + +The Prowler documentation is organized into several sections. The main ones are: + +- **Getting Started**: Provides an overview of the Prowler platform and its different solutions, including Prowler Cloud/App, Prowler CLI, Prowler MCP Server, Prowler Hub, and Prowler Lighthouse AI. This section helps new users understand which Prowler solution best fits their needs and includes product comparisons. + +- **Guides**: Contains practical tutorials and how-to guides organized by product (Prowler Cloud/App, CLI) and provider (AWS, Azure, GCP, Kubernetes, Microsoft 365, GitHub, etc.). This section covers authentication, integrations, compliance, and advanced usage scenarios. + +- **Developer Guide**: Documentation for contributors looking to extend Prowler functionality. This includes guides on creating providers, services, checks, output formats, integrations, and compliance frameworks. Provider-specific implementation details and testing strategies are also covered here. + +- **Troubleshooting**: Common issues, error messages, and their solutions. This section helps users resolve problems encountered during installation, configuration, or execution. + + +## AI-Driven Documentation + +As mentioned in the [Introduction](/developer-guide/introduction#ai-driven-contributions), we have specialized resources to enhance AI-driven development. + +This includes the [AGENTS.md](https://github.com/prowler-cloud/prowler/blob/master/docs/AGENTS.md) file that contains the guidelines and style guide for the AI agents in the Prowler documentation. + +## Local Development @@ -33,10 +52,10 @@ Prowler documentation is built using [Mintlify](https://www.mintlify.com/docs), - Once documentation updates are complete, submit a pull request for review. + Once documentation updates are complete, [submit a pull request for review](/developer-guide/introduction#sending-the-pull-request). The Prowler team will assess and merge contributions. -Your efforts help improve Prowler documentation—thank you for contributing! +Your efforts help improve Prowler documentation. Thank you for contributing! 🤘 diff --git a/docs/developer-guide/introduction.mdx b/docs/developer-guide/introduction.mdx index 5361d4460a..9d1ea742b1 100644 --- a/docs/developer-guide/introduction.mdx +++ b/docs/developer-guide/introduction.mdx @@ -2,19 +2,70 @@ title: 'Introduction to developing in Prowler' --- -Extending Prowler +Thanks for your interest in contributing to Prowler! -Prowler can be extended in various ways, with common use cases including: +Prowler can be extended in various ways. This guide provides the different ways to contribute and how to get started. -- New security checks -- New compliance frameworks -- New output formats -- New integrations -- New proposed features +## Contributing to Prowler -All the relevant information for these cases is included in this guide. +### Review Current Issues +Check out our [GitHub Issues](https://github.com/prowler-cloud/prowler/issues) page for ideas to contribute. + + + We tag issues as `good first issue` for new contributors. These are typically well-defined and manageable in scope. + + + We tag issues as `help wanted` for other issues that require more time to complete. + + -## Getting the Code and Installing All Dependencies +### Expand Prowler's Capabilities +Prowler is constantly evolving. Contributions to checks, services, or integrations help improve the tool for everyone. Here is how to get involved: + + + + Want to improve Prowler's detection capabilities for your favorite cloud provider? You can contribute by writing new checks. + + + One key service for your favorite cloud provider is missing? Add it to Prowler! Do not forget to include relevant checks to validate functionality. + + + If you would like to extend Prowler to work with a new cloud provider, this typically involves setting up new services and checks to ensure compatibility. + + + Want to tailor how results are displayed or exported? You can add custom output formats. + + + Prowler can work with other tools and platforms through integrations. + + + Propose brand-new features or enhancements to existing ones, or help implement community-requested improvements. + + + +### Improve Documentation +Help make Prowler more accessible by enhancing our documentation, fixing typos, or adding examples/tutorials. + + + + Enhance our documentation, fix typos, or add examples/tutorials. + + + +### Bug Fixes +If you find any issues or bugs, you can report them in the [GitHub Issues](https://github.com/prowler-cloud/prowler/issues) page and if you want you can also fix them. + + + + Report or fix issues or bugs. + + + +Remember, our community is here to help! If you need guidance, do not hesitate to ask questions in the issues or join our [ Slack workspace](https://goto.prowler.com/slack). + + + +## Setting up your development environment ### Prerequisites @@ -26,11 +77,11 @@ Before proceeding, ensure the following: ### Forking the Prowler Repository -To contribute to Prowler, fork the Prowler GitHub repository. This allows you to propose changes, submit new features, and fix bugs. For guidance on forking, refer to the [official GitHub documentation](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/fork-a-repo?tool=webui#forking-a-repository). +Fork the Prowler GitHub repository to contribute to Prowler. This allows proposing changes, submitting new features, and fixing bugs. For guidance on forking, refer to the [official GitHub documentation](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/fork-a-repo?tool=webui#forking-a-repository). ### Cloning Your Forked Repository -Once your fork is created, clone it using the following commands: +Once your fork is created, clone it using the following commands (replace `` with your GitHub username): ``` git clone https://github.com//prowler @@ -56,39 +107,7 @@ If your poetry version is below 2.0.0 you must keep using `poetry shell` to acti In case you have any doubts, consult the [Poetry environment activation guide](https://python-poetry.org/docs/managing-environments/#activating-the-environment). -## Contributing to Prowler -### Ways to Contribute - -Here are some ideas for collaborating with Prowler: - -1. **Review Current Issues**: Check out our [GitHub Issues](https://github.com/prowler-cloud/prowler/issues) page. We often tag issues as `good first issue` - these are perfect for new contributors as they are typically well-defined and manageable in scope. - -2. **Expand Prowler's Capabilities**: Prowler is constantly evolving, and you can be a part of its growth. Whether you are adding checks, supporting new services, or introducing integrations, your contributions help improve the tool for everyone. Here is how you can get involved: - - - **Adding New Checks** - Want to improve Prowler's detection capabilities for your favorite cloud provider? You can contribute by writing new checks. To get started, follow the [create a new check guide](/developer-guide/checks). - - - **Adding New Services** - One key service for your favorite cloud provider is missing? Add it to Prowler! To add a new service, check out the [create a new service guide](/developer-guide/services). Do not forget to include relevant checks to validate functionality. - - - **Adding New Providers** - If you would like to extend Prowler to work with a new cloud provider, follow the [create a new provider guide](/developer-guide/provider). This typically involves setting up new services and checks to ensure compatibility. - - - **Adding New Output Formats** - Want to tailor how results are displayed or exported? You can add custom output formats by following the [create a new output format guide](/developer-guide/outputs). - - - **Adding New Integrations** - Prowler can work with other tools and platforms through integrations. If you would like to add one, see the [create a new integration guide](/developer-guide/integrations). - - - **Proposing or Implementing Features** - Got an idea to make Prowler better? Whether it is a brand-new feature or an enhancement to an existing one, you are welcome to propose it or help implement community-requested improvements. - -3. **Improve Documentation**: Help make Prowler more accessible by enhancing our documentation, fixing typos, or adding examples/tutorials. See the tutorial of how we write our documentation [here](/developer-guide/documentation). - -4. **Bug Fixes**: If you find any issues or bugs, you can report them in the [GitHub Issues](https://github.com/prowler-cloud/prowler/issues) page and if you want you can also fix them. - -Remember, our community is here to help! If you need guidance, do not hesitate to ask questions in the issues or join our [Slack workspace](https://goto.prowler.com/slack). ### Pre-Commit Hooks @@ -121,6 +140,16 @@ These should have been already installed if `poetry install --with dev` was alre Additionally, ensure the latest version of [`TruffleHog`](https://github.com/trufflesecurity/trufflehog) is installed to scan for sensitive data in the code. Follow the official [installation guide](https://github.com/trufflesecurity/trufflehog?tab=readme-ov-file#floppy_disk-installation) for setup. +### AI-Driven Contributions + +If you are using AI assistants to help with your contributions, Prowler provides specialized resources to enhance AI-driven development: + +- **Prowler MCP Server**: The [Prowler MCP Server](/getting-started/products/prowler-mcp) provides AI assistants with access to the entire Prowler ecosystem, including security checks, compliance frameworks, documentation, and more. This enables AI tools to better understand Prowler's architecture and help you create contributions that align with project standards. + +- **AGENTS.md Files**: Each component of the Prowler monorepo includes an `AGENTS.md` file that contains specific guidelines for AI agents working on that component. These files provide context about project structure, coding standards, and best practices. When working on a specific component, refer to the relevant `AGENTS.md` file (e.g., `prowler/AGENTS.md`, `ui/AGENTS.md`, `api/AGENTS.md`) to ensure your AI assistant follows the appropriate guidelines. + +These resources help ensure that AI-assisted contributions maintain consistency with Prowler's codebase and development practices. + ### Dependency Management All dependencies are listed in the `pyproject.toml` file. @@ -133,7 +162,7 @@ If you encounter issues when committing to the Prowler repository, use the `--no ### Repository Folder Structure -Understanding the layout of the Prowler codebase will help you quickly find where to add new features, checks, or integrations. The following is a high-level overview from the root of the repository: +The Prowler codebase layout helps quickly locate where to add new features, checks, or integrations. The following is a high-level overview from the root of the repository: ``` prowler/ @@ -148,7 +177,7 @@ prowler/ ├── permissions/ # Permission-related files and policies ├── contrib/ # Community-contributed scripts or modules ├── kubernetes/ # Kubernetes deployment files -├── .github/ # GitHub related files (workflows, issue templates, etc.) +├── .github/ # GitHub-related files (workflows, issue templates, etc.) ├── pyproject.toml # Python project configuration (Poetry) ├── poetry.lock # Poetry lock file ├── README.md # Project overview and getting started @@ -158,19 +187,23 @@ prowler/ └── ... # Other supporting files ``` -## Pull Request Checklist +## Sending the Pull Request -When creating or reviewing a pull request in https://github.com/prowler-cloud/prowler, follow [this checklist](https://github.com/prowler-cloud/prowler/blob/master/.github/pull_request_template.md#checklist). +When creating or reviewing a pull request in [Prowler](https://github.com/prowler-cloud/prowler), follow [this template](https://github.com/prowler-cloud/prowler/blob/master/.github/pull_request_template.md) and fill it with the relevant information: + +- **Context** and **Description** of the change: This will help the reviewers to understand the change and the purpose of the pull request. +- **Steps to review**: A detailed description of how to review the change. +- **Checklist**: A mandatory checklist of the things that should be reviewed before merging the pull request. ## Contribution Appreciation -If you enjoy swag, we’d love to thank you for your contribution with laptop stickers or other Prowler merchandise! +If you enjoy swag, we'd love to thank you for your contribution with laptop stickers or other Prowler merchandise! To request swag: Share your pull request details in our [Slack workspace](https://goto.prowler.com/slack). You can also reach out to Toni de la Fuente on [Twitter](https://twitter.com/ToniBlyx)—his DMs are open! -# Testing a Pull Request from a Specific Branch +## Testing a Pull Request from a Specific Branch To test Prowler from a specific branch (for example, to try out changes from a pull request before it is merged), you can use `pipx` to install directly from GitHub: @@ -179,3 +212,5 @@ pipx install "git+https://github.com/prowler-cloud/prowler.git@branch-name" ``` Replace `branch-name` with the name of the branch you want to test. This will install Prowler in an isolated environment, allowing you to try out the changes safely. + +For more details on testing go to the [Testing section](/developer-guide/unit-testing) of this documentation. \ No newline at end of file diff --git a/docs/developer-guide/kubernetes-details.mdx b/docs/developer-guide/kubernetes-details.mdx index fa0c9291f6..0ccda94f38 100644 --- a/docs/developer-guide/kubernetes-details.mdx +++ b/docs/developer-guide/kubernetes-details.mdx @@ -4,7 +4,7 @@ title: 'Kubernetes Provider' This page details the [Kubernetes](https://kubernetes.io/) provider implementation in Prowler. -By default, Prowler will audit all namespaces in the Kubernetes cluster accessible by the configured context. To configure it, see the [In-Cluster Execution](/user-guide/providers/kubernetes/in-cluster) or [Non In-Cluster Execution](/user-guide/providers/kubernetes/outside-cluster) guides. +By default, Prowler will audit all namespaces in the Kubernetes cluster accessible by the configured context. To configure it, see the [In-Cluster Execution](/user-guide/providers/kubernetes/getting-started-k8s#in-cluster-execution) or [Non In-Cluster Execution](/user-guide/providers/kubernetes/getting-started-k8s#non-in-cluster-execution) guides. ## Kubernetes Provider Classes Architecture diff --git a/docs/docs.json b/docs/docs.json index 54402e5d8a..7d3f795482 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -110,6 +110,7 @@ ] }, "user-guide/tutorials/prowler-app-lighthouse", + "user-guide/tutorials/prowler-cloud-public-ips", { "group": "Tutorials", "pages": [ @@ -194,8 +195,7 @@ { "group": "Kubernetes", "pages": [ - "user-guide/providers/kubernetes/in-cluster", - "user-guide/providers/kubernetes/outside-cluster", + "user-guide/providers/kubernetes/getting-started-k8s", "user-guide/providers/kubernetes/misc" ] }, diff --git a/docs/getting-started/products/prowler-mcp.mdx b/docs/getting-started/products/prowler-mcp.mdx index 40d627007c..94a5466edb 100644 --- a/docs/getting-started/products/prowler-mcp.mdx +++ b/docs/getting-started/products/prowler-mcp.mdx @@ -5,7 +5,7 @@ title: "Overview" **Prowler MCP Server** brings the entire Prowler ecosystem to AI assistants through the Model Context Protocol (MCP). It enables seamless integration with AI tools like Claude Desktop, Cursor, and other MCP clients, allowing interaction with Prowler's security capabilities through natural language. -**Preview Feature**: This MCP server is currently in preview and under active development. Features and functionality may change. We welcome your feedback—please report any issues on [GitHub](https://github.com/prowler-cloud/prowler/issues) or join our [Slack community](https://goto.prowler.com/slack) to discuss and share your thoughts. +**Preview Feature**: This MCP server is currently under active development. Features and functionality may change. We welcome your feedback—please report any issues on [GitHub](https://github.com/prowler-cloud/prowler/issues) or join our [Slack community](https://goto.prowler.com/slack) to discuss and share your thoughts. ## What is the Model Context Protocol? @@ -42,6 +42,15 @@ Search and retrieve official Prowler documentation: - **Contextual Results**: Get relevant documentation pages with highlighted snippets. - **Document Retrieval**: Access complete markdown content of any documentation file. +## MCP Server Architecture + +The following diagram illustrates the Prowler MCP Server architecture and its integration points: + +Prowler MCP Server Schema +Prowler MCP Server Schema + +The architecture shows how AI assistants connect through the MCP protocol to access Prowler's three main components: Prowler Cloud/App for security operations, Prowler Hub for security knowledge, and Prowler Documentation for guidance and reference. + ## Use Cases The Prowler MCP Server enables powerful workflows through AI assistants: diff --git a/docs/images/prowler_mcp_schema_dark.png b/docs/images/prowler_mcp_schema_dark.png new file mode 100644 index 0000000000..7771557601 Binary files /dev/null and b/docs/images/prowler_mcp_schema_dark.png differ diff --git a/docs/images/prowler_mcp_schema_light.png b/docs/images/prowler_mcp_schema_light.png new file mode 100644 index 0000000000..c542d84ed2 Binary files /dev/null and b/docs/images/prowler_mcp_schema_light.png differ diff --git a/docs/introduction.mdx b/docs/introduction.mdx index 616ba34f53..603bd1afbd 100644 --- a/docs/introduction.mdx +++ b/docs/introduction.mdx @@ -28,7 +28,7 @@ The supported providers right now are: | [AWS](/user-guide/providers/aws/getting-started-aws) | Official | UI, API, CLI | | [Azure](/user-guide/providers/azure/getting-started-azure) | Official | UI, API, CLI | | [Google Cloud](/user-guide/providers/gcp/getting-started-gcp) | Official | UI, API, CLI | -| [Kubernetes](/user-guide/providers/kubernetes/in-cluster) | Official | UI, API, CLI | +| [Kubernetes](/user-guide/providers/kubernetes/getting-started-k8s) | Official | UI, API, CLI | | [M365](/user-guide/providers/microsoft365/getting-started-m365) | Official | UI, API, CLI | | [Github](/user-guide/providers/github/getting-started-github) | Official | UI, API, CLI | | [Oracle Cloud](/user-guide/providers/oci/getting-started-oci) | Official | UI, API, CLI | diff --git a/docs/user-guide/cli/tutorials/compliance.mdx b/docs/user-guide/cli/tutorials/compliance.mdx index da4d15e5c7..8754be6237 100644 --- a/docs/user-guide/cli/tutorials/compliance.mdx +++ b/docs/user-guide/cli/tutorials/compliance.mdx @@ -24,7 +24,7 @@ Standard results will be shown and additionally the framework information as the **If Prowler can't find a resource related with a check from a compliance requirement, this requirement won't appear on the output** -## List Available Compliance Frameworks +## List Available Compliance Frameworks To see which compliance frameworks are covered by Prowler, use the `--list-compliance` option: @@ -34,7 +34,7 @@ prowler --list-compliance Or you can visit [Prowler Hub](https://hub.prowler.com/compliance). -## List Requirements of Compliance Frameworks +## List Requirements of Compliance Frameworks To list requirements for a compliance framework, use the `--list-compliance-requirements` option: ```sh diff --git a/docs/user-guide/cli/tutorials/configuration_file.mdx b/docs/user-guide/cli/tutorials/configuration_file.mdx index 819c17e9ca..c2f886b3f3 100644 --- a/docs/user-guide/cli/tutorials/configuration_file.mdx +++ b/docs/user-guide/cli/tutorials/configuration_file.mdx @@ -94,7 +94,7 @@ The following list includes all the Azure checks with configurable variables tha ### Configurable Checks -## Kubernetes +## Kubernetes ### Configurable Checks The following list includes all the Kubernetes checks with configurable variables that can be changed in the configuration yaml file: diff --git a/docs/user-guide/cli/tutorials/integrations.mdx b/docs/user-guide/cli/tutorials/integrations.mdx index 2667b81c50..f3e698d799 100644 --- a/docs/user-guide/cli/tutorials/integrations.mdx +++ b/docs/user-guide/cli/tutorials/integrations.mdx @@ -2,7 +2,7 @@ title: 'Integrations' --- -## Integration with Slack +## Integration with Slack Prowler can be integrated with [Slack](https://slack.com/) to send a summary of the execution having configured a Slack APP in your channel with the following command: diff --git a/docs/user-guide/cli/tutorials/misc.mdx b/docs/user-guide/cli/tutorials/misc.mdx index 9921f89032..0940508ed7 100644 --- a/docs/user-guide/cli/tutorials/misc.mdx +++ b/docs/user-guide/cli/tutorials/misc.mdx @@ -14,7 +14,7 @@ prowler -V/-v/--version Prowler provides various execution settings. -### Verbose Execution +### Verbose Execution To enable verbose mode in Prowler, similar to Version 2, use: @@ -54,7 +54,7 @@ To run Prowler without color formatting: prowler --no-color ``` -### Checks in Prowler +### Checks in Prowler Prowler provides various security checks per cloud provider. Use the following options to list, execute, or exclude specific checks: @@ -96,7 +96,7 @@ prowler -e/--excluded-checks ec2 rds prowler -C/--checks-file .json ``` -## Custom Checks in Prowler +## Custom Checks in Prowler Prowler supports custom security checks, allowing users to define their own logic. diff --git a/docs/user-guide/cli/tutorials/mutelist.mdx b/docs/user-guide/cli/tutorials/mutelist.mdx index 4bb7524fa6..79292f49b3 100644 --- a/docs/user-guide/cli/tutorials/mutelist.mdx +++ b/docs/user-guide/cli/tutorials/mutelist.mdx @@ -19,15 +19,45 @@ The Mutelist option works in combination with other filtering mechanisms and mod ## How the Mutelist Works -The **Mutelist** uses both "AND" and "OR" logic to determine which resources, checks, regions, and tags should be muted. For each check, the Mutelist evaluates whether the account, region, and resource match the specified criteria using "AND" logic. If tags are specified, the Mutelist can apply either "AND" or "OR" logic. +The **Mutelist** uses **AND logic** to evaluate whether a finding should be muted. For a finding to be muted, **ALL** of the following conditions must match: -If any of the criteria do not match, the check is not muted. +- **Account** matches (exact match or `*`) +- **Check** matches (exact match, regex pattern, or `*`) +- **Region** matches (exact match, regex pattern, or `*`) +- **Resource** matches (exact match, regex pattern, or `*`) +- **Tags** match (if specified) + +If **any** of these criteria do not match, the finding is **not muted**. + +### Tag Matching Logic + +Tags have special matching behavior: + +- **Multiple tags in the list = AND logic**: ALL tags must be present on the resource + ```yaml + Tags: + - "environment=dev" + - "team=backend" # BOTH tags required + ``` + +- **Regex alternation within a single tag = OR logic**: Use the pipe operator `|` for OR + ```yaml + Tags: + - "environment=dev|environment=stg" # Matches EITHER dev OR stg + ``` + +- **Complex tag patterns**: Combine AND and OR using regex + ```yaml + Tags: + - "team=backend" # Required + - "environment=dev|environment=stg" # AND (dev OR stg) + ``` Remember that mutelist can be used with regular expressions. -## Mutelist Specification +## Mutelist Specification - For Azure provider, the Account ID is the Subscription Name and the Region is the Location. @@ -40,9 +70,10 @@ The Mutelist file uses the [YAML](https://en.wikipedia.org/wiki/YAML) format wit ```yaml ### Account, Check and/or Region can be * to apply for all the cases. ### Resources and tags are lists that can have either Regex or Keywords. -### Tags is an optional list that matches on tuples of 'key=value' and are "ANDed" together. -### Use an alternation Regex to match one of multiple tags with "ORed" logic. -### For each check you can except Accounts, Regions, Resources and/or Tags. +### Multiple tags in the list are "ANDed" together (ALL must match). +### Use regex alternation (|) within a single tag for "OR" logic (e.g., "env=dev|env=stg"). +### For each check you can use Exceptions to unmute specific Accounts, Regions, Resources and/or Tags. +### All conditions (Account, Check, Region, Resource, Tags) are ANDed together. ########################### MUTELIST EXAMPLE ########################### Mutelist: Accounts: @@ -148,11 +179,11 @@ Mutelist: | Field| Description| Logic |----------|----------|---------- -| `account_id`| Use `*` to apply the mutelist to all accounts.| `ANDed` -| `check_name`| The name of the Prowler check. Use `*` to apply the mutelist to all checks, or `service_*` to apply it to all service's checks.| `ANDed` -| `region`| The region identifier. Use `*` to apply the mutelist to all regions.| `ANDed` -| `resource`| The resource identifier. Use `*` to apply the mutelist to all resources.| `ANDed` -| `tag`| The tag value.| `ORed` +| `account_id`| Use `*` to apply the mutelist to all accounts. Supports exact match or wildcard.| `AND` (with other fields) +| `check_name`| The name of the Prowler check. Use `*` to apply the mutelist to all checks, or `service_*` to apply it to all service's checks. Supports regex patterns.| `AND` (with other fields) +| `region`| The region identifier. Use `*` to apply the mutelist to all regions. Supports regex patterns.| `AND` (with other fields) +| `resource`| The resource identifier. Use `*` to apply the mutelist to all resources. Supports regex patterns.| `AND` (with other fields) +| `tags`| List of tag patterns in `key=value` format. **Multiple tags = AND** (all must match). **Regex alternation within single tag = OR** (use `tag1\|tag2`).| `AND` between tags, `OR` within regex ### Description @@ -173,6 +204,68 @@ Replace `` with the appropriate provider name. - The Mutelist can be used in combination with other Prowler options, such as the `--service` or `--checks` option, to further customize the scanning process. - Make sure to review and update the Mutelist regularly to ensure it reflects the desired exclusions and remains up to date with your infrastructure. +## Current Limitations and Workarounds + +### Limitation: No OR Logic Between Different Rule Sets + +The current Mutelist schema **does not support OR logic** between different condition sets. Each check can have only **one rule object**, and all conditions are **ANDed** together. + +**Example of unsupported scenario:** +```yaml +# ❌ INVALID: Cannot have multiple rule blocks for the same check +Accounts: + "*": + Checks: + "*": # Rule 1 + Regions: ["eu-west-1", "us-west-2"] + Resources: ["*"] + "*": # Rule 2 - This will OVERWRITE Rule 1 (YAML duplicate key) + Regions: ["us-east-1"] + Tags: ["environment=dev"] +``` + +**Workaround: Use multiple scans with different mutelists** + +For complex scenarios requiring OR logic, run separate scans: + +```bash +# Scan 1: Mute findings in non-critical regions +prowler aws --mutelist-file mutelist_noncritical.yaml + +# Scan 2: Mute dev/stg in critical regions +prowler aws --mutelist-file mutelist_critical.yaml --regions us-east-1,sa-east-1 +``` + +Then merge the outputs in your reporting pipeline. + +### Limitation: Cannot Negate Regions + +You cannot express "all regions **except** X and Y". You must explicitly list all regions you want to mute. + +**Workaround:** +```yaml +# Must enumerate all unwanted regions +Accounts: + "*": + Checks: + "*": + Regions: + - "af-south-1" + - "ap-east-1" + # ... list all regions EXCEPT the ones you want to monitor + Resources: ["*"] +``` + +### Best Practices + +1. **Use regex patterns for flexibility**: Instead of listing multiple resources, use regex patterns like `"dev-.*"` or `"test-instance-[0-9]+"` + +2. **Combine tag OR logic with regex**: Use `"environment=dev|environment=stg|environment=test"` instead of multiple tag entries + +3. **Be specific with exceptions**: Use the `Exceptions` field to unmute specific resources within a broader muting rule + +4. **Test your mutelist**: Run Prowler with `--output-modes json` and verify that the expected findings are muted + ## AWS Mutelist ### Muting specific AWS regions diff --git a/docs/user-guide/cli/tutorials/parallel-execution.mdx b/docs/user-guide/cli/tutorials/parallel-execution.mdx index b364483ace..93b8ef381b 100644 --- a/docs/user-guide/cli/tutorials/parallel-execution.mdx +++ b/docs/user-guide/cli/tutorials/parallel-execution.mdx @@ -10,7 +10,7 @@ This can help for really large accounts, but please be aware of AWS API rate lim 2. **API Rate Limits**: Most of the rate limits in AWS are applied at the API level. Each API call to an AWS service counts towards the rate limit for that service. 3. **Throttling Responses**: When you exceed the rate limit for a service, AWS responds with a throttling error. In AWS SDKs, these are typically represented as `ThrottlingException` or `RateLimitExceeded` errors. -For information on Prowler's retrier configuration please refer to this [page](https://docs.prowler.cloud/en/latest/tutorials/aws/boto3-configuration/). +For information on Prowler's retrier configuration please refer to this [page](https://docs.prowler.com/user-guide/providers/aws/boto3-configuration/). You might need to increase the `--aws-retries-max-attempts` parameter from the default value of 3. The retrier follows an exponential backoff strategy. diff --git a/docs/user-guide/cli/tutorials/quick-inventory.mdx b/docs/user-guide/cli/tutorials/quick-inventory.mdx index 33ce719d19..08519c305c 100644 --- a/docs/user-guide/cli/tutorials/quick-inventory.mdx +++ b/docs/user-guide/cli/tutorials/quick-inventory.mdx @@ -24,6 +24,6 @@ By default, it extracts resources from all the regions, you could use `-f`/`--fi ![Quick Inventory Example](/images/quick-inventory.jpg) -## Objections +## Objections The inventorying process is carried out with `resourcegroupstaggingapi` calls, which means that only resources they have or have had tags will appear (except for the IAM and S3 resources which are done with Boto3 API calls). diff --git a/docs/user-guide/cli/tutorials/reporting.mdx b/docs/user-guide/cli/tutorials/reporting.mdx index 2e2fed88c0..65eec93263 100644 --- a/docs/user-guide/cli/tutorials/reporting.mdx +++ b/docs/user-guide/cli/tutorials/reporting.mdx @@ -22,7 +22,7 @@ prowler --output-formats json-asff All compliance-related reports are automatically generated when Prowler is executed. These outputs are stored in the `/output/compliance` directory. -## Custom Output Flags +## Custom Output Flags By default, Prowler creates a file inside the `output` directory named: `prowler-output-ACCOUNT_NUM-OUTPUT_DATE.format`. @@ -53,13 +53,13 @@ Both flags can be used simultaneously to provide a custom directory and filename By default, the timestamp format of the output files is ISO 8601. This can be changed with the flag `--unix-timestamp` generating the timestamp fields in pure unix timestamp format. -## Supported Output Formats +## Supported Output Formats Prowler natively supports the following reporting output formats: - CSV - JSON-OCSF -- JSON-ASFF +- JSON-ASFF (AWS only) - HTML Hereunder is the structure for each of the supported report formats by Prowler: @@ -285,10 +285,10 @@ The JSON-OCSF output format implements the [Detection Finding](https://schema.oc Each finding is a `json` object within a list. -### JSON-ASFF +### JSON-ASFF (AWS Only) -Only available when using `--security-hub` or `--output-formats json-asff` +Only available when using `--security-hub` or `--output-formats json-asff` with the AWS provider. The following code is an example output of the [JSON-ASFF](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-findings-format-syntax.html) format: diff --git a/docs/user-guide/cli/tutorials/scan-unused-services.mdx b/docs/user-guide/cli/tutorials/scan-unused-services.mdx index 32756cdce0..6d675e159f 100644 --- a/docs/user-guide/cli/tutorials/scan-unused-services.mdx +++ b/docs/user-guide/cli/tutorials/scan-unused-services.mdx @@ -14,7 +14,7 @@ prowler --scan-unused-services ## Services Ignored -### AWS +### AWS #### ACM (AWS Certificate Manager) @@ -22,21 +22,21 @@ Certificates stored in ACM without active usage in AWS resources are excluded. B - `acm_certificates_expiration_check` -#### Athena +#### Athena Upon AWS account creation, Athena provisions a default primary workgroup for the user. Prowler verifies if this workgroup is enabled and used by checking for queries within the last 45 days. If Athena is unused, findings related to its checks will not appear. - `athena_workgroup_encryption` - `athena_workgroup_enforce_configuration` -#### AWS CloudTrail +#### AWS CloudTrail AWS CloudTrail should have at least one trail with a data event to record all S3 object-level API operations. Before flagging this issue, Prowler verifies if S3 buckets exist in the account. - `cloudtrail_s3_dataevents_read_enabled` - `cloudtrail_s3_dataevents_write_enabled` -#### AWS Elastic Compute Cloud (EC2) +#### AWS Elastic Compute Cloud (EC2) If Amazon Elastic Block Store (EBS) default encyption is not enabled, sensitive data at rest will remain unprotected in EC2. However, Prowler will only generate a finding if EBS volumes exist where default encryption could be enforced. @@ -56,7 +56,7 @@ Prowler scans only attached security groups to report vulnerabilities in activel - `ec2_networkacl_allow_ingress_X_port` -#### AWS Glue +#### AWS Glue AWS Glue best practices recommend encrypting metadata and connection passwords in Data Catalogs. @@ -71,7 +71,7 @@ Amazon Inspector is a vulnerability discovery service that automates continuous - `inspector2_is_enabled` -#### Amazon Macie +#### Amazon Macie Amazon Macie leverages machine learning to automatically discover, classify, and protect sensitive data in S3 buckets. Prowler only generates findings if Macie is disabled and there are S3 buckets in the AWS account. @@ -83,7 +83,7 @@ A network firewall is essential for monitoring and controlling traffic within a - `networkfirewall_in_all_vpc` -#### Amazon S3 +#### Amazon S3 To prevent unintended data exposure: @@ -91,7 +91,7 @@ Public Access Block should be enabled at the account level. Prowler only checks - `s3_account_level_public_access_blocks` -#### Virtual Private Cloud (VPC) +#### Virtual Private Cloud (VPC) VPC settings directly impact network security and availability. diff --git a/docs/user-guide/providers/aws/getting-started-aws.mdx b/docs/user-guide/providers/aws/getting-started-aws.mdx index e6cc636a42..f502981b08 100644 --- a/docs/user-guide/providers/aws/getting-started-aws.mdx +++ b/docs/user-guide/providers/aws/getting-started-aws.mdx @@ -84,6 +84,17 @@ For detailed instructions on how to create the role, see [Authentication > Assum ![Next button in Prowler Cloud](/images/providers/next-button-prowler-cloud.png) ![Launch Scan](/images/providers/launch-scan-button-prowler-cloud.png) + +Check if your AWS Security Token Service (STS) has the EU (Ireland) endpoint active. If not, we will not be able to connect to your AWS account. + +If that is the case your STS configuration may look like this: + +AWS Role + +To solve this issue, please activate the EU (Ireland) STS endpoint. + + + --- #### Credentials (Static Access Keys) diff --git a/docs/user-guide/providers/azure/getting-started-azure.mdx b/docs/user-guide/providers/azure/getting-started-azure.mdx index f9f37b9f9b..a5299c614b 100644 --- a/docs/user-guide/providers/azure/getting-started-azure.mdx +++ b/docs/user-guide/providers/azure/getting-started-azure.mdx @@ -53,7 +53,8 @@ For detailed instructions on how to create the Service Principal and configure p ### Step 3: Add Credentials to Prowler App -Having completed the [Service Principal setup from the Authentication guide](/user-guide/providers/azure/authentication#service-principal-application-authentication-recommended): +For Azure, Prowler App uses a service principal application to authenticate. For more information about the process of creating and adding permissions to a service principal refer to this [section](/user-guide/providers/azure/authentication). When you finish creating and adding the [Entra](/user-guide/providers/azure/create-prowler-service-principal#assigning-proper-permissions) and [Subscription](/user-guide/providers/azure/subscriptions) scope permissions to the service principal, enter the `Tenant ID`, `Client ID` and `Client Secret` of the service principal application. + 1. Go to your App Registration overview and copy the `Client ID` and `Tenant ID` diff --git a/docs/user-guide/providers/gcp/authentication.mdx b/docs/user-guide/providers/gcp/authentication.mdx index 7eea8ac5dd..9447d73a20 100644 --- a/docs/user-guide/providers/gcp/authentication.mdx +++ b/docs/user-guide/providers/gcp/authentication.mdx @@ -14,7 +14,10 @@ Prowler for Google Cloud supports multiple authentication methods. To use a spec Prowler for Google Cloud requires the following permissions: ### IAM Roles -- **Reader (`roles/reader`)** – Must be granted at the **project, folder, or organization** level to allow scanning of target projects. +- **Viewer (`roles/viewer`)** – Must be granted at the **project, folder, or organization** level to allow scanning of target projects. +- **Service Usage Consumer (`roles/serviceusage.serviceUsageConsumer`)** IAM Role – Required for resource scanning. +- **Custom `ProwlerRole`** – Include granular permissions that are not included in the Viewer role: + - `storage.buckets.getIamPolicy` ### Project-Level Settings @@ -106,18 +109,46 @@ prowler gcp --project-ids This method uses a service account with a downloaded key file for authentication. -### Create Service Account and Key +### Step 1: Create ProwlerRole -1. Go to the [Service Accounts page](https://console.cloud.google.com/iam-admin/serviceaccounts) in the GCP Console -2. Click "Create Service Account" -3. Fill in the service account details and click "Create and Continue" -4. Grant the service account the "Reader" role -5. Click "Done" -6. Find your service account in the list and click on it -7. Go to the "Keys" tab -8. Click "Add Key" > "Create new key" -9. Select "JSON" and click "Create" -10. Save the downloaded key file securely +To keep permissions focused: +1. Create a custom role named **ProwlerRole** that explicitly includes the permissions your compliance team approves. Click **Create role**, set the title to *ProwlerRole*, keep the ID readable (for example, `prowler_role`) +2. Add the required permission `storage.buckets.getIamPolicy` (the permission highlighted in the screenshots). To make it easier, filter the permissions by `Storage Admin` role. + +![Create a custom Prowler role](/user-guide/providers/gcp/img/roles-section.png) + +![Sample permissions for a custom Prowler role](/user-guide/providers/gcp/img/prowler-role.png) + +### Step 2: Create the Service Account + +1. Navigate to **IAM & Admin > Service Accounts** and make sure the correct project is selected. + + ![Service accounts landing page](/user-guide/providers/gcp/img/service-account-page.png) + +2. Select **Create service account**, provide a name, ID, and a short description that states the purpose (for example, “Service account to execute Prowler”), then click **Create and continue**. + + ![Create service account wizard](/user-guide/providers/gcp/img/create-service-account.png) + +3. Assign the roles you prepared earlier: + - **ProwlerRole** for `cloudstorage` service checks. + - **Viewer** for broad read-only visibility. + - **Service Usage Consumer** so Prowler can inspect API states. + + ![Assign roles to the service account](/user-guide/providers/gcp/img/service-account-permissions.png) + +4. Continue through the wizard and finish. No principals need to be granted access in step 3 unless you want other identities to impersonate this account. + +### Step 3: Generate a JSON Key + +1. Open the newly created service account, move to the **Keys** tab, and choose **Add key > Create new key**. + + ![Add a new key to the service account](/user-guide/providers/gcp/img/create-new-key.png) + +2. Select **JSON** as the key type and click **Create**. The browser downloads the file exactly once. + + ![Select JSON as the key type](/user-guide/providers/gcp/img/json-key.png) + +3. Once created, make sure to store the Key securely. ### Using with Prowler CLI diff --git a/docs/user-guide/providers/gcp/getting-started-gcp.mdx b/docs/user-guide/providers/gcp/getting-started-gcp.mdx index 218272793a..c2f8a9363c 100644 --- a/docs/user-guide/providers/gcp/getting-started-gcp.mdx +++ b/docs/user-guide/providers/gcp/getting-started-gcp.mdx @@ -32,35 +32,45 @@ title: 'Getting Started With GCP on Prowler' ### Step 3: Set Up GCP Authentication -Choose the preferred authentication mode before proceeding: +For Google Cloud, first enter your `GCP Project ID` and then select the authentication method you want to use: -**User Credentials (Application Default Credentials)** +- **Service Account Authentication** (**Recommended**) + * Authenticates as a service identity + * Stable and auditable + * Recommended for production +- **Application Default Credentials** + * Quick scan as current user + * Uses Google Cloud CLI authentication + * Credentials may time out -* Quick scan as current user -* Uses Google Cloud CLI authentication -* Credentials may time out +**Service Account Authentication** is the recommended authentication method for automated systems and machine-to-machine interactions, like Prowler. For detailed information about this, refer to the [Google Cloud documentation](https://cloud.google.com/iam/docs/service-account-overview). -**Service Account Key File** +GCP Authentication Methods -* Authenticates as a service identity -* Stable and auditable -* Recommended for production + + + First of all, in the same project that you selected in the previous step, you need to create a service account and then generate a key in JSON format for it. For more information about this, you can follow the next Google Cloud documentation tutorials: -For detailed instructions on how to set up authentication, see [Authentication](/user-guide/providers/gcp/authentication). + - [Create a service account](https://cloud.google.com/iam/docs/creating-managing-service-accounts) + - [Generate a key for a service account](https://cloud.google.com/iam/docs/creating-managing-service-account-keys) -6. Once credentials are configured, return to Prowler App and enter the required values: + GCP Service Account Credentials + + + 1. Run the following command in your terminal to authenticate with GCP: - For "Service Account Key": + ```bash + gcloud auth application-default login + ``` - - `Service Account Key JSON` + 2. Once authenticated, get the `Client ID`, `Client Secret` and `Refresh Token` from `~/.config/gcloud/application_default_credentials`. - For "Application Default Credentials": + 3. Paste the `Client ID`, `Client Secret` and `Refresh Token` into Prowler App. - - `client_id` - - `client_secret` - - `refresh_token` + GCP Credentials + + - ![Enter the Credentials](/images/providers/enter-credentials-prowler-cloud.png) 7. Click "Next", then "Launch Scan" diff --git a/docs/user-guide/providers/gcp/img/create-new-key.png b/docs/user-guide/providers/gcp/img/create-new-key.png new file mode 100644 index 0000000000..db925004d5 Binary files /dev/null and b/docs/user-guide/providers/gcp/img/create-new-key.png differ diff --git a/docs/user-guide/providers/gcp/img/create-service-account.png b/docs/user-guide/providers/gcp/img/create-service-account.png new file mode 100644 index 0000000000..5c6bc516ca Binary files /dev/null and b/docs/user-guide/providers/gcp/img/create-service-account.png differ diff --git a/docs/user-guide/providers/gcp/img/json-key.png b/docs/user-guide/providers/gcp/img/json-key.png new file mode 100644 index 0000000000..1466000b7e Binary files /dev/null and b/docs/user-guide/providers/gcp/img/json-key.png differ diff --git a/docs/user-guide/providers/gcp/img/prowler-role.png b/docs/user-guide/providers/gcp/img/prowler-role.png new file mode 100644 index 0000000000..99da2f6edb Binary files /dev/null and b/docs/user-guide/providers/gcp/img/prowler-role.png differ diff --git a/docs/user-guide/providers/gcp/img/roles-section.png b/docs/user-guide/providers/gcp/img/roles-section.png new file mode 100644 index 0000000000..dcf068d967 Binary files /dev/null and b/docs/user-guide/providers/gcp/img/roles-section.png differ diff --git a/docs/user-guide/providers/gcp/img/service-account-page.png b/docs/user-guide/providers/gcp/img/service-account-page.png new file mode 100644 index 0000000000..588bb54816 Binary files /dev/null and b/docs/user-guide/providers/gcp/img/service-account-page.png differ diff --git a/docs/user-guide/providers/gcp/img/service-account-permissions.png b/docs/user-guide/providers/gcp/img/service-account-permissions.png new file mode 100644 index 0000000000..a4fce5e408 Binary files /dev/null and b/docs/user-guide/providers/gcp/img/service-account-permissions.png differ diff --git a/docs/user-guide/providers/kubernetes/getting-started-k8s.mdx b/docs/user-guide/providers/kubernetes/getting-started-k8s.mdx new file mode 100644 index 0000000000..ae70c06263 --- /dev/null +++ b/docs/user-guide/providers/kubernetes/getting-started-k8s.mdx @@ -0,0 +1,131 @@ +--- +title: 'Getting Started with Kubernetes' +--- + +## Prowler App + +### Step 1: Access Prowler Cloud/App + +1. Navigate to [Prowler Cloud](https://cloud.prowler.com/) or launch [Prowler App](/user-guide/tutorials/prowler-app) +2. Go to "Configuration" > "Cloud Providers" + + ![Cloud Providers Page](/images/prowler-app/cloud-providers-page.png) + +3. Click "Add Cloud Provider" + + ![Add a Cloud Provider](/images/prowler-app/add-cloud-provider.png) + +4. Select "Kubernetes" + +5. Enter your Kubernetes Cluster context from your kubeconfig file and optionally provide a friendly alias + +### Step 2: Configure Kubernetes Authentication + +For Kubernetes, Prowler App uses a `kubeconfig` file to authenticate. Paste the contents of your `kubeconfig` file into the `Kubeconfig content` field. + +By default, the `kubeconfig` file is located at `~/.kube/config`. + +![Kubernetes Credentials](/images/kubernetes-credentials.png) + +### Step 3: Additional Setup for EKS, GKE, AKS, or External Clusters + +If you are adding an **EKS**, **GKE**, **AKS** or external cluster, follow these additional steps to ensure proper authentication: + +**Make sure your cluster allows traffic from the Prowler Cloud IP address `52.48.254.174/32`** + +1. Apply the necessary Kubernetes resources to your EKS, GKE, AKS or external cluster (you can find the files in the [`kubernetes` directory of the Prowler repository](https://github.com/prowler-cloud/prowler/tree/master/kubernetes)): + + ```console + kubectl apply -f kubernetes/prowler-sa.yaml + kubectl apply -f kubernetes/prowler-role.yaml + kubectl apply -f kubernetes/prowler-rolebinding.yaml + ``` + +2. Generate a long-lived token for authentication: + + ```console + kubectl create token prowler-sa -n prowler-ns --duration=0 + ``` + + - **Security Note:** The `--duration=0` option generates a non-expiring token, which may pose a security risk if not managed properly. Users should decide on an appropriate expiration time based on their security policies. If a limited-time token is preferred, set `--duration= ## Mutelist Ready To Use Examples -Below are examples for different cloud providers supported by Prowler App. Check how the mutelist works [here](https://docs.prowler.com/projects/prowler-open-source/en/latest/tutorials/mutelist/#how-the-mutelist-works). +Below are examples for different cloud providers supported by Prowler App. Check how the mutelist works [here](/user-guide/cli/tutorials/mutelist#how-the-mutelist-works). ### AWS Provider diff --git a/docs/user-guide/tutorials/prowler-app-sso.mdx b/docs/user-guide/tutorials/prowler-app-sso.mdx index f56336f415..fa062100d1 100644 --- a/docs/user-guide/tutorials/prowler-app-sso.mdx +++ b/docs/user-guide/tutorials/prowler-app-sso.mdx @@ -10,9 +10,9 @@ This guide provides comprehensive instructions to configure SAML-based Single Si This document is divided into two main sections: -- **User Guide**: For organization administrators to configure SAML SSO through Prowler App. +- **[User Guide](#user-guide-configuration)**: For organization administrators to configure SAML SSO through Prowler App. -- **Developer and Administrator Guide**: For developers and system administrators running self-hosted Prowler App instances, providing technical details on environment configuration, API usage, and testing. +- **[Developer and Administrator Guide](#developer-and-administrator-guide)**: For developers and system administrators running self-hosted Prowler App instances, providing technical details on environment configuration, API usage, and testing. --- @@ -53,58 +53,65 @@ On the profile page, find the "SAML SSO Integration" card and click "Enable" to ![Enable SAML Integration](/images/prowler-app/saml/saml-step-2.png) - -**Choose Your Method** +Next section will explain how to fill the IdP configuration based on your Identity Provider. -**Use Step 3A (Generic Method)** for any SAML 2.0 compliant Identity Provider or when you need custom configuration. +#### Step 3: Configure the Identity Provider (IdP) +Choose a Method: -**Use Step 3B (Okta App Catalog)** if you're using Okta and want a simplified setup process with pre-configured settings. +- Use [**Generic Method**](#generic-method) for any SAML 2.0 compliant Identity Provider or when you need custom configuration. +- Use [**Okta App Catalog**](#okta-app-catalog) if you're using Okta and want a simplified setup process with pre-configured settings. - -#### Step 3A: Configure the Identity Provider (IdP) - Generic + + + Prowler App displays the SAML configuration information needed to configure the IdP. Use this information to create a new SAML application in the IdP. -Prowler App displays the SAML configuration information needed to configure the IdP. Use this information to create a new SAML application in the IdP. + 1. **Assertion Consumer Service (ACS) URL**: The endpoint in Prowler that will receive the SAML assertion from the IdP. + 2. **Audience URI (Entity ID)**: A unique identifier for the Prowler application (Service Provider). -1. **Assertion Consumer Service (ACS) URL**: The endpoint in Prowler that will receive the SAML assertion from the IdP. -2. **Audience URI (Entity ID)**: A unique identifier for the Prowler application (Service Provider). + To configure the IdP, copy the **ACS URL** and **Audience URI** from Prowler App and use them to set up a new SAML application. -To configure the IdP, copy the **ACS URL** and **Audience URI** from Prowler App and use them to set up a new SAML application. + ![IdP configuration](/images/prowler-app/saml/idp_config.png) -![IdP configuration](/images/prowler-app/saml/idp_config.png) + + **IdP Configuration** - -**IdP Configuration** + The exact steps for configuring an IdP vary depending on the provider (Okta, Azure AD, etc.). Please refer to the IdP's documentation for instructions on creating a SAML application. For SSO integration with Azure AD / Entra ID, see our [Entra ID configuration instructions](/user-guide/tutorials/prowler-app-sso-entra). -The exact steps for configuring an IdP vary depending on the provider (Okta, Azure AD, etc.). Please refer to the IdP's documentation for instructions on creating a SAML application. For SSO integration with Azure AD / Entra ID, see our [Entra ID configuration instructions](/user-guide/tutorials/prowler-app-sso-entra). + - -#### Step 3B: Configure Prowler from App Catalog - Okta + + + Instead of creating a custom SAML integration, Okta administrators can configure Prowler Cloud directly from Okta's application catalog. -Instead of creating a custom SAML integration, Okta administrators can configure Prowler Cloud directly from Okta's application catalog: + You can find a walkthrough video [here](https://youtu.be/NjSp5owvCdY). -1. **Access App Catalog**: Navigate to the IdP's application catalog (e.g., [Browse App Catalog](https://www.okta.com/integrations/) in Okta). + 1. **Access App Catalog**: Navigate to the IdP's application catalog (e.g., [Browse App Catalog](https://www.okta.com/integrations/) in Okta). - ![Browse App Catalog](/images/prowler-app/saml/app-catalog-browse.png) + ![Browse App Catalog](/images/prowler-app/saml/app-catalog-browse.png) -2. **Search for Prowler Cloud**: Use the search functionality to find "Prowler Cloud" in the app catalog. The official Prowler Cloud application will appear in the search results. + 2. **Search for Prowler Cloud**: Use the search functionality to find "Prowler Cloud" in the app catalog. The official Prowler Cloud application will appear in the search results. - ![Search for Prowler](/images/prowler-app/saml/app-catalog-browse-prowler.png) + ![Search for Prowler](/images/prowler-app/saml/app-catalog-browse-prowler.png) -3. **Select Prowler Cloud Application**: Click on the Prowler Cloud application from the search results to view its details page. + 3. **Select Prowler Cloud Application**: Click the Prowler Cloud application from the search results to view its details page. - ![Prowler Application Details](/images/prowler-app/saml/app-catalog-browse-prowler-add.png) + ![Prowler Application Details](/images/prowler-app/saml/app-catalog-browse-prowler-add.png) -4. **Add Integration**: Click the "Add Integration" button to begin adding Prowler Cloud to the organization's applications. + 4. **Add Integration**: Click the "Add Integration" button to begin adding Prowler Cloud to the organization's applications. -5. **Configure General Settings**: In the "Add Prowler Cloud" configuration screen, the integration automatically configures the necessary settings. + 5. **Configure General Settings**: In the "Add Prowler Cloud" configuration screen, the integration automatically configures the necessary settings. - ![Add Prowler Configuration](/images/prowler-app/saml/app-catalog-browse-prowler-configure.png) + ![Add Prowler Configuration](/images/prowler-app/saml/app-catalog-browse-prowler-configure.png) -6. **Assign Users**: Navigate to the **Assignments** tab and assign the appropriate users or groups to the Prowler application by clicking "Assign" and selecting "Assign to People" or "Assign to Groups". + 6. **Assign Users**: Navigate to the "Assignments" tab and assign the appropriate users or groups to the Prowler application by clicking "Assign" and selecting "Assign to People" or "Assign to Groups". -With this step, the Okta app catalog configuration is complete. Users can now access Prowler Cloud using either [IdP-initiated](#idp-initiated-sso) or [SP-initiated SSO](#sp-initiated-sso) flows. + With this step, the Okta app catalog configuration is complete. Users can now access Prowler Cloud using either [IdP-initiated](#idp-initiated-sso) or [SP-initiated SSO](#sp-initiated-sso) flows. -**If you used Step 3B (Okta App Catalog)**, jump to [Step 6: Save and Verify Configuration](#step-6-save-and-verify-configuration). + 7. **Download Metadata XML**: Inside the "Sign On" section, go to the "Metadata URL" and download the metadata XML file. + + Jump to [Step 5: Upload IdP Metadata to Prowler](#step-5:-upload-idp-metadata-to-prowler). + + #### Step 4: Configure Attribute Mapping in the IdP @@ -120,7 +127,7 @@ For Prowler App to correctly identify and provision users, configure the IdP to **IdP Attribute Mapping** -Note that the attribute name is just an example and may be different depending on the IdP. For instance, if the IdP provides a 'division' attribute, it can be mapped to 'userType'. +Note that the attribute name is just an example and may be different depending on the IdP. For instance, if the IdP provides a `division` attribute, it can be mapped to `userType`. ![IdP configuration](/images/prowler-app/saml/saml_attribute_statements.png) @@ -156,7 +163,8 @@ Click the "Save" button to complete the setup. The "SAML Integration" card will The exact steps for configuring an IdP vary depending on the provider (Okta, Azure AD, etc.). Please refer to the IdP's documentation for instructions on creating a SAML application. -##### Remove SAML Configuration + +### Remove SAML Configuration SAML SSO can be disabled by removing the existing configuration from the integration panel. ![Remove SAML configuration](/images/prowler-app/saml/saml-step-remove.png) diff --git a/docs/user-guide/tutorials/prowler-app.mdx b/docs/user-guide/tutorials/prowler-app.mdx index dd2074c3b9..52210b01bf 100644 --- a/docs/user-guide/tutorials/prowler-app.mdx +++ b/docs/user-guide/tutorials/prowler-app.mdx @@ -77,208 +77,35 @@ Steps to add a provider: ## **Step 4: Configure the Provider** -Select the cloud provider you want to scan. +Select the cloud provider to scan and configure authentication credentials. Each provider has specific requirements and authentication methods. Select a Provider -Once chosen, enter the Provider UID for authentication: - -- **AWS**: Enter your AWS Account ID. -- **GCP**: Enter your GCP Project ID. -- **Azure**: Enter your Azure Subscription ID. -- **Kubernetes**: Enter your Kubernetes Cluster context of your kubeconfig file. -- **M365**: Enter your M365 Domain ID. - -Optionally, provide a **Provider Alias** for easier identification. Follow the instructions provided to add your credentials: - -### **Step 4.1: AWS Credentials** - -For AWS, enter your `AWS Account ID` and choose one of the following methods to connect: - -#### **Step 4.1.1: IAM Access Keys** - -1. Select `Connect via Credentials`. - - AWS Credentials - -2. Enter your `Access Key ID`, `Secret Access Key` and optionally a `Session Token`: - - AWS Credentials - -#### **Step 4.1.2: IAM Role** - -1. Select `Connect assuming IAM Role`. - - AWS Role - -2. Enter the `Role ARN` and any optional field like the AWS Access Keys to assume the role, the `External ID`, the `Role Session Name` or the `Session Duration`: - - AWS Role - - -Check if your AWS Security Token Service (STS) has the EU (Ireland) endpoint active. If not, we will not be able to connect to your AWS account. - -If that is the case your STS configuration may look like this: - -AWS Role - -To solve this issue, please activate the EU (Ireland) STS endpoint. - - -### **Step 4.2: Azure Credentials**: - -For Azure, Prowler App uses a service principal application to authenticate. For more information about the process of creating and adding permissions to a service principal refer to this [section](/user-guide/providers/azure/authentication). When you finish creating and adding the [Entra](/user-guide/providers/azure/create-prowler-service-principal#assigning-proper-permissions) and [Subscription](/user-guide/providers/azure/subscriptions) scope permissions to the service principal, enter the `Tenant ID`, `Client ID` and `Client Secret` of the service principal application. - -Azure Credentials - ---- -### **Step 4.3: GCP Credentials** - -For Google Cloud, first enter your `GCP Project ID` and then select the authentication method you want to use: - -- **Service Account Authentication** (**Recommended**) -- **Application Default Credentials** - -**Service Account Authentication** is the recommended authentication method for automated systems and machine-to-machine interactions, like Prowler. For detailed information about this, refer to the [Google Cloud documentation](https://cloud.google.com/iam/docs/service-account-overview). - -GCP Authentication Methods - -#### **Step 4.3.1: Service Account Authentication** - -First of all, in the same project that you selected in the previous step, you need to create a service account and then generate a key in JSON format for it. For more information about this, you can follow the next Google Cloud documentation tutorials: - -- [Create a service account](https://cloud.google.com/iam/docs/creating-managing-service-accounts) -- [Generate a key for a service account](https://cloud.google.com/iam/docs/creating-managing-service-account-keys) - -GCP Service Account Credentials - -#### **Step 4.3.2: Application Default Credentials** - -1. Run the following command in your terminal to authenticate with GCP: - - ```bash - gcloud auth application-default login - ``` - -2. Once authenticated, get the `Client ID`, `Client Secret` and `Refresh Token` from `~/.config/gcloud/application_default_credentials`. - -3. Paste the `Client ID`, `Client Secret` and `Refresh Token` into Prowler App. - -GCP Credentials - -### **Step 4.4: Kubernetes Credentials**: - -For Kubernetes, Prowler App uses a `kubeconfig` file to authenticate, paste the contents of your `kubeconfig` file into the `Kubeconfig content` field. - -By default, the `kubeconfig` file is located at `~/.kube/config`. - -Kubernetes Credentials - -If you are adding an **EKS**, **GKE**, **AKS** or external cluster, follow these additional steps to ensure proper authentication: - -**Make sure your cluster allow traffic from the Prowler Cloud IP address `52.48.254.174/32`** - -1. Apply the necessary Kubernetes resources to your EKS, GKE, AKS or external cluster (you can find the files in the [`kubernetes` directory of the Prowler repository](https://github.com/prowler-cloud/prowler/tree/master/kubernetes)): - - ```console - kubectl apply -f kubernetes/prowler-sa.yaml - kubectl apply -f kubernetes/prowler-role.yaml - kubectl apply -f kubernetes/prowler-rolebinding.yaml - ``` - -2. Generate a long-lived token for authentication: - - ```console - kubectl create token prowler-sa -n prowler-ns --duration=0 - ``` - - - **Security Note:** The `--duration=0` option generates a non-expiring token, which may pose a security risk if not managed properly. Users should decide on an appropriate expiration time based on their security policies. If a limited-time token is preferred, set `--duration=