mirror of
https://github.com/prowler-cloud/prowler.git
synced 2026-05-18 10:13:14 +00:00
Compare commits
28 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 3066d82863 | |||
| 969ca8863a | |||
| 03c6f98db4 | |||
| 8ebefb8aa1 | |||
| c3694fdc5b | |||
| df10bc0c4c | |||
| e694b0f634 | |||
| 81e3f87003 | |||
| 7ffe2aeec9 | |||
| 672aa6eb2f | |||
| 2e999f55f9 | |||
| 18998b8867 | |||
| ff4a186df6 | |||
| b8dab5e0ed | |||
| 0b3142f7a8 | |||
| f5dc0c9ee0 | |||
| a230809095 | |||
| e6d1b5639b | |||
| b1856e42f0 | |||
| ba8dbb0d28 | |||
| b436cc1cac | |||
| 51baa88644 | |||
| 5098b12e97 | |||
| 3d1e7015a6 | |||
| 0b7f02f7e4 | |||
| c0396e97bf | |||
| 8d4fa46038 | |||
| 4b160257b9 |
@@ -8,7 +8,7 @@ body:
|
||||
attributes:
|
||||
label: Feature search
|
||||
options:
|
||||
- label: I have searched the existing issues and this feature has not been requested yet
|
||||
- label: I have searched the existing issues and this feature has not been requested yet or is already in our [Public Roadmap](https://roadmap.prowler.com/roadmap)
|
||||
required: true
|
||||
- type: dropdown
|
||||
id: component
|
||||
|
||||
@@ -1,4 +1,18 @@
|
||||
name: "SDK - CodeQL Config"
|
||||
name: 'SDK: CodeQL Config'
|
||||
paths:
|
||||
- 'prowler/'
|
||||
|
||||
paths-ignore:
|
||||
- "api/"
|
||||
- "ui/"
|
||||
- 'api/'
|
||||
- 'ui/'
|
||||
- 'dashboard/'
|
||||
- 'mcp_server/'
|
||||
- 'tests/**'
|
||||
- 'util/**'
|
||||
- 'contrib/**'
|
||||
- 'examples/**'
|
||||
- 'prowler/**/__pycache__/**'
|
||||
- 'prowler/**/*.md'
|
||||
|
||||
queries:
|
||||
- uses: security-and-quality
|
||||
|
||||
@@ -1,3 +1,17 @@
|
||||
name: "UI - CodeQL Config"
|
||||
name: 'UI: CodeQL Config'
|
||||
paths:
|
||||
- "ui/"
|
||||
- 'ui/'
|
||||
|
||||
paths-ignore:
|
||||
- 'ui/node_modules/**'
|
||||
- 'ui/.next/**'
|
||||
- 'ui/out/**'
|
||||
- 'ui/tests/**'
|
||||
- 'ui/**/*.test.ts'
|
||||
- 'ui/**/*.test.tsx'
|
||||
- 'ui/**/*.spec.ts'
|
||||
- 'ui/**/*.spec.tsx'
|
||||
- 'ui/**/*.md'
|
||||
|
||||
queries:
|
||||
- uses: security-and-quality
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
name: Label Community Contributors PRs
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened]
|
||||
|
||||
jobs:
|
||||
add-community-label:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
issues: write
|
||||
pull-requests: write
|
||||
|
||||
steps:
|
||||
- name: Label community contributors
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
# Fetch fresh PR data to get current author_association
|
||||
ASSOCIATION=$(gh api /repos/${{ github.repository }}/pulls/${{ github.event.number }} --jq '.author_association')
|
||||
AUTHOR=$(gh api /repos/${{ github.repository }}/pulls/${{ github.event.number }} --jq '.user.login')
|
||||
|
||||
echo "Author: $AUTHOR, Association: $ASSOCIATION"
|
||||
|
||||
# Members have associations like: OWNER, MEMBER, COLLABORATOR
|
||||
# Non-members have: CONTRIBUTOR, FIRST_TIME_CONTRIBUTOR, FIRST_TIMER, NONE
|
||||
if [[ "$ASSOCIATION" != "OWNER" && "$ASSOCIATION" != "MEMBER" && "$ASSOCIATION" != "COLLABORATOR" ]]; then
|
||||
gh api /repos/${{ github.repository }}/issues/${{ github.event.number }}/labels \
|
||||
-X POST \
|
||||
-f labels[]='community'
|
||||
echo "Added 'community' label for $ASSOCIATION contributor"
|
||||
else
|
||||
echo "Skipped labeling for $ASSOCIATION"
|
||||
fi
|
||||
@@ -0,0 +1,80 @@
|
||||
name: 'MCP: Pull Request'
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- 'master'
|
||||
- 'v5.*'
|
||||
paths:
|
||||
- '.github/workflows/mcp-pull-request.yml'
|
||||
- 'mcp_server/**'
|
||||
- '!mcp_server/README.md'
|
||||
- '!mcp_server/CHANGELOG.md'
|
||||
pull_request:
|
||||
branches:
|
||||
- 'master'
|
||||
- 'v5.*'
|
||||
paths:
|
||||
- '.github/workflows/mcp-pull-request.yml'
|
||||
- 'mcp_server/**'
|
||||
- '!mcp_server/README.md'
|
||||
- '!mcp_server/CHANGELOG.md'
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
MCP_WORKING_DIR: ./mcp_server
|
||||
IMAGE_NAME: prowler-mcp
|
||||
|
||||
jobs:
|
||||
dockerfile-lint:
|
||||
if: github.repository == 'prowler-cloud/prowler'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
|
||||
|
||||
- name: Lint Dockerfile with Hadolint
|
||||
uses: hadolint/hadolint-action@2332a7b74a6de0dda2e2221d575162eba76ba5e5 # v3.3.0
|
||||
with:
|
||||
dockerfile: mcp_server/Dockerfile
|
||||
|
||||
container-build-and-scan:
|
||||
if: github.repository == 'prowler-cloud/prowler'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
permissions:
|
||||
contents: read
|
||||
security-events: write
|
||||
pull-requests: write
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@e468171a9de216ec08956ac3ada2f0791b6bd435 # v3.11.1
|
||||
|
||||
- name: Build MCP container
|
||||
uses: docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0
|
||||
with:
|
||||
context: ${{ env.MCP_WORKING_DIR }}
|
||||
push: false
|
||||
load: true
|
||||
tags: ${{ env.IMAGE_NAME }}:${{ github.sha }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
|
||||
- name: Scan MCP container with Trivy
|
||||
uses: ./.github/actions/trivy-scan
|
||||
with:
|
||||
image-name: ${{ env.IMAGE_NAME }}
|
||||
image-tag: ${{ github.sha }}
|
||||
fail-on-critical: 'false'
|
||||
severity: 'CRITICAL'
|
||||
@@ -150,8 +150,8 @@ jobs:
|
||||
# Remove --- separators
|
||||
sed -i '/^---$/d' "$output_file"
|
||||
|
||||
# Remove trailing empty lines
|
||||
sed -i '/^$/d' "$output_file"
|
||||
# Remove only trailing empty lines (not all empty lines)
|
||||
sed -i -e :a -e '/^\s*$/d;N;ba' "$output_file"
|
||||
}
|
||||
|
||||
# Calculate expected versions for this release
|
||||
@@ -247,6 +247,11 @@ jobs:
|
||||
echo "" >> combined_changelog.md
|
||||
fi
|
||||
|
||||
# Add fallback message if no changelogs were added
|
||||
if [ ! -s combined_changelog.md ]; then
|
||||
echo "No component changes detected for this release." >> combined_changelog.md
|
||||
fi
|
||||
|
||||
echo "Combined changelog preview:"
|
||||
cat combined_changelog.md
|
||||
|
||||
@@ -336,13 +341,6 @@ jobs:
|
||||
CURRENT_PROWLER_REF=$(grep 'prowler @ git+https://github.com/prowler-cloud/prowler.git@' api/pyproject.toml | sed -E 's/.*@([^"]+)".*/\1/' | tr -d '[:space:]')
|
||||
BRANCH_NAME_TRIMMED=$(echo "$BRANCH_NAME" | tr -d '[:space:]')
|
||||
|
||||
# Create a temporary branch for the PR from the minor version branch
|
||||
TEMP_BRANCH="update-api-dependency-$BRANCH_NAME_TRIMMED-$(date +%s)"
|
||||
echo "TEMP_BRANCH=$TEMP_BRANCH" >> $GITHUB_ENV
|
||||
|
||||
# Create temp branch from the current minor version branch
|
||||
git checkout -b "$TEMP_BRANCH"
|
||||
|
||||
# Minor release: update the dependency to use the release branch
|
||||
echo "Updating prowler dependency from '$CURRENT_PROWLER_REF' to '$BRANCH_NAME_TRIMMED'"
|
||||
sed -i "s|prowler @ git+https://github.com/prowler-cloud/prowler.git@[^\"]*\"|prowler @ git+https://github.com/prowler-cloud/prowler.git@$BRANCH_NAME_TRIMMED\"|" api/pyproject.toml
|
||||
@@ -360,11 +358,6 @@ jobs:
|
||||
poetry lock
|
||||
cd ..
|
||||
|
||||
# Commit and push the temporary branch
|
||||
git add api/pyproject.toml api/poetry.lock
|
||||
git commit -m "chore(api): update prowler dependency to $BRANCH_NAME_TRIMMED for release $PROWLER_VERSION"
|
||||
git push origin "$TEMP_BRANCH"
|
||||
|
||||
echo "✓ Prepared prowler dependency update to: $UPDATED_PROWLER_REF"
|
||||
|
||||
- name: Create PR for API dependency update
|
||||
@@ -372,8 +365,12 @@ jobs:
|
||||
uses: peter-evans/create-pull-request@271a8d0340265f705b14b6d32b9829c1cb33d45e # v7.0.8
|
||||
with:
|
||||
token: ${{ secrets.PROWLER_BOT_ACCESS_TOKEN }}
|
||||
branch: ${{ env.TEMP_BRANCH }}
|
||||
commit-message: 'chore(api): update prowler dependency to ${{ env.BRANCH_NAME }} for release ${{ env.PROWLER_VERSION }}'
|
||||
branch: update-api-dependency-${{ env.BRANCH_NAME }}-${{ github.run_number }}
|
||||
base: ${{ env.BRANCH_NAME }}
|
||||
add-paths: |
|
||||
api/pyproject.toml
|
||||
api/poetry.lock
|
||||
title: "chore(api): Update prowler dependency to ${{ env.BRANCH_NAME }} for release ${{ env.PROWLER_VERSION }}"
|
||||
body: |
|
||||
### Description
|
||||
@@ -406,5 +403,6 @@ jobs:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Clean up temporary files
|
||||
if: always()
|
||||
run: |
|
||||
rm -f prowler_changelog.md api_changelog.md ui_changelog.md mcp_changelog.md combined_changelog.md
|
||||
|
||||
@@ -1,44 +1,40 @@
|
||||
# For most projects, this workflow file will not need changing; you simply need
|
||||
# to commit it to your repository.
|
||||
#
|
||||
# You may wish to alter this file to override the set of languages analyzed,
|
||||
# or to provide custom queries or build logic.
|
||||
#
|
||||
# ******** NOTE ********
|
||||
# We have attempted to detect the languages in your repository. Please check
|
||||
# the `language` matrix defined below to confirm you have the correct set of
|
||||
# supported CodeQL languages.
|
||||
#
|
||||
name: SDK - CodeQL
|
||||
name: 'SDK: CodeQL'
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- "master"
|
||||
- "v3"
|
||||
- "v4.*"
|
||||
- "v5.*"
|
||||
paths-ignore:
|
||||
- 'ui/**'
|
||||
- 'api/**'
|
||||
- '.github/**'
|
||||
- 'master'
|
||||
- 'v5.*'
|
||||
paths:
|
||||
- 'prowler/**'
|
||||
- 'tests/**'
|
||||
- 'pyproject.toml'
|
||||
- '.github/workflows/sdk-codeql.yml'
|
||||
- '.github/codeql/sdk-codeql-config.yml'
|
||||
- '!prowler/CHANGELOG.md'
|
||||
pull_request:
|
||||
branches:
|
||||
- "master"
|
||||
- "v3"
|
||||
- "v4.*"
|
||||
- "v5.*"
|
||||
paths-ignore:
|
||||
- 'ui/**'
|
||||
- 'api/**'
|
||||
- '.github/**'
|
||||
- 'master'
|
||||
- 'v5.*'
|
||||
paths:
|
||||
- 'prowler/**'
|
||||
- 'tests/**'
|
||||
- 'pyproject.toml'
|
||||
- '.github/workflows/sdk-codeql.yml'
|
||||
- '.github/codeql/sdk-codeql-config.yml'
|
||||
- '!prowler/CHANGELOG.md'
|
||||
schedule:
|
||||
- cron: '00 12 * * *'
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
analyze:
|
||||
name: Analyze
|
||||
name: CodeQL Security Analysis
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
permissions:
|
||||
actions: read
|
||||
contents: read
|
||||
@@ -47,21 +43,20 @@ jobs:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
language: [ 'python' ]
|
||||
# Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support
|
||||
language:
|
||||
- 'python'
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
|
||||
|
||||
# Initializes the CodeQL tools for scanning.
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@3599b3baa15b485a2e49ef411a7a4bb2452e7f93 # v3.30.5
|
||||
with:
|
||||
languages: ${{ matrix.language }}
|
||||
config-file: ./.github/codeql/sdk-codeql-config.yml
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@3599b3baa15b485a2e49ef411a7a4bb2452e7f93 # v3.30.5
|
||||
with:
|
||||
languages: ${{ matrix.language }}
|
||||
config-file: ./.github/codeql/sdk-codeql-config.yml
|
||||
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@3599b3baa15b485a2e49ef411a7a4bb2452e7f93 # v3.30.5
|
||||
with:
|
||||
category: "/language:${{matrix.language}}"
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@3599b3baa15b485a2e49ef411a7a4bb2452e7f93 # v3.30.5
|
||||
with:
|
||||
category: '/language:${{ matrix.language }}'
|
||||
|
||||
@@ -1,36 +1,36 @@
|
||||
# For most projects, this workflow file will not need changing; you simply need
|
||||
# to commit it to your repository.
|
||||
#
|
||||
# You may wish to alter this file to override the set of languages analyzed,
|
||||
# or to provide custom queries or build logic.
|
||||
#
|
||||
# ******** NOTE ********
|
||||
# We have attempted to detect the languages in your repository. Please check
|
||||
# the `language` matrix defined below to confirm you have the correct set of
|
||||
# supported CodeQL languages.
|
||||
#
|
||||
name: UI - CodeQL
|
||||
name: 'UI: CodeQL'
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- "master"
|
||||
- "v5.*"
|
||||
- 'master'
|
||||
- 'v5.*'
|
||||
paths:
|
||||
- "ui/**"
|
||||
- 'ui/**'
|
||||
- '.github/workflows/ui-codeql.yml'
|
||||
- '.github/codeql/ui-codeql-config.yml'
|
||||
- '!ui/CHANGELOG.md'
|
||||
pull_request:
|
||||
branches:
|
||||
- "master"
|
||||
- "v5.*"
|
||||
- 'master'
|
||||
- 'v5.*'
|
||||
paths:
|
||||
- "ui/**"
|
||||
- 'ui/**'
|
||||
- '.github/workflows/ui-codeql.yml'
|
||||
- '.github/codeql/ui-codeql-config.yml'
|
||||
- '!ui/CHANGELOG.md'
|
||||
schedule:
|
||||
- cron: "00 12 * * *"
|
||||
- cron: '00 12 * * *'
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
analyze:
|
||||
name: Analyze
|
||||
name: CodeQL Security Analysis
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
permissions:
|
||||
actions: read
|
||||
contents: read
|
||||
@@ -39,14 +39,13 @@ jobs:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
language: ["javascript"]
|
||||
# Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support
|
||||
language:
|
||||
- 'javascript-typescript'
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
|
||||
|
||||
# Initializes the CodeQL tools for scanning.
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@3599b3baa15b485a2e49ef411a7a4bb2452e7f93 # v3.30.5
|
||||
with:
|
||||
@@ -56,4 +55,4 @@ jobs:
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@3599b3baa15b485a2e49ef411a7a4bb2452e7f93 # v3.30.5
|
||||
with:
|
||||
category: "/language:${{matrix.language}}"
|
||||
category: '/language:${{ matrix.language }}'
|
||||
|
||||
@@ -18,6 +18,7 @@ jobs:
|
||||
AUTH_TRUST_HOST: true
|
||||
NEXTAUTH_URL: 'http://localhost:3000'
|
||||
NEXT_PUBLIC_API_BASE_URL: 'http://localhost:8080/api/v1'
|
||||
E2E_NEW_PASSWORD: ${{ secrets.E2E_NEW_PASSWORD }}
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
|
||||
|
||||
@@ -39,6 +39,12 @@ secrets-*/
|
||||
# JUnit Reports
|
||||
junit-reports/
|
||||
|
||||
# Test and coverage artifacts
|
||||
*_coverage.xml
|
||||
pytest_*.xml
|
||||
.coverage
|
||||
htmlcov/
|
||||
|
||||
# VSCode files
|
||||
.vscode/
|
||||
|
||||
|
||||
+6
-1
@@ -2,7 +2,12 @@
|
||||
|
||||
All notable changes to the **Prowler API** are documented in this file.
|
||||
|
||||
## [1.14.0] (Prowler UNRELEASED)
|
||||
## [1.15.0] (Prowler UNRELEASED)
|
||||
|
||||
### Added
|
||||
- Support for configuring multiple LLM providers [(#8772)](https://github.com/prowler-cloud/prowler/pull/8772)
|
||||
|
||||
## [1.14.0] (Prowler 5.13.0)
|
||||
|
||||
### Added
|
||||
- Default JWT keys are generated and stored if they are missing from configuration [(#8655)](https://github.com/prowler-cloud/prowler/pull/8655)
|
||||
|
||||
+1
-1
@@ -43,7 +43,7 @@ name = "prowler-api"
|
||||
package-mode = false
|
||||
# Needed for the SDK compatibility
|
||||
requires-python = ">=3.11,<3.13"
|
||||
version = "1.14.0"
|
||||
version = "1.15.0"
|
||||
|
||||
[project.scripts]
|
||||
celery = "src.backend.config.settings.celery"
|
||||
|
||||
@@ -27,6 +27,8 @@ from api.models import (
|
||||
Finding,
|
||||
Integration,
|
||||
Invitation,
|
||||
LighthouseProviderConfiguration,
|
||||
LighthouseProviderModels,
|
||||
Membership,
|
||||
OverviewStatusChoices,
|
||||
PermissionChoices,
|
||||
@@ -928,3 +930,45 @@ class TenantApiKeyFilter(FilterSet):
|
||||
"revoked": ["exact"],
|
||||
"name": ["exact", "icontains"],
|
||||
}
|
||||
|
||||
|
||||
class LighthouseProviderConfigFilter(FilterSet):
|
||||
provider_type = ChoiceFilter(
|
||||
choices=LighthouseProviderConfiguration.LLMProviderChoices.choices
|
||||
)
|
||||
provider_type__in = ChoiceInFilter(
|
||||
choices=LighthouseProviderConfiguration.LLMProviderChoices.choices,
|
||||
field_name="provider_type",
|
||||
lookup_expr="in",
|
||||
)
|
||||
is_active = BooleanFilter()
|
||||
|
||||
class Meta:
|
||||
model = LighthouseProviderConfiguration
|
||||
fields = {
|
||||
"provider_type": ["exact", "in"],
|
||||
"is_active": ["exact"],
|
||||
}
|
||||
|
||||
|
||||
class LighthouseProviderModelsFilter(FilterSet):
|
||||
provider_type = ChoiceFilter(
|
||||
choices=LighthouseProviderConfiguration.LLMProviderChoices.choices,
|
||||
field_name="provider_configuration__provider_type",
|
||||
)
|
||||
provider_type__in = ChoiceInFilter(
|
||||
choices=LighthouseProviderConfiguration.LLMProviderChoices.choices,
|
||||
field_name="provider_configuration__provider_type",
|
||||
lookup_expr="in",
|
||||
)
|
||||
|
||||
# Allow filtering by model id
|
||||
model_id = CharFilter(field_name="model_id", lookup_expr="exact")
|
||||
model_id__icontains = CharFilter(field_name="model_id", lookup_expr="icontains")
|
||||
model_id__in = CharInFilter(field_name="model_id", lookup_expr="in")
|
||||
|
||||
class Meta:
|
||||
model = LighthouseProviderModels
|
||||
fields = {
|
||||
"model_id": ["exact", "icontains", "in"],
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ class Migration(migrations.Migration):
|
||||
(
|
||||
"name",
|
||||
models.CharField(
|
||||
max_length=255,
|
||||
max_length=100,
|
||||
validators=[django.core.validators.MinLengthValidator(3)],
|
||||
),
|
||||
),
|
||||
|
||||
@@ -0,0 +1,266 @@
|
||||
# Generated by Django 5.1.12 on 2025-10-09 07:50
|
||||
|
||||
import json
|
||||
import logging
|
||||
import uuid
|
||||
|
||||
import django.db.models.deletion
|
||||
from config.custom_logging import BackendLogger
|
||||
from cryptography.fernet import Fernet
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
|
||||
import api.rls
|
||||
from api.db_router import MainRouter
|
||||
|
||||
logger = logging.getLogger(BackendLogger.API)
|
||||
|
||||
|
||||
def migrate_lighthouse_configs_forward(apps, schema_editor):
|
||||
"""
|
||||
Migrate data from old LighthouseConfiguration to new multi-provider models.
|
||||
Old system: one LighthouseConfiguration per tenant (always OpenAI).
|
||||
"""
|
||||
LighthouseConfiguration = apps.get_model("api", "LighthouseConfiguration")
|
||||
LighthouseProviderConfiguration = apps.get_model(
|
||||
"api", "LighthouseProviderConfiguration"
|
||||
)
|
||||
LighthouseTenantConfiguration = apps.get_model(
|
||||
"api", "LighthouseTenantConfiguration"
|
||||
)
|
||||
LighthouseProviderModels = apps.get_model("api", "LighthouseProviderModels")
|
||||
|
||||
fernet = Fernet(settings.SECRETS_ENCRYPTION_KEY.encode())
|
||||
|
||||
# Migrate only tenants that actually have a LighthouseConfiguration
|
||||
for old_config in (
|
||||
LighthouseConfiguration.objects.using(MainRouter.admin_db)
|
||||
.select_related("tenant")
|
||||
.all()
|
||||
):
|
||||
tenant = old_config.tenant
|
||||
tenant_id = str(tenant.id)
|
||||
|
||||
try:
|
||||
# Create OpenAI provider configuration for this tenant
|
||||
api_key_decrypted = fernet.decrypt(bytes(old_config.api_key)).decode()
|
||||
credentials_encrypted = fernet.encrypt(
|
||||
json.dumps({"api_key": api_key_decrypted}).encode()
|
||||
)
|
||||
provider_config = LighthouseProviderConfiguration.objects.using(
|
||||
MainRouter.admin_db
|
||||
).create(
|
||||
tenant=tenant,
|
||||
provider_type="openai",
|
||||
credentials=credentials_encrypted,
|
||||
is_active=old_config.is_active,
|
||||
)
|
||||
|
||||
# Create tenant configuration from old values
|
||||
LighthouseTenantConfiguration.objects.using(MainRouter.admin_db).create(
|
||||
tenant=tenant,
|
||||
business_context=old_config.business_context or "",
|
||||
default_provider="openai",
|
||||
default_models={"openai": old_config.model},
|
||||
)
|
||||
|
||||
# Create initial provider model record
|
||||
LighthouseProviderModels.objects.using(MainRouter.admin_db).create(
|
||||
tenant=tenant,
|
||||
provider_configuration=provider_config,
|
||||
model_id=old_config.model,
|
||||
model_name=old_config.model,
|
||||
default_parameters={},
|
||||
)
|
||||
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"Failed to migrate lighthouse config for tenant %s", tenant_id
|
||||
)
|
||||
continue
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [
|
||||
("api", "0049_compliancerequirementoverview_passed_failed_findings"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name="LighthouseProviderConfiguration",
|
||||
fields=[
|
||||
(
|
||||
"id",
|
||||
models.UUIDField(
|
||||
default=uuid.uuid4,
|
||||
editable=False,
|
||||
primary_key=True,
|
||||
serialize=False,
|
||||
),
|
||||
),
|
||||
("inserted_at", models.DateTimeField(auto_now_add=True)),
|
||||
("updated_at", models.DateTimeField(auto_now=True)),
|
||||
(
|
||||
"provider_type",
|
||||
models.CharField(
|
||||
choices=[("openai", "OpenAI")],
|
||||
help_text="LLM provider name",
|
||||
max_length=50,
|
||||
),
|
||||
),
|
||||
("base_url", models.URLField(blank=True, null=True)),
|
||||
(
|
||||
"credentials",
|
||||
models.BinaryField(
|
||||
help_text="Encrypted JSON credentials for the provider"
|
||||
),
|
||||
),
|
||||
("is_active", models.BooleanField(default=True)),
|
||||
],
|
||||
options={
|
||||
"db_table": "lighthouse_provider_configurations",
|
||||
"abstract": False,
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name="LighthouseProviderModels",
|
||||
fields=[
|
||||
(
|
||||
"id",
|
||||
models.UUIDField(
|
||||
default=uuid.uuid4,
|
||||
editable=False,
|
||||
primary_key=True,
|
||||
serialize=False,
|
||||
),
|
||||
),
|
||||
("inserted_at", models.DateTimeField(auto_now_add=True)),
|
||||
("updated_at", models.DateTimeField(auto_now=True)),
|
||||
("model_id", models.CharField(max_length=100)),
|
||||
("model_name", models.CharField(max_length=100)),
|
||||
("default_parameters", models.JSONField(blank=True, default=dict)),
|
||||
],
|
||||
options={
|
||||
"db_table": "lighthouse_provider_models",
|
||||
"abstract": False,
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name="LighthouseTenantConfiguration",
|
||||
fields=[
|
||||
(
|
||||
"id",
|
||||
models.UUIDField(
|
||||
default=uuid.uuid4,
|
||||
editable=False,
|
||||
primary_key=True,
|
||||
serialize=False,
|
||||
),
|
||||
),
|
||||
("inserted_at", models.DateTimeField(auto_now_add=True)),
|
||||
("updated_at", models.DateTimeField(auto_now=True)),
|
||||
("business_context", models.TextField(blank=True, default="")),
|
||||
("default_provider", models.CharField(blank=True, max_length=50)),
|
||||
("default_models", models.JSONField(blank=True, default=dict)),
|
||||
],
|
||||
options={
|
||||
"db_table": "lighthouse_tenant_config",
|
||||
"abstract": False,
|
||||
},
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name="lighthouseproviderconfiguration",
|
||||
name="tenant",
|
||||
field=models.ForeignKey(
|
||||
on_delete=django.db.models.deletion.CASCADE, to="api.tenant"
|
||||
),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name="lighthouseprovidermodels",
|
||||
name="provider_configuration",
|
||||
field=models.ForeignKey(
|
||||
on_delete=django.db.models.deletion.CASCADE,
|
||||
related_name="available_models",
|
||||
to="api.lighthouseproviderconfiguration",
|
||||
),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name="lighthouseprovidermodels",
|
||||
name="tenant",
|
||||
field=models.ForeignKey(
|
||||
on_delete=django.db.models.deletion.CASCADE, to="api.tenant"
|
||||
),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name="lighthousetenantconfiguration",
|
||||
name="tenant",
|
||||
field=models.ForeignKey(
|
||||
on_delete=django.db.models.deletion.CASCADE, to="api.tenant"
|
||||
),
|
||||
),
|
||||
migrations.AddIndex(
|
||||
model_name="lighthouseproviderconfiguration",
|
||||
index=models.Index(
|
||||
fields=["tenant_id", "provider_type"], name="lh_pc_tenant_type_idx"
|
||||
),
|
||||
),
|
||||
migrations.AddConstraint(
|
||||
model_name="lighthouseproviderconfiguration",
|
||||
constraint=api.rls.RowLevelSecurityConstraint(
|
||||
"tenant_id",
|
||||
name="rls_on_lighthouseproviderconfiguration",
|
||||
statements=["SELECT", "INSERT", "UPDATE", "DELETE"],
|
||||
),
|
||||
),
|
||||
migrations.AddConstraint(
|
||||
model_name="lighthouseproviderconfiguration",
|
||||
constraint=models.UniqueConstraint(
|
||||
fields=("tenant_id", "provider_type"),
|
||||
name="unique_provider_config_per_tenant",
|
||||
),
|
||||
),
|
||||
migrations.AddIndex(
|
||||
model_name="lighthouseprovidermodels",
|
||||
index=models.Index(
|
||||
fields=["tenant_id", "provider_configuration"],
|
||||
name="lh_prov_models_cfg_idx",
|
||||
),
|
||||
),
|
||||
migrations.AddConstraint(
|
||||
model_name="lighthouseprovidermodels",
|
||||
constraint=api.rls.RowLevelSecurityConstraint(
|
||||
"tenant_id",
|
||||
name="rls_on_lighthouseprovidermodels",
|
||||
statements=["SELECT", "INSERT", "UPDATE", "DELETE"],
|
||||
),
|
||||
),
|
||||
migrations.AddConstraint(
|
||||
model_name="lighthouseprovidermodels",
|
||||
constraint=models.UniqueConstraint(
|
||||
fields=("tenant_id", "provider_configuration", "model_id"),
|
||||
name="unique_provider_model_per_configuration",
|
||||
),
|
||||
),
|
||||
migrations.AddConstraint(
|
||||
model_name="lighthousetenantconfiguration",
|
||||
constraint=api.rls.RowLevelSecurityConstraint(
|
||||
"tenant_id",
|
||||
name="rls_on_lighthousetenantconfiguration",
|
||||
statements=["SELECT", "INSERT", "UPDATE", "DELETE"],
|
||||
),
|
||||
),
|
||||
migrations.AddConstraint(
|
||||
model_name="lighthousetenantconfiguration",
|
||||
constraint=models.UniqueConstraint(
|
||||
fields=("tenant_id",), name="unique_tenant_lighthouse_config"
|
||||
),
|
||||
),
|
||||
# Migrate data from old LighthouseConfiguration to new tables
|
||||
# This runs after all tables, indexes, and constraints are created
|
||||
# The old Lighthouse configuration table is not removed, so reverse_code is noop
|
||||
# During rollbacks, the old Lighthouse configuration remains intact while the new tables are removed
|
||||
migrations.RunPython(
|
||||
migrate_lighthouse_configs_forward,
|
||||
reverse_code=migrations.RunPython.noop,
|
||||
),
|
||||
]
|
||||
+181
-25
@@ -1873,22 +1873,6 @@ class LighthouseConfiguration(RowLevelSecurityProtectedModel):
|
||||
def clean(self):
|
||||
super().clean()
|
||||
|
||||
# Validate temperature
|
||||
if not 0 <= self.temperature <= 1:
|
||||
raise ModelValidationError(
|
||||
detail="Temperature must be between 0 and 1",
|
||||
code="invalid_temperature",
|
||||
pointer="/data/attributes/temperature",
|
||||
)
|
||||
|
||||
# Validate max_tokens
|
||||
if not 500 <= self.max_tokens <= 5000:
|
||||
raise ModelValidationError(
|
||||
detail="Max tokens must be between 500 and 5000",
|
||||
code="invalid_max_tokens",
|
||||
pointer="/data/attributes/max_tokens",
|
||||
)
|
||||
|
||||
@property
|
||||
def api_key_decoded(self):
|
||||
"""Return the decrypted API key, or None if unavailable or invalid."""
|
||||
@@ -1913,15 +1897,6 @@ class LighthouseConfiguration(RowLevelSecurityProtectedModel):
|
||||
code="invalid_api_key",
|
||||
pointer="/data/attributes/api_key",
|
||||
)
|
||||
|
||||
# Validate OpenAI API key format
|
||||
openai_key_pattern = r"^sk-[\w-]+T3BlbkFJ[\w-]+$"
|
||||
if not re.match(openai_key_pattern, value):
|
||||
raise ModelValidationError(
|
||||
detail="Invalid OpenAI API key format.",
|
||||
code="invalid_api_key",
|
||||
pointer="/data/attributes/api_key",
|
||||
)
|
||||
self.api_key = fernet.encrypt(value.encode())
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
@@ -1984,3 +1959,184 @@ class Processor(RowLevelSecurityProtectedModel):
|
||||
|
||||
class JSONAPIMeta:
|
||||
resource_name = "processors"
|
||||
|
||||
|
||||
class LighthouseProviderConfiguration(RowLevelSecurityProtectedModel):
|
||||
"""
|
||||
Per-tenant configuration for an LLM provider (credentials, base URL, activation).
|
||||
|
||||
One configuration per provider type per tenant.
|
||||
"""
|
||||
|
||||
class LLMProviderChoices(models.TextChoices):
|
||||
OPENAI = "openai", _("OpenAI")
|
||||
|
||||
id = models.UUIDField(primary_key=True, default=uuid4, editable=False)
|
||||
inserted_at = models.DateTimeField(auto_now_add=True, editable=False)
|
||||
updated_at = models.DateTimeField(auto_now=True, editable=False)
|
||||
|
||||
provider_type = models.CharField(
|
||||
max_length=50,
|
||||
choices=LLMProviderChoices.choices,
|
||||
help_text="LLM provider name",
|
||||
)
|
||||
|
||||
# For OpenAI-compatible providers
|
||||
base_url = models.URLField(blank=True, null=True)
|
||||
|
||||
# Encrypted JSON for provider-specific auth
|
||||
credentials = models.BinaryField(
|
||||
blank=False, null=False, help_text="Encrypted JSON credentials for the provider"
|
||||
)
|
||||
|
||||
is_active = models.BooleanField(default=True)
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.get_provider_type_display()} ({self.tenant_id})"
|
||||
|
||||
def clean(self):
|
||||
super().clean()
|
||||
|
||||
@property
|
||||
def credentials_decoded(self):
|
||||
if not self.credentials:
|
||||
return None
|
||||
try:
|
||||
decrypted_data = fernet.decrypt(bytes(self.credentials))
|
||||
return json.loads(decrypted_data.decode())
|
||||
except (InvalidToken, json.JSONDecodeError) as e:
|
||||
logger.warning("Failed to decrypt provider credentials: %s", e)
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.exception(
|
||||
"Unexpected error while decrypting provider credentials: %s", e
|
||||
)
|
||||
return None
|
||||
|
||||
@credentials_decoded.setter
|
||||
def credentials_decoded(self, value):
|
||||
"""
|
||||
Set and encrypt credentials (assumes serializer performed validation).
|
||||
"""
|
||||
if not value:
|
||||
raise ModelValidationError(
|
||||
detail="Credentials are required",
|
||||
code="invalid_credentials",
|
||||
pointer="/data/attributes/credentials",
|
||||
)
|
||||
self.credentials = fernet.encrypt(json.dumps(value).encode())
|
||||
|
||||
class Meta(RowLevelSecurityProtectedModel.Meta):
|
||||
db_table = "lighthouse_provider_configurations"
|
||||
|
||||
constraints = [
|
||||
RowLevelSecurityConstraint(
|
||||
field="tenant_id",
|
||||
name="rls_on_%(class)s",
|
||||
statements=["SELECT", "INSERT", "UPDATE", "DELETE"],
|
||||
),
|
||||
models.UniqueConstraint(
|
||||
fields=["tenant_id", "provider_type"],
|
||||
name="unique_provider_config_per_tenant",
|
||||
),
|
||||
]
|
||||
|
||||
indexes = [
|
||||
models.Index(
|
||||
fields=["tenant_id", "provider_type"],
|
||||
name="lh_pc_tenant_type_idx",
|
||||
),
|
||||
]
|
||||
|
||||
class JSONAPIMeta:
|
||||
resource_name = "lighthouse-providers"
|
||||
|
||||
|
||||
class LighthouseTenantConfiguration(RowLevelSecurityProtectedModel):
|
||||
"""
|
||||
Tenant-level Lighthouse settings (business context and defaults).
|
||||
One record per tenant.
|
||||
"""
|
||||
|
||||
id = models.UUIDField(primary_key=True, default=uuid4, editable=False)
|
||||
inserted_at = models.DateTimeField(auto_now_add=True, editable=False)
|
||||
updated_at = models.DateTimeField(auto_now=True, editable=False)
|
||||
|
||||
business_context = models.TextField(blank=True, default="")
|
||||
|
||||
# Preferred provider key (e.g., "openai", "bedrock", "openai_compatible")
|
||||
default_provider = models.CharField(max_length=50, blank=True)
|
||||
|
||||
# Mapping of provider -> model id, e.g., {"openai": "gpt-4o", "bedrock": "anthropic.claude-v2"}
|
||||
default_models = models.JSONField(default=dict, blank=True)
|
||||
|
||||
def __str__(self):
|
||||
return f"Lighthouse Tenant Config for {self.tenant_id}"
|
||||
|
||||
def clean(self):
|
||||
super().clean()
|
||||
|
||||
class Meta(RowLevelSecurityProtectedModel.Meta):
|
||||
db_table = "lighthouse_tenant_config"
|
||||
|
||||
constraints = [
|
||||
RowLevelSecurityConstraint(
|
||||
field="tenant_id",
|
||||
name="rls_on_%(class)s",
|
||||
statements=["SELECT", "INSERT", "UPDATE", "DELETE"],
|
||||
),
|
||||
models.UniqueConstraint(
|
||||
fields=["tenant_id"], name="unique_tenant_lighthouse_config"
|
||||
),
|
||||
]
|
||||
|
||||
class JSONAPIMeta:
|
||||
resource_name = "lighthouse-config"
|
||||
|
||||
|
||||
class LighthouseProviderModels(RowLevelSecurityProtectedModel):
|
||||
"""
|
||||
Per-tenant, per-provider configuration list of available LLM models.
|
||||
RLS-protected; populated via provider API using tenant-scoped credentials.
|
||||
"""
|
||||
|
||||
id = models.UUIDField(primary_key=True, default=uuid4, editable=False)
|
||||
inserted_at = models.DateTimeField(auto_now_add=True, editable=False)
|
||||
updated_at = models.DateTimeField(auto_now=True, editable=False)
|
||||
|
||||
# Scope to a specific provider configuration within a tenant
|
||||
provider_configuration = models.ForeignKey(
|
||||
LighthouseProviderConfiguration,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="available_models",
|
||||
)
|
||||
model_id = models.CharField(max_length=100)
|
||||
|
||||
# Human-friendly model name
|
||||
model_name = models.CharField(max_length=100)
|
||||
|
||||
# Model-specific default parameters (e.g., temperature, max_tokens)
|
||||
default_parameters = models.JSONField(default=dict, blank=True)
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.provider_configuration.provider_type}:{self.model_id} ({self.tenant_id})"
|
||||
|
||||
class Meta(RowLevelSecurityProtectedModel.Meta):
|
||||
db_table = "lighthouse_provider_models"
|
||||
constraints = [
|
||||
RowLevelSecurityConstraint(
|
||||
field="tenant_id",
|
||||
name="rls_on_%(class)s",
|
||||
statements=["SELECT", "INSERT", "UPDATE", "DELETE"],
|
||||
),
|
||||
models.UniqueConstraint(
|
||||
fields=["tenant_id", "provider_configuration", "model_id"],
|
||||
name="unique_provider_model_per_configuration",
|
||||
),
|
||||
]
|
||||
indexes = [
|
||||
models.Index(
|
||||
fields=["tenant_id", "provider_configuration"],
|
||||
name="lh_prov_models_cfg_idx",
|
||||
),
|
||||
]
|
||||
|
||||
@@ -6,7 +6,14 @@ from django.dispatch import receiver
|
||||
from django_celery_results.backends.database import DatabaseBackend
|
||||
|
||||
from api.db_utils import delete_related_daily_task
|
||||
from api.models import Membership, Provider, TenantAPIKey, User
|
||||
from api.models import (
|
||||
LighthouseProviderConfiguration,
|
||||
LighthouseTenantConfiguration,
|
||||
Membership,
|
||||
Provider,
|
||||
TenantAPIKey,
|
||||
User,
|
||||
)
|
||||
|
||||
|
||||
def create_task_result_on_publish(sender=None, headers=None, **kwargs): # noqa: F841
|
||||
@@ -56,3 +63,33 @@ def revoke_membership_api_keys(sender, instance, **kwargs): # noqa: F841
|
||||
TenantAPIKey.objects.filter(
|
||||
entity=instance.user, tenant_id=instance.tenant.id
|
||||
).update(revoked=True)
|
||||
|
||||
|
||||
@receiver(pre_delete, sender=LighthouseProviderConfiguration)
|
||||
def cleanup_lighthouse_defaults_before_delete(sender, instance, **kwargs): # noqa: F841
|
||||
"""
|
||||
Ensure tenant Lighthouse defaults do not reference a soon-to-be-deleted provider.
|
||||
|
||||
This runs for both per-instance deletes and queryset (bulk) deletes.
|
||||
"""
|
||||
try:
|
||||
tenant_cfg = LighthouseTenantConfiguration.objects.get(
|
||||
tenant_id=instance.tenant_id
|
||||
)
|
||||
except LighthouseTenantConfiguration.DoesNotExist:
|
||||
return
|
||||
|
||||
updated = False
|
||||
defaults = tenant_cfg.default_models or {}
|
||||
|
||||
if instance.provider_type in defaults:
|
||||
defaults.pop(instance.provider_type, None)
|
||||
tenant_cfg.default_models = defaults
|
||||
updated = True
|
||||
|
||||
if tenant_cfg.default_provider == instance.provider_type:
|
||||
tenant_cfg.default_provider = ""
|
||||
updated = True
|
||||
|
||||
if updated:
|
||||
tenant_cfg.save()
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -35,6 +35,9 @@ from api.db_router import MainRouter
|
||||
from api.models import (
|
||||
Integration,
|
||||
Invitation,
|
||||
LighthouseProviderConfiguration,
|
||||
LighthouseProviderModels,
|
||||
LighthouseTenantConfiguration,
|
||||
Membership,
|
||||
Processor,
|
||||
Provider,
|
||||
@@ -2689,6 +2692,55 @@ class TestScanViewSet:
|
||||
== "There is a problem with credentials."
|
||||
)
|
||||
|
||||
@patch("api.v1.views.ScanViewSet._get_task_status")
|
||||
@patch("api.v1.views.get_s3_client")
|
||||
@patch("api.v1.views.env.str")
|
||||
def test_threatscore_s3_wildcard(
|
||||
self,
|
||||
mock_env_str,
|
||||
mock_get_s3_client,
|
||||
mock_get_task_status,
|
||||
authenticated_client,
|
||||
scans_fixture,
|
||||
):
|
||||
"""
|
||||
When the threatscore endpoint is called with an S3 output_location,
|
||||
the view should list objects in S3 using wildcard pattern matching,
|
||||
retrieve the matching PDF file, and return it with HTTP 200 and proper headers.
|
||||
"""
|
||||
scan = scans_fixture[0]
|
||||
scan.state = StateChoices.COMPLETED
|
||||
bucket = "test-bucket"
|
||||
zip_key = "tenant-id/scan-id/prowler-output-foo.zip"
|
||||
scan.output_location = f"s3://{bucket}/{zip_key}"
|
||||
scan.save()
|
||||
|
||||
pdf_key = os.path.join(
|
||||
os.path.dirname(zip_key),
|
||||
"threatscore",
|
||||
"prowler-output-123_threatscore_report.pdf",
|
||||
)
|
||||
|
||||
mock_s3_client = Mock()
|
||||
mock_s3_client.list_objects_v2.return_value = {"Contents": [{"Key": pdf_key}]}
|
||||
mock_s3_client.get_object.return_value = {"Body": io.BytesIO(b"pdf-bytes")}
|
||||
|
||||
mock_env_str.return_value = bucket
|
||||
mock_get_s3_client.return_value = mock_s3_client
|
||||
mock_get_task_status.return_value = None
|
||||
|
||||
url = reverse("scan-threatscore", kwargs={"pk": scan.id})
|
||||
response = authenticated_client.get(url)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
assert response["Content-Type"] == "application/pdf"
|
||||
assert response["Content-Disposition"].endswith(
|
||||
'"prowler-output-123_threatscore_report.pdf"'
|
||||
)
|
||||
assert response.content == b"pdf-bytes"
|
||||
mock_s3_client.list_objects_v2.assert_called_once()
|
||||
mock_s3_client.get_object.assert_called_once_with(Bucket=bucket, Key=pdf_key)
|
||||
|
||||
def test_report_s3_success(self, authenticated_client, scans_fixture, monkeypatch):
|
||||
"""
|
||||
When output_location is an S3 URL and the S3 client returns the file successfully,
|
||||
@@ -8654,3 +8706,483 @@ class TestTenantApiKeyViewSet:
|
||||
# Verify error object structure
|
||||
error = response_data["errors"][0]
|
||||
assert "detail" in error or "title" in error
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestLighthouseTenantConfigViewSet:
|
||||
"""Test Lighthouse tenant configuration endpoint (singleton pattern)"""
|
||||
|
||||
def test_lighthouse_tenant_config_create_via_patch(self, authenticated_client):
|
||||
"""Test creating a tenant config successfully via PATCH (upsert)"""
|
||||
payload = {
|
||||
"data": {
|
||||
"type": "lighthouse-config",
|
||||
"attributes": {
|
||||
"business_context": "Test business context for security analysis",
|
||||
"default_provider": "",
|
||||
"default_models": {},
|
||||
},
|
||||
}
|
||||
}
|
||||
response = authenticated_client.patch(
|
||||
reverse("lighthouse-config"),
|
||||
data=payload,
|
||||
content_type=API_JSON_CONTENT_TYPE,
|
||||
)
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
data = response.json()["data"]
|
||||
assert (
|
||||
data["attributes"]["business_context"]
|
||||
== "Test business context for security analysis"
|
||||
)
|
||||
assert data["attributes"]["default_provider"] == ""
|
||||
assert data["attributes"]["default_models"] == {}
|
||||
|
||||
def test_lighthouse_tenant_config_upsert_behavior(self, authenticated_client):
|
||||
"""Test that PATCH creates config if not exists and updates if exists (upsert)"""
|
||||
payload = {
|
||||
"data": {
|
||||
"type": "lighthouse-config",
|
||||
"attributes": {
|
||||
"business_context": "First config",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
# First PATCH creates the config
|
||||
response = authenticated_client.patch(
|
||||
reverse("lighthouse-config"),
|
||||
data=payload,
|
||||
content_type=API_JSON_CONTENT_TYPE,
|
||||
)
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
first_data = response.json()["data"]
|
||||
assert first_data["attributes"]["business_context"] == "First config"
|
||||
|
||||
# Second PATCH updates the same config (not creating a duplicate)
|
||||
payload["data"]["attributes"]["business_context"] = "Updated config"
|
||||
response = authenticated_client.patch(
|
||||
reverse("lighthouse-config"),
|
||||
data=payload,
|
||||
content_type=API_JSON_CONTENT_TYPE,
|
||||
)
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
second_data = response.json()["data"]
|
||||
assert second_data["attributes"]["business_context"] == "Updated config"
|
||||
# Verify it's the same config (same ID)
|
||||
assert first_data["id"] == second_data["id"]
|
||||
|
||||
@patch("openai.OpenAI")
|
||||
def test_lighthouse_tenant_config_retrieve(
|
||||
self, mock_openai_client, authenticated_client, tenants_fixture
|
||||
):
|
||||
"""Test retrieving the singleton tenant config with proper provider and model validation"""
|
||||
|
||||
# Mock OpenAI client and models response
|
||||
mock_models_response = Mock()
|
||||
mock_models_response.data = [
|
||||
Mock(id="gpt-4o"),
|
||||
Mock(id="gpt-4o-mini"),
|
||||
Mock(id="gpt-5"),
|
||||
]
|
||||
mock_openai_client.return_value.models.list.return_value = mock_models_response
|
||||
|
||||
# Create OpenAI provider configuration
|
||||
provider_config = LighthouseProviderConfiguration.objects.create(
|
||||
tenant_id=tenants_fixture[0].id,
|
||||
provider_type="openai",
|
||||
credentials=b'{"api_key": "sk-test1234567890T3BlbkFJtest1234567890"}',
|
||||
is_active=True,
|
||||
)
|
||||
|
||||
# Create provider models (simulating refresh)
|
||||
LighthouseProviderModels.objects.create(
|
||||
tenant_id=tenants_fixture[0].id,
|
||||
provider_configuration=provider_config,
|
||||
model_id="gpt-4o",
|
||||
default_parameters={},
|
||||
)
|
||||
LighthouseProviderModels.objects.create(
|
||||
tenant_id=tenants_fixture[0].id,
|
||||
provider_configuration=provider_config,
|
||||
model_id="gpt-4o-mini",
|
||||
default_parameters={},
|
||||
)
|
||||
|
||||
# Create tenant configuration with valid provider and model
|
||||
config = LighthouseTenantConfiguration.objects.create(
|
||||
tenant_id=tenants_fixture[0].id,
|
||||
business_context="Test context",
|
||||
default_provider="openai",
|
||||
default_models={"openai": "gpt-4o"},
|
||||
)
|
||||
|
||||
# Retrieve and verify the configuration
|
||||
response = authenticated_client.get(reverse("lighthouse-config"))
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
data = response.json()["data"]
|
||||
assert data["id"] == str(config.id)
|
||||
assert data["attributes"]["business_context"] == "Test context"
|
||||
assert data["attributes"]["default_provider"] == "openai"
|
||||
assert data["attributes"]["default_models"] == {"openai": "gpt-4o"}
|
||||
|
||||
def test_lighthouse_tenant_config_retrieve_not_found(self, authenticated_client):
|
||||
"""Test GET when config doesn't exist returns 404"""
|
||||
response = authenticated_client.get(reverse("lighthouse-config"))
|
||||
assert response.status_code == status.HTTP_404_NOT_FOUND
|
||||
assert "not found" in response.json()["errors"][0]["detail"].lower()
|
||||
|
||||
def test_lighthouse_tenant_config_partial_update(
|
||||
self, authenticated_client, tenants_fixture
|
||||
):
|
||||
"""Test updating tenant config fields"""
|
||||
from api.models import LighthouseTenantConfiguration
|
||||
|
||||
# Create config first
|
||||
config = LighthouseTenantConfiguration.objects.create(
|
||||
tenant_id=tenants_fixture[0].id,
|
||||
business_context="Original context",
|
||||
default_provider="",
|
||||
default_models={},
|
||||
)
|
||||
|
||||
# Update it
|
||||
payload = {
|
||||
"data": {
|
||||
"type": "lighthouse-config",
|
||||
"attributes": {
|
||||
"business_context": "Updated context for cloud security",
|
||||
},
|
||||
}
|
||||
}
|
||||
response = authenticated_client.patch(
|
||||
reverse("lighthouse-config"),
|
||||
data=payload,
|
||||
content_type=API_JSON_CONTENT_TYPE,
|
||||
)
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
|
||||
# Verify update
|
||||
config.refresh_from_db()
|
||||
assert config.business_context == "Updated context for cloud security"
|
||||
|
||||
def test_lighthouse_tenant_config_update_invalid_provider(
|
||||
self, authenticated_client, tenants_fixture
|
||||
):
|
||||
"""Test validation fails when default_provider is not configured and active"""
|
||||
from api.models import LighthouseTenantConfiguration
|
||||
|
||||
# Create config first
|
||||
LighthouseTenantConfiguration.objects.create(
|
||||
tenant_id=tenants_fixture[0].id,
|
||||
business_context="Test",
|
||||
)
|
||||
|
||||
# Try to set invalid provider
|
||||
payload = {
|
||||
"data": {
|
||||
"type": "lighthouse-config",
|
||||
"attributes": {
|
||||
"default_provider": "nonexistent-provider",
|
||||
},
|
||||
}
|
||||
}
|
||||
response = authenticated_client.patch(
|
||||
reverse("lighthouse-config"),
|
||||
data=payload,
|
||||
content_type=API_JSON_CONTENT_TYPE,
|
||||
)
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
assert "provider" in response.json()["errors"][0]["detail"].lower()
|
||||
|
||||
def test_lighthouse_tenant_config_update_invalid_json_format(
|
||||
self, authenticated_client, tenants_fixture
|
||||
):
|
||||
"""Test that invalid JSON payload is rejected"""
|
||||
from api.models import LighthouseTenantConfiguration
|
||||
|
||||
# Create config first
|
||||
LighthouseTenantConfiguration.objects.create(
|
||||
tenant_id=tenants_fixture[0].id,
|
||||
business_context="Test",
|
||||
)
|
||||
|
||||
# Send invalid JSON
|
||||
response = authenticated_client.patch(
|
||||
reverse("lighthouse-config"),
|
||||
data="invalid json",
|
||||
content_type=API_JSON_CONTENT_TYPE,
|
||||
)
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestLighthouseProviderConfigViewSet:
|
||||
"""Tests for LighthouseProviderConfiguration create validations"""
|
||||
|
||||
def test_invalid_provider_type(self, authenticated_client):
|
||||
"""Add invalid provider (testprovider) should error"""
|
||||
payload = {
|
||||
"data": {
|
||||
"type": "lighthouse-providers",
|
||||
"attributes": {
|
||||
"provider_type": "testprovider",
|
||||
"credentials": {"api_key": "sk-testT3BlbkFJkey"},
|
||||
},
|
||||
}
|
||||
}
|
||||
resp = authenticated_client.post(
|
||||
reverse("lighthouse-providers-list"),
|
||||
data=payload,
|
||||
content_type=API_JSON_CONTENT_TYPE,
|
||||
)
|
||||
assert resp.status_code == status.HTTP_400_BAD_REQUEST
|
||||
|
||||
def test_openai_missing_credentials(self, authenticated_client):
|
||||
"""OpenAI provider without credentials should error"""
|
||||
payload = {
|
||||
"data": {
|
||||
"type": "lighthouse-providers",
|
||||
"attributes": {
|
||||
"provider_type": "openai",
|
||||
},
|
||||
}
|
||||
}
|
||||
resp = authenticated_client.post(
|
||||
reverse("lighthouse-providers-list"),
|
||||
data=payload,
|
||||
content_type=API_JSON_CONTENT_TYPE,
|
||||
)
|
||||
assert resp.status_code == status.HTTP_400_BAD_REQUEST
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"credentials",
|
||||
[
|
||||
{}, # empty credentials
|
||||
{"token": "sk-testT3BlbkFJkey"}, # wrong key name
|
||||
{"api_key": "ks-invalid-format"}, # wrong format
|
||||
],
|
||||
)
|
||||
def test_openai_invalid_credentials(self, authenticated_client, credentials):
|
||||
"""OpenAI provider with invalid credentials should error"""
|
||||
payload = {
|
||||
"data": {
|
||||
"type": "lighthouse-providers",
|
||||
"attributes": {
|
||||
"provider_type": "openai",
|
||||
"credentials": credentials,
|
||||
},
|
||||
}
|
||||
}
|
||||
resp = authenticated_client.post(
|
||||
reverse("lighthouse-providers-list"),
|
||||
data=payload,
|
||||
content_type=API_JSON_CONTENT_TYPE,
|
||||
)
|
||||
assert resp.status_code == status.HTTP_400_BAD_REQUEST
|
||||
|
||||
def test_openai_valid_credentials_success(self, authenticated_client):
|
||||
"""OpenAI provider with valid sk-xxx format should succeed"""
|
||||
valid_key = "sk-abc123T3BlbkFJxyz456"
|
||||
payload = {
|
||||
"data": {
|
||||
"type": "lighthouse-providers",
|
||||
"attributes": {
|
||||
"provider_type": "openai",
|
||||
"credentials": {"api_key": valid_key},
|
||||
},
|
||||
}
|
||||
}
|
||||
resp = authenticated_client.post(
|
||||
reverse("lighthouse-providers-list"),
|
||||
data=payload,
|
||||
content_type=API_JSON_CONTENT_TYPE,
|
||||
)
|
||||
assert resp.status_code == status.HTTP_201_CREATED
|
||||
data = resp.json()["data"]
|
||||
|
||||
masked_creds = data["attributes"].get("credentials")
|
||||
assert masked_creds is not None
|
||||
assert "api_key" in masked_creds
|
||||
assert masked_creds["api_key"] == ("*" * len(valid_key))
|
||||
|
||||
def test_openai_provider_duplicate_per_tenant(self, authenticated_client):
|
||||
"""If an OpenAI provider exists for tenant, creating again should error"""
|
||||
valid_key = "sk-dup123T3BlbkFJdup456"
|
||||
payload = {
|
||||
"data": {
|
||||
"type": "lighthouse-providers",
|
||||
"attributes": {
|
||||
"provider_type": "openai",
|
||||
"credentials": {"api_key": valid_key},
|
||||
},
|
||||
}
|
||||
}
|
||||
# First creation succeeds
|
||||
resp1 = authenticated_client.post(
|
||||
reverse("lighthouse-providers-list"),
|
||||
data=payload,
|
||||
content_type=API_JSON_CONTENT_TYPE,
|
||||
)
|
||||
assert resp1.status_code == status.HTTP_201_CREATED
|
||||
|
||||
# Second creation should fail with validation error
|
||||
resp2 = authenticated_client.post(
|
||||
reverse("lighthouse-providers-list"),
|
||||
data=payload,
|
||||
content_type=API_JSON_CONTENT_TYPE,
|
||||
)
|
||||
assert resp2.status_code == status.HTTP_400_BAD_REQUEST
|
||||
assert "already exists" in str(resp2.json()).lower()
|
||||
|
||||
def test_openai_patch_base_url_and_is_active(self, authenticated_client):
|
||||
"""After creating, should be able to patch base_url and is_active"""
|
||||
valid_key = "sk-patch123T3BlbkFJpatch456"
|
||||
create_payload = {
|
||||
"data": {
|
||||
"type": "lighthouse-providers",
|
||||
"attributes": {
|
||||
"provider_type": "openai",
|
||||
"credentials": {"api_key": valid_key},
|
||||
},
|
||||
}
|
||||
}
|
||||
create_resp = authenticated_client.post(
|
||||
reverse("lighthouse-providers-list"),
|
||||
data=create_payload,
|
||||
content_type=API_JSON_CONTENT_TYPE,
|
||||
)
|
||||
assert create_resp.status_code == status.HTTP_201_CREATED
|
||||
provider_id = create_resp.json()["data"]["id"]
|
||||
|
||||
patch_payload = {
|
||||
"data": {
|
||||
"type": "lighthouse-providers",
|
||||
"id": provider_id,
|
||||
"attributes": {
|
||||
"base_url": "https://api.example.com/v1",
|
||||
"is_active": False,
|
||||
},
|
||||
}
|
||||
}
|
||||
patch_resp = authenticated_client.patch(
|
||||
reverse("lighthouse-providers-detail", kwargs={"pk": provider_id}),
|
||||
data=patch_payload,
|
||||
content_type=API_JSON_CONTENT_TYPE,
|
||||
)
|
||||
assert patch_resp.status_code == status.HTTP_200_OK
|
||||
updated = patch_resp.json()["data"]["attributes"]
|
||||
assert updated["base_url"] == "https://api.example.com/v1"
|
||||
assert updated["is_active"] is False
|
||||
|
||||
def test_openai_patch_invalid_credentials(self, authenticated_client):
|
||||
"""PATCH with invalid credentials.api_key should error (400)"""
|
||||
valid_key = "sk-ok123T3BlbkFJok456"
|
||||
create_payload = {
|
||||
"data": {
|
||||
"type": "lighthouse-providers",
|
||||
"attributes": {
|
||||
"provider_type": "openai",
|
||||
"credentials": {"api_key": valid_key},
|
||||
},
|
||||
}
|
||||
}
|
||||
create_resp = authenticated_client.post(
|
||||
reverse("lighthouse-providers-list"),
|
||||
data=create_payload,
|
||||
content_type=API_JSON_CONTENT_TYPE,
|
||||
)
|
||||
assert create_resp.status_code == status.HTTP_201_CREATED
|
||||
provider_id = create_resp.json()["data"]["id"]
|
||||
|
||||
# Try patch with invalid api_key format
|
||||
patch_payload = {
|
||||
"data": {
|
||||
"type": "lighthouse-providers",
|
||||
"id": provider_id,
|
||||
"attributes": {
|
||||
"credentials": {"api_key": "ks-invalid-format"},
|
||||
},
|
||||
}
|
||||
}
|
||||
patch_resp = authenticated_client.patch(
|
||||
reverse("lighthouse-providers-detail", kwargs={"pk": provider_id}),
|
||||
data=patch_payload,
|
||||
content_type=API_JSON_CONTENT_TYPE,
|
||||
)
|
||||
assert patch_resp.status_code == status.HTTP_400_BAD_REQUEST
|
||||
|
||||
def test_openai_get_masking_and_fields_filter(self, authenticated_client):
|
||||
valid_key = "sk-get123T3BlbkFJget456"
|
||||
create_payload = {
|
||||
"data": {
|
||||
"type": "lighthouse-providers",
|
||||
"attributes": {
|
||||
"provider_type": "openai",
|
||||
"credentials": {"api_key": valid_key},
|
||||
},
|
||||
}
|
||||
}
|
||||
create_resp = authenticated_client.post(
|
||||
reverse("lighthouse-providers-list"),
|
||||
data=create_payload,
|
||||
content_type=API_JSON_CONTENT_TYPE,
|
||||
)
|
||||
assert create_resp.status_code == status.HTTP_201_CREATED
|
||||
provider_id = create_resp.json()["data"]["id"]
|
||||
|
||||
# Default GET should return masked credentials
|
||||
get_resp = authenticated_client.get(
|
||||
reverse("lighthouse-providers-detail", kwargs={"pk": provider_id})
|
||||
)
|
||||
assert get_resp.status_code == status.HTTP_200_OK
|
||||
masked = get_resp.json()["data"]["attributes"]["credentials"]["api_key"]
|
||||
assert masked == ("*" * len(valid_key))
|
||||
|
||||
# Fields filter should return decrypted credentials structure
|
||||
get_full = authenticated_client.get(
|
||||
reverse("lighthouse-providers-detail", kwargs={"pk": provider_id})
|
||||
+ "?fields[lighthouse-providers]=credentials"
|
||||
)
|
||||
assert get_full.status_code == status.HTTP_200_OK
|
||||
creds = get_full.json()["data"]["attributes"]["credentials"]
|
||||
assert creds["api_key"] == valid_key
|
||||
|
||||
def test_delete_provider_updates_tenant_defaults(
|
||||
self, authenticated_client, tenants_fixture
|
||||
):
|
||||
"""Deleting a provider config should clear tenant default_provider and its default_model entry."""
|
||||
|
||||
tenant = tenants_fixture[0]
|
||||
|
||||
# Create provider configuration to delete
|
||||
provider = LighthouseProviderConfiguration.objects.create(
|
||||
tenant_id=tenant.id,
|
||||
provider_type="openai",
|
||||
credentials=b'{"api_key":"sk-test123T3BlbkFJ"}',
|
||||
is_active=True,
|
||||
)
|
||||
|
||||
# Seed tenant defaults referencing the provider we will delete
|
||||
cfg = LighthouseTenantConfiguration.objects.create(
|
||||
tenant_id=tenant.id,
|
||||
business_context="Test",
|
||||
default_provider="openai",
|
||||
default_models={"openai": "gpt-4o", "other": "model-x"},
|
||||
)
|
||||
|
||||
# Delete via API and validate response
|
||||
url = reverse("lighthouse-providers-detail", kwargs={"pk": str(provider.id)})
|
||||
resp = authenticated_client.delete(url)
|
||||
assert resp.status_code in (
|
||||
status.HTTP_204_NO_CONTENT,
|
||||
status.HTTP_200_OK,
|
||||
)
|
||||
|
||||
# Tenant defaults should be updated
|
||||
cfg.refresh_from_db()
|
||||
assert cfg.default_provider == ""
|
||||
assert "openai" not in cfg.default_models
|
||||
|
||||
# Unrelated entries should remain untouched
|
||||
assert cfg.default_models.get("other") == "model-x"
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import re
|
||||
|
||||
from rest_framework_json_api import serializers
|
||||
|
||||
|
||||
class OpenAICredentialsSerializer(serializers.Serializer):
|
||||
api_key = serializers.CharField()
|
||||
|
||||
def validate_api_key(self, value: str) -> str:
|
||||
pattern = r"^sk-[\w-]+$"
|
||||
if not re.match(pattern, value or ""):
|
||||
raise serializers.ValidationError("Invalid OpenAI API key format.")
|
||||
return value
|
||||
@@ -6,8 +6,10 @@ from django.conf import settings
|
||||
from django.contrib.auth import authenticate
|
||||
from django.contrib.auth.models import update_last_login
|
||||
from django.contrib.auth.password_validation import validate_password
|
||||
from django.db import IntegrityError
|
||||
from drf_spectacular.utils import extend_schema_field
|
||||
from jwt.exceptions import InvalidKeyError
|
||||
from rest_framework.reverse import reverse
|
||||
from rest_framework.validators import UniqueTogetherValidator
|
||||
from rest_framework_json_api import serializers
|
||||
from rest_framework_json_api.relations import SerializerMethodResourceRelatedField
|
||||
@@ -25,6 +27,9 @@ from api.models import (
|
||||
Invitation,
|
||||
InvitationRoleRelationship,
|
||||
LighthouseConfiguration,
|
||||
LighthouseProviderConfiguration,
|
||||
LighthouseProviderModels,
|
||||
LighthouseTenantConfiguration,
|
||||
Membership,
|
||||
Processor,
|
||||
Provider,
|
||||
@@ -54,6 +59,7 @@ from api.v1.serializer_utils.integrations import (
|
||||
S3ConfigSerializer,
|
||||
SecurityHubConfigSerializer,
|
||||
)
|
||||
from api.v1.serializer_utils.lighthouse import OpenAICredentialsSerializer
|
||||
from api.v1.serializer_utils.processors import ProcessorConfigField
|
||||
from api.v1.serializer_utils.providers import ProviderSecretField
|
||||
from prowler.lib.mutelist.mutelist import Mutelist
|
||||
@@ -2750,6 +2756,16 @@ class LighthouseConfigCreateSerializer(RLSSerializer, BaseWriteSerializer):
|
||||
"updated_at": {"read_only": True},
|
||||
}
|
||||
|
||||
def validate_temperature(self, value):
|
||||
if not 0 <= value <= 1:
|
||||
raise ValidationError("Temperature must be between 0 and 1.")
|
||||
return value
|
||||
|
||||
def validate_max_tokens(self, value):
|
||||
if not 500 <= value <= 5000:
|
||||
raise ValidationError("Max tokens must be between 500 and 5000.")
|
||||
return value
|
||||
|
||||
def validate(self, attrs):
|
||||
tenant_id = self.context.get("request").tenant_id
|
||||
if LighthouseConfiguration.objects.filter(tenant_id=tenant_id).exists():
|
||||
@@ -2758,6 +2774,11 @@ class LighthouseConfigCreateSerializer(RLSSerializer, BaseWriteSerializer):
|
||||
"tenant_id": "Lighthouse configuration already exists for this tenant."
|
||||
}
|
||||
)
|
||||
api_key = attrs.get("api_key")
|
||||
if api_key is not None:
|
||||
OpenAICredentialsSerializer(data={"api_key": api_key}).is_valid(
|
||||
raise_exception=True
|
||||
)
|
||||
return super().validate(attrs)
|
||||
|
||||
def create(self, validated_data):
|
||||
@@ -2802,6 +2823,24 @@ class LighthouseConfigUpdateSerializer(BaseWriteSerializer):
|
||||
"max_tokens": {"required": False},
|
||||
}
|
||||
|
||||
def validate_temperature(self, value):
|
||||
if not 0 <= value <= 1:
|
||||
raise ValidationError("Temperature must be between 0 and 1.")
|
||||
return value
|
||||
|
||||
def validate_max_tokens(self, value):
|
||||
if not 500 <= value <= 5000:
|
||||
raise ValidationError("Max tokens must be between 500 and 5000.")
|
||||
return value
|
||||
|
||||
def validate(self, attrs):
|
||||
api_key = attrs.get("api_key", None)
|
||||
if api_key is not None:
|
||||
OpenAICredentialsSerializer(data={"api_key": api_key}).is_valid(
|
||||
raise_exception=True
|
||||
)
|
||||
return super().validate(attrs)
|
||||
|
||||
def update(self, instance, validated_data):
|
||||
api_key = validated_data.pop("api_key", None)
|
||||
instance = super().update(instance, validated_data)
|
||||
@@ -2931,3 +2970,352 @@ class TenantApiKeyUpdateSerializer(RLSSerializer, BaseWriteSerializer):
|
||||
):
|
||||
raise ValidationError("An API key with this name already exists.")
|
||||
return value
|
||||
|
||||
|
||||
# Lighthouse: Provider configurations
|
||||
|
||||
|
||||
class LighthouseProviderConfigSerializer(RLSSerializer):
|
||||
"""
|
||||
Read serializer for LighthouseProviderConfiguration.
|
||||
"""
|
||||
|
||||
# Decrypted credentials are only returned in to_representation when requested
|
||||
credentials = serializers.JSONField(required=False, read_only=True)
|
||||
|
||||
class Meta:
|
||||
model = LighthouseProviderConfiguration
|
||||
fields = [
|
||||
"id",
|
||||
"inserted_at",
|
||||
"updated_at",
|
||||
"provider_type",
|
||||
"base_url",
|
||||
"is_active",
|
||||
"credentials",
|
||||
"url",
|
||||
]
|
||||
extra_kwargs = {
|
||||
"id": {"read_only": True},
|
||||
"inserted_at": {"read_only": True},
|
||||
"updated_at": {"read_only": True},
|
||||
"is_active": {"read_only": True},
|
||||
"url": {"read_only": True, "view_name": "lighthouse-providers-detail"},
|
||||
}
|
||||
|
||||
class JSONAPIMeta:
|
||||
resource_name = "lighthouse-providers"
|
||||
|
||||
def to_representation(self, instance):
|
||||
data = super().to_representation(instance)
|
||||
# Support JSON:API fields filter: fields[lighthouse-providers]=credentials,base_url
|
||||
fields_param = self.context.get("request", None) and self.context[
|
||||
"request"
|
||||
].query_params.get("fields[lighthouse-providers]", "")
|
||||
|
||||
creds = instance.credentials_decoded
|
||||
|
||||
requested_fields = (
|
||||
[f.strip() for f in fields_param.split(",")] if fields_param else []
|
||||
)
|
||||
|
||||
if "credentials" in requested_fields:
|
||||
# Return full decrypted credentials JSON
|
||||
data["credentials"] = creds
|
||||
else:
|
||||
# Return masked credentials by default
|
||||
def mask_value(value):
|
||||
if isinstance(value, str):
|
||||
return "*" * len(value)
|
||||
if isinstance(value, dict):
|
||||
return {k: mask_value(v) for k, v in value.items()}
|
||||
if isinstance(value, list):
|
||||
return [mask_value(v) for v in value]
|
||||
return value
|
||||
|
||||
# Always return masked credentials, even if creds is None
|
||||
if creds is not None:
|
||||
data["credentials"] = mask_value(creds)
|
||||
else:
|
||||
# If credentials_decoded returns None, return None for credentials field
|
||||
data["credentials"] = None
|
||||
|
||||
return data
|
||||
|
||||
|
||||
class LighthouseProviderConfigCreateSerializer(RLSSerializer, BaseWriteSerializer):
|
||||
"""
|
||||
Create serializer for LighthouseProviderConfiguration.
|
||||
Accepts credentials as JSON; stored encrypted via credentials_decoded.
|
||||
"""
|
||||
|
||||
credentials = serializers.JSONField(write_only=True, required=True)
|
||||
|
||||
class Meta:
|
||||
model = LighthouseProviderConfiguration
|
||||
fields = [
|
||||
"provider_type",
|
||||
"base_url",
|
||||
"credentials",
|
||||
"is_active",
|
||||
]
|
||||
extra_kwargs = {
|
||||
"is_active": {"required": False},
|
||||
"base_url": {"required": False, "allow_null": True},
|
||||
}
|
||||
|
||||
def create(self, validated_data):
|
||||
credentials = validated_data.pop("credentials")
|
||||
|
||||
instance = LighthouseProviderConfiguration(**validated_data)
|
||||
instance.tenant_id = self.context.get("tenant_id")
|
||||
instance.credentials_decoded = credentials
|
||||
|
||||
try:
|
||||
instance.save()
|
||||
return instance
|
||||
except IntegrityError:
|
||||
raise ValidationError(
|
||||
{
|
||||
"provider_type": "Configuration for this provider already exists for the tenant."
|
||||
}
|
||||
)
|
||||
|
||||
def validate(self, attrs):
|
||||
provider_type = attrs.get("provider_type")
|
||||
credentials = attrs.get("credentials") or {}
|
||||
|
||||
if provider_type == LighthouseProviderConfiguration.LLMProviderChoices.OPENAI:
|
||||
try:
|
||||
OpenAICredentialsSerializer(data=credentials).is_valid(
|
||||
raise_exception=True
|
||||
)
|
||||
except ValidationError as e:
|
||||
details = e.detail.copy()
|
||||
for key, value in details.items():
|
||||
e.detail[f"credentials/{key}"] = value
|
||||
del e.detail[key]
|
||||
raise e
|
||||
|
||||
return super().validate(attrs)
|
||||
|
||||
|
||||
class LighthouseProviderConfigUpdateSerializer(BaseWriteSerializer):
|
||||
"""
|
||||
Update serializer for LighthouseProviderConfiguration.
|
||||
"""
|
||||
|
||||
credentials = serializers.JSONField(write_only=True, required=False)
|
||||
|
||||
class Meta:
|
||||
model = LighthouseProviderConfiguration
|
||||
fields = [
|
||||
"id",
|
||||
"provider_type",
|
||||
"base_url",
|
||||
"credentials",
|
||||
"is_active",
|
||||
]
|
||||
extra_kwargs = {
|
||||
"id": {"read_only": True},
|
||||
"provider_type": {"read_only": True},
|
||||
"base_url": {"required": False, "allow_null": True},
|
||||
"is_active": {"required": False},
|
||||
}
|
||||
|
||||
def update(self, instance, validated_data):
|
||||
credentials = validated_data.pop("credentials", None)
|
||||
|
||||
for attr, value in validated_data.items():
|
||||
setattr(instance, attr, value)
|
||||
|
||||
if credentials is not None:
|
||||
instance.credentials_decoded = credentials
|
||||
|
||||
instance.save()
|
||||
return instance
|
||||
|
||||
def validate(self, attrs):
|
||||
provider_type = getattr(self.instance, "provider_type", None)
|
||||
credentials = attrs.get("credentials", None)
|
||||
|
||||
if (
|
||||
credentials is not None
|
||||
and provider_type
|
||||
== LighthouseProviderConfiguration.LLMProviderChoices.OPENAI
|
||||
):
|
||||
try:
|
||||
OpenAICredentialsSerializer(data=credentials).is_valid(
|
||||
raise_exception=True
|
||||
)
|
||||
except ValidationError as e:
|
||||
details = e.detail.copy()
|
||||
for key, value in details.items():
|
||||
e.detail[f"credentials/{key}"] = value
|
||||
del e.detail[key]
|
||||
raise e
|
||||
|
||||
return super().validate(attrs)
|
||||
|
||||
|
||||
# Lighthouse: Tenant configuration
|
||||
|
||||
|
||||
class LighthouseTenantConfigSerializer(RLSSerializer):
|
||||
"""
|
||||
Read serializer for LighthouseTenantConfiguration.
|
||||
"""
|
||||
|
||||
# Build singleton URL without pk
|
||||
url = serializers.SerializerMethodField()
|
||||
|
||||
def get_url(self, obj):
|
||||
request = self.context.get("request")
|
||||
return reverse("lighthouse-config", request=request)
|
||||
|
||||
class Meta:
|
||||
model = LighthouseTenantConfiguration
|
||||
fields = [
|
||||
"id",
|
||||
"inserted_at",
|
||||
"updated_at",
|
||||
"business_context",
|
||||
"default_provider",
|
||||
"default_models",
|
||||
"url",
|
||||
]
|
||||
extra_kwargs = {
|
||||
"id": {"read_only": True},
|
||||
"inserted_at": {"read_only": True},
|
||||
"updated_at": {"read_only": True},
|
||||
"url": {"read_only": True},
|
||||
}
|
||||
|
||||
|
||||
class LighthouseTenantConfigUpdateSerializer(BaseWriteSerializer):
|
||||
class Meta:
|
||||
model = LighthouseTenantConfiguration
|
||||
fields = [
|
||||
"id",
|
||||
"business_context",
|
||||
"default_provider",
|
||||
"default_models",
|
||||
]
|
||||
extra_kwargs = {
|
||||
"id": {"read_only": True},
|
||||
}
|
||||
|
||||
def validate(self, attrs):
|
||||
request = self.context.get("request")
|
||||
tenant_id = self.context.get("tenant_id") or (
|
||||
getattr(request, "tenant_id", None) if request else None
|
||||
)
|
||||
|
||||
default_provider = attrs.get(
|
||||
"default_provider", getattr(self.instance, "default_provider", "")
|
||||
)
|
||||
default_models = attrs.get(
|
||||
"default_models", getattr(self.instance, "default_models", {})
|
||||
)
|
||||
|
||||
if default_provider:
|
||||
supported = set(LighthouseProviderConfiguration.LLMProviderChoices.values)
|
||||
if default_provider not in supported:
|
||||
raise ValidationError(
|
||||
{"default_provider": f"Unsupported provider '{default_provider}'."}
|
||||
)
|
||||
if not LighthouseProviderConfiguration.objects.filter(
|
||||
tenant_id=tenant_id, provider_type=default_provider, is_active=True
|
||||
).exists():
|
||||
raise ValidationError(
|
||||
{
|
||||
"default_provider": f"No active configuration found for '{default_provider}'."
|
||||
}
|
||||
)
|
||||
|
||||
if default_models is not None and not isinstance(default_models, dict):
|
||||
raise ValidationError(
|
||||
{"default_models": "Must be an object mapping provider -> model_id."}
|
||||
)
|
||||
|
||||
for provider_type, model_id in (default_models or {}).items():
|
||||
provider_cfg = LighthouseProviderConfiguration.objects.filter(
|
||||
tenant_id=tenant_id, provider_type=provider_type, is_active=True
|
||||
).first()
|
||||
if not provider_cfg:
|
||||
raise ValidationError(
|
||||
{
|
||||
"default_models": f"No active configuration for provider '{provider_type}'."
|
||||
}
|
||||
)
|
||||
if not LighthouseProviderModels.objects.filter(
|
||||
tenant_id=tenant_id,
|
||||
provider_configuration=provider_cfg,
|
||||
model_id=model_id,
|
||||
).exists():
|
||||
raise ValidationError(
|
||||
{
|
||||
"default_models": f"Invalid model '{model_id}' for provider '{provider_type}'."
|
||||
}
|
||||
)
|
||||
|
||||
return super().validate(attrs)
|
||||
|
||||
|
||||
# Lighthouse: Provider models
|
||||
|
||||
|
||||
class LighthouseProviderModelsSerializer(RLSSerializer):
|
||||
"""
|
||||
Read serializer for LighthouseProviderModels.
|
||||
"""
|
||||
|
||||
provider_configuration = serializers.ResourceRelatedField(read_only=True)
|
||||
|
||||
class Meta:
|
||||
model = LighthouseProviderModels
|
||||
fields = [
|
||||
"id",
|
||||
"inserted_at",
|
||||
"updated_at",
|
||||
"provider_configuration",
|
||||
"model_id",
|
||||
"model_name",
|
||||
"default_parameters",
|
||||
"url",
|
||||
]
|
||||
extra_kwargs = {
|
||||
"id": {"read_only": True},
|
||||
"inserted_at": {"read_only": True},
|
||||
"updated_at": {"read_only": True},
|
||||
"url": {"read_only": True, "view_name": "lighthouse-models-detail"},
|
||||
}
|
||||
|
||||
|
||||
class LighthouseProviderModelsCreateSerializer(RLSSerializer, BaseWriteSerializer):
|
||||
provider_configuration = serializers.ResourceRelatedField(
|
||||
queryset=LighthouseProviderConfiguration.objects.all()
|
||||
)
|
||||
|
||||
class Meta:
|
||||
model = LighthouseProviderModels
|
||||
fields = [
|
||||
"provider_configuration",
|
||||
"model_id",
|
||||
"default_parameters",
|
||||
]
|
||||
extra_kwargs = {
|
||||
"default_parameters": {"required": False},
|
||||
}
|
||||
|
||||
|
||||
class LighthouseProviderModelsUpdateSerializer(BaseWriteSerializer):
|
||||
class Meta:
|
||||
model = LighthouseProviderModels
|
||||
fields = [
|
||||
"id",
|
||||
"default_parameters",
|
||||
]
|
||||
extra_kwargs = {
|
||||
"id": {"read_only": True},
|
||||
}
|
||||
|
||||
@@ -17,6 +17,9 @@ from api.v1.views import (
|
||||
InvitationAcceptViewSet,
|
||||
InvitationViewSet,
|
||||
LighthouseConfigViewSet,
|
||||
LighthouseProviderConfigViewSet,
|
||||
LighthouseProviderModelsViewSet,
|
||||
LighthouseTenantConfigViewSet,
|
||||
MembershipViewSet,
|
||||
OverviewViewSet,
|
||||
ProcessorViewSet,
|
||||
@@ -34,12 +37,12 @@ from api.v1.views import (
|
||||
ScheduleViewSet,
|
||||
SchemaView,
|
||||
TaskViewSet,
|
||||
TenantApiKeyViewSet,
|
||||
TenantFinishACSView,
|
||||
TenantMembersViewSet,
|
||||
TenantViewSet,
|
||||
UserRoleRelationshipView,
|
||||
UserViewSet,
|
||||
TenantApiKeyViewSet,
|
||||
)
|
||||
|
||||
router = routers.DefaultRouter(trailing_slash=False)
|
||||
@@ -67,6 +70,16 @@ router.register(
|
||||
basename="lighthouseconfiguration",
|
||||
)
|
||||
router.register(r"api-keys", TenantApiKeyViewSet, basename="api-key")
|
||||
router.register(
|
||||
r"lighthouse/providers",
|
||||
LighthouseProviderConfigViewSet,
|
||||
basename="lighthouse-providers",
|
||||
)
|
||||
router.register(
|
||||
r"lighthouse/models",
|
||||
LighthouseProviderModelsViewSet,
|
||||
basename="lighthouse-models",
|
||||
)
|
||||
|
||||
tenants_router = routers.NestedSimpleRouter(router, r"tenants", lookup="tenant")
|
||||
tenants_router.register(
|
||||
@@ -137,6 +150,14 @@ urlpatterns = [
|
||||
),
|
||||
name="provider_group-providers-relationship",
|
||||
),
|
||||
# Lighthouse tenant config as singleton endpoint
|
||||
path(
|
||||
"lighthouse/configuration",
|
||||
LighthouseTenantConfigViewSet.as_view(
|
||||
{"get": "list", "patch": "partial_update"}
|
||||
),
|
||||
name="lighthouse-config",
|
||||
),
|
||||
# API endpoint to start SAML SSO flow
|
||||
path(
|
||||
"auth/saml/initiate/", SAMLInitiateAPIView.as_view(), name="api_saml_initiate"
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import fnmatch
|
||||
import glob
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from datetime import datetime, timedelta, timezone
|
||||
@@ -59,11 +61,13 @@ from tasks.tasks import (
|
||||
backfill_scan_resource_summaries_task,
|
||||
check_integration_connection_task,
|
||||
check_lighthouse_connection_task,
|
||||
check_lighthouse_provider_connection_task,
|
||||
check_provider_connection_task,
|
||||
delete_provider_task,
|
||||
delete_tenant_task,
|
||||
jira_integration_task,
|
||||
perform_scan_task,
|
||||
refresh_lighthouse_provider_models_task,
|
||||
)
|
||||
|
||||
from api.base_views import BaseRLSViewSet, BaseTenantViewset, BaseUserViewset
|
||||
@@ -83,6 +87,8 @@ from api.filters import (
|
||||
InvitationFilter,
|
||||
LatestFindingFilter,
|
||||
LatestResourceFilter,
|
||||
LighthouseProviderConfigFilter,
|
||||
LighthouseProviderModelsFilter,
|
||||
MembershipFilter,
|
||||
ProcessorFilter,
|
||||
ProviderFilter,
|
||||
@@ -105,6 +111,9 @@ from api.models import (
|
||||
Integration,
|
||||
Invitation,
|
||||
LighthouseConfiguration,
|
||||
LighthouseProviderConfiguration,
|
||||
LighthouseProviderModels,
|
||||
LighthouseTenantConfiguration,
|
||||
Membership,
|
||||
Processor,
|
||||
Provider,
|
||||
@@ -159,6 +168,12 @@ from api.v1.serializers import (
|
||||
LighthouseConfigCreateSerializer,
|
||||
LighthouseConfigSerializer,
|
||||
LighthouseConfigUpdateSerializer,
|
||||
LighthouseProviderConfigCreateSerializer,
|
||||
LighthouseProviderConfigSerializer,
|
||||
LighthouseProviderConfigUpdateSerializer,
|
||||
LighthouseProviderModelsSerializer,
|
||||
LighthouseTenantConfigSerializer,
|
||||
LighthouseTenantConfigUpdateSerializer,
|
||||
MembershipSerializer,
|
||||
OverviewFindingSerializer,
|
||||
OverviewProviderSerializer,
|
||||
@@ -306,7 +321,7 @@ class SchemaView(SpectacularAPIView):
|
||||
|
||||
def get(self, request, *args, **kwargs):
|
||||
spectacular_settings.TITLE = "Prowler API"
|
||||
spectacular_settings.VERSION = "1.14.0"
|
||||
spectacular_settings.VERSION = "1.15.0"
|
||||
spectacular_settings.DESCRIPTION = (
|
||||
"Prowler API specification.\n\nThis file is auto-generated."
|
||||
)
|
||||
@@ -1775,7 +1790,18 @@ class ScanViewSet(BaseRLSViewSet):
|
||||
status=status.HTTP_502_BAD_GATEWAY,
|
||||
)
|
||||
contents = resp.get("Contents", [])
|
||||
keys = [obj["Key"] for obj in contents if obj["Key"].endswith(suffix)]
|
||||
keys = []
|
||||
for obj in contents:
|
||||
key = obj["Key"]
|
||||
key_basename = os.path.basename(key)
|
||||
if any(ch in suffix for ch in ("*", "?", "[")):
|
||||
if fnmatch.fnmatch(key_basename, suffix):
|
||||
keys.append(key)
|
||||
elif key_basename == suffix:
|
||||
keys.append(key)
|
||||
elif key.endswith(suffix):
|
||||
# Backward compatibility if suffix already includes directories
|
||||
keys.append(key)
|
||||
if not keys:
|
||||
return Response(
|
||||
{
|
||||
@@ -4165,21 +4191,25 @@ class IntegrationJiraViewSet(BaseRLSViewSet):
|
||||
tags=["Lighthouse AI"],
|
||||
summary="List all Lighthouse AI configurations",
|
||||
description="Retrieve a list of all Lighthouse AI configurations.",
|
||||
deprecated=True,
|
||||
),
|
||||
create=extend_schema(
|
||||
tags=["Lighthouse AI"],
|
||||
summary="Create a new Lighthouse AI configuration",
|
||||
description="Create a new Lighthouse AI configuration with the specified details.",
|
||||
deprecated=True,
|
||||
),
|
||||
partial_update=extend_schema(
|
||||
tags=["Lighthouse AI"],
|
||||
summary="Partially update a Lighthouse AI configuration",
|
||||
description="Update certain fields of an existing Lighthouse AI configuration.",
|
||||
deprecated=True,
|
||||
),
|
||||
destroy=extend_schema(
|
||||
tags=["Lighthouse AI"],
|
||||
summary="Delete a Lighthouse AI configuration",
|
||||
description="Remove a Lighthouse AI configuration by its ID.",
|
||||
deprecated=True,
|
||||
),
|
||||
connection=extend_schema(
|
||||
tags=["Lighthouse AI"],
|
||||
@@ -4187,6 +4217,7 @@ class IntegrationJiraViewSet(BaseRLSViewSet):
|
||||
description="Verify the connection to the OpenAI API for a specific Lighthouse AI configuration.",
|
||||
request=None,
|
||||
responses={202: OpenApiResponse(response=TaskSerializer)},
|
||||
deprecated=True,
|
||||
),
|
||||
)
|
||||
class LighthouseConfigViewSet(BaseRLSViewSet):
|
||||
@@ -4237,6 +4268,273 @@ class LighthouseConfigViewSet(BaseRLSViewSet):
|
||||
)
|
||||
|
||||
|
||||
@extend_schema_view(
|
||||
list=extend_schema(
|
||||
tags=["Lighthouse AI"],
|
||||
summary="List all LLM provider configs",
|
||||
description="Retrieve all LLM provider configurations for the current tenant",
|
||||
),
|
||||
retrieve=extend_schema(
|
||||
tags=["Lighthouse AI"],
|
||||
summary="Retrieve LLM provider config",
|
||||
description="Get details for a specific provider configuration in the current tenant.",
|
||||
),
|
||||
create=extend_schema(
|
||||
tags=["Lighthouse AI"],
|
||||
summary="Create LLM provider config",
|
||||
description="Create a per-tenant configuration for an LLM provider. Only one configuration per provider type is allowed per tenant.",
|
||||
),
|
||||
partial_update=extend_schema(
|
||||
tags=["Lighthouse AI"],
|
||||
summary="Update LLM provider config",
|
||||
description="Partially update a provider configuration (e.g., base_url, is_active).",
|
||||
),
|
||||
destroy=extend_schema(
|
||||
tags=["Lighthouse AI"],
|
||||
summary="Delete LLM provider config",
|
||||
description="Delete a provider configuration. Any tenant defaults that reference this provider are cleared during deletion.",
|
||||
),
|
||||
)
|
||||
class LighthouseProviderConfigViewSet(BaseRLSViewSet):
|
||||
queryset = LighthouseProviderConfiguration.objects.all()
|
||||
serializer_class = LighthouseProviderConfigSerializer
|
||||
http_method_names = ["get", "post", "patch", "delete"]
|
||||
filterset_class = LighthouseProviderConfigFilter
|
||||
|
||||
def get_queryset(self):
|
||||
if getattr(self, "swagger_fake_view", False):
|
||||
return LighthouseProviderConfiguration.objects.none()
|
||||
return LighthouseProviderConfiguration.objects.filter(
|
||||
tenant_id=self.request.tenant_id
|
||||
)
|
||||
|
||||
def get_serializer_class(self):
|
||||
if self.action == "create":
|
||||
return LighthouseProviderConfigCreateSerializer
|
||||
elif self.action == "partial_update":
|
||||
return LighthouseProviderConfigUpdateSerializer
|
||||
elif self.action in ["connection", "refresh_models"]:
|
||||
return TaskSerializer
|
||||
return super().get_serializer_class()
|
||||
|
||||
def create(self, request, *args, **kwargs):
|
||||
serializer = self.get_serializer(data=request.data)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
instance = serializer.save()
|
||||
|
||||
read_serializer = LighthouseProviderConfigSerializer(
|
||||
instance, context=self.get_serializer_context()
|
||||
)
|
||||
headers = self.get_success_headers(read_serializer.data)
|
||||
return Response(
|
||||
data=read_serializer.data,
|
||||
status=status.HTTP_201_CREATED,
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
def partial_update(self, request, *args, **kwargs):
|
||||
instance = self.get_object()
|
||||
serializer = self.get_serializer(
|
||||
instance,
|
||||
data=request.data,
|
||||
partial=True,
|
||||
context=self.get_serializer_context(),
|
||||
)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
serializer.save()
|
||||
read_serializer = LighthouseProviderConfigSerializer(
|
||||
instance, context=self.get_serializer_context()
|
||||
)
|
||||
return Response(data=read_serializer.data, status=status.HTTP_200_OK)
|
||||
|
||||
@extend_schema(
|
||||
tags=["Lighthouse AI"],
|
||||
summary="Check LLM provider connection",
|
||||
description="Validate provider credentials asynchronously and toggle is_active.",
|
||||
request=None,
|
||||
responses={202: OpenApiResponse(response=TaskSerializer)},
|
||||
)
|
||||
@action(detail=True, methods=["post"], url_name="connection")
|
||||
def connection(self, request, pk=None):
|
||||
instance = self.get_object()
|
||||
if (
|
||||
instance.provider_type
|
||||
!= LighthouseProviderConfiguration.LLMProviderChoices.OPENAI
|
||||
):
|
||||
return Response(
|
||||
data={
|
||||
"errors": [{"detail": "Only 'openai' provider supported in MVP"}]
|
||||
},
|
||||
status=status.HTTP_400_BAD_REQUEST,
|
||||
)
|
||||
|
||||
with transaction.atomic():
|
||||
task = check_lighthouse_provider_connection_task.delay(
|
||||
provider_config_id=str(instance.id), tenant_id=self.request.tenant_id
|
||||
)
|
||||
|
||||
prowler_task = Task.objects.get(id=task.id)
|
||||
serializer = TaskSerializer(prowler_task)
|
||||
return Response(
|
||||
data=serializer.data,
|
||||
status=status.HTTP_202_ACCEPTED,
|
||||
headers={
|
||||
"Content-Location": reverse(
|
||||
"task-detail", kwargs={"pk": prowler_task.id}
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
@extend_schema(
|
||||
tags=["Lighthouse AI"],
|
||||
summary="Refresh LLM models catalog",
|
||||
description="Fetch available models for this provider configuration and upsert into catalog.",
|
||||
request=None,
|
||||
responses={202: OpenApiResponse(response=TaskSerializer)},
|
||||
)
|
||||
@action(
|
||||
detail=True,
|
||||
methods=["post"],
|
||||
url_path="refresh-models",
|
||||
url_name="refresh-models",
|
||||
)
|
||||
def refresh_models(self, request, pk=None):
|
||||
instance = self.get_object()
|
||||
if (
|
||||
instance.provider_type
|
||||
!= LighthouseProviderConfiguration.LLMProviderChoices.OPENAI
|
||||
):
|
||||
return Response(
|
||||
data={
|
||||
"errors": [{"detail": "Only 'openai' provider supported in MVP"}]
|
||||
},
|
||||
status=status.HTTP_400_BAD_REQUEST,
|
||||
)
|
||||
|
||||
with transaction.atomic():
|
||||
task = refresh_lighthouse_provider_models_task.delay(
|
||||
provider_config_id=str(instance.id), tenant_id=self.request.tenant_id
|
||||
)
|
||||
|
||||
prowler_task = Task.objects.get(id=task.id)
|
||||
serializer = TaskSerializer(prowler_task)
|
||||
return Response(
|
||||
data=serializer.data,
|
||||
status=status.HTTP_202_ACCEPTED,
|
||||
headers={
|
||||
"Content-Location": reverse(
|
||||
"task-detail", kwargs={"pk": prowler_task.id}
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@extend_schema_view(
|
||||
list=extend_schema(
|
||||
tags=["Lighthouse AI"],
|
||||
summary="Get Lighthouse AI Tenant config",
|
||||
description="Retrieve current tenant-level Lighthouse AI settings. Returns a single configuration object.",
|
||||
),
|
||||
partial_update=extend_schema(
|
||||
tags=["Lighthouse AI"],
|
||||
summary="Update Lighthouse AI Tenant config",
|
||||
description="Update tenant-level settings. Validates that the default provider is configured and active and that default model IDs exist for the chosen providers. Auto-creates configuration if it doesn't exist.",
|
||||
),
|
||||
)
|
||||
class LighthouseTenantConfigViewSet(BaseRLSViewSet):
|
||||
"""
|
||||
Singleton endpoint for tenant-level Lighthouse AI configuration.
|
||||
|
||||
This viewset implements a true singleton pattern:
|
||||
- GET returns the single configuration object (or 404 if not found)
|
||||
- PATCH updates/creates the configuration (upsert semantics)
|
||||
- No ID is required in the URL
|
||||
"""
|
||||
|
||||
queryset = LighthouseTenantConfiguration.objects.all()
|
||||
serializer_class = LighthouseTenantConfigSerializer
|
||||
http_method_names = ["get", "patch"]
|
||||
|
||||
def get_queryset(self):
|
||||
if getattr(self, "swagger_fake_view", False):
|
||||
return LighthouseTenantConfiguration.objects.none()
|
||||
return LighthouseTenantConfiguration.objects.filter(
|
||||
tenant_id=self.request.tenant_id
|
||||
)
|
||||
|
||||
def get_serializer_class(self):
|
||||
if self.action == "partial_update":
|
||||
return LighthouseTenantConfigUpdateSerializer
|
||||
return super().get_serializer_class()
|
||||
|
||||
def get_object(self):
|
||||
"""Retrieve the singleton instance for the current tenant."""
|
||||
obj = LighthouseTenantConfiguration.objects.filter(
|
||||
tenant_id=self.request.tenant_id
|
||||
).first()
|
||||
if obj is None:
|
||||
raise NotFound("Tenant Lighthouse configuration not found")
|
||||
self.check_object_permissions(self.request, obj)
|
||||
return obj
|
||||
|
||||
def list(self, request, *args, **kwargs):
|
||||
"""GET endpoint for singleton - returns single object, not an array."""
|
||||
instance = self.get_object()
|
||||
serializer = self.get_serializer(instance)
|
||||
return Response(serializer.data)
|
||||
|
||||
def partial_update(self, request, *args, **kwargs):
|
||||
"""PATCH endpoint for singleton - no pk required. Auto-creates if not exists."""
|
||||
# Auto-create tenant config if it doesn't exist (upsert semantics)
|
||||
instance, created = LighthouseTenantConfiguration.objects.get_or_create(
|
||||
tenant_id=self.request.tenant_id,
|
||||
defaults={},
|
||||
)
|
||||
|
||||
# Extract attributes from JSON:API payload
|
||||
try:
|
||||
payload = json.loads(request.body)
|
||||
attributes = payload.get("data", {}).get("attributes", {})
|
||||
except (json.JSONDecodeError, AttributeError):
|
||||
raise ValidationError("Invalid JSON:API payload")
|
||||
|
||||
serializer = self.get_serializer(instance, data=attributes, partial=True)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
serializer.save()
|
||||
read_serializer = LighthouseTenantConfigSerializer(
|
||||
instance, context=self.get_serializer_context()
|
||||
)
|
||||
return Response(read_serializer.data, status=status.HTTP_200_OK)
|
||||
|
||||
|
||||
@extend_schema_view(
|
||||
list=extend_schema(
|
||||
tags=["Lighthouse AI"],
|
||||
summary="List all LLM models",
|
||||
description="List available LLM models per configured provider for the current tenant.",
|
||||
),
|
||||
retrieve=extend_schema(
|
||||
tags=["Lighthouse AI"],
|
||||
summary="Retrieve LLM model details",
|
||||
description="Get details for a specific LLM model.",
|
||||
),
|
||||
)
|
||||
class LighthouseProviderModelsViewSet(BaseRLSViewSet):
|
||||
queryset = LighthouseProviderModels.objects.all()
|
||||
serializer_class = LighthouseProviderModelsSerializer
|
||||
filterset_class = LighthouseProviderModelsFilter
|
||||
# Expose as read-only catalog collection
|
||||
http_method_names = ["get"]
|
||||
|
||||
def get_queryset(self):
|
||||
if getattr(self, "swagger_fake_view", False):
|
||||
return LighthouseProviderModels.objects.none()
|
||||
return LighthouseProviderModels.objects.filter(tenant_id=self.request.tenant_id)
|
||||
|
||||
def get_serializer_class(self):
|
||||
return super().get_serializer_class()
|
||||
|
||||
|
||||
@extend_schema_view(
|
||||
list=extend_schema(
|
||||
tags=["Processor"],
|
||||
|
||||
@@ -20,10 +20,10 @@ from prowler.lib.outputs.asff.asff import ASFF
|
||||
from prowler.lib.outputs.compliance.aws_well_architected.aws_well_architected import (
|
||||
AWSWellArchitected,
|
||||
)
|
||||
from prowler.lib.outputs.compliance.c5.c5_aws import AWSC5
|
||||
from prowler.lib.outputs.compliance.ccc.ccc_aws import CCC_AWS
|
||||
from prowler.lib.outputs.compliance.ccc.ccc_azure import CCC_Azure
|
||||
from prowler.lib.outputs.compliance.ccc.ccc_gcp import CCC_GCP
|
||||
from prowler.lib.outputs.compliance.c5.c5_aws import AWSC5
|
||||
from prowler.lib.outputs.compliance.cis.cis_aws import AWSCIS
|
||||
from prowler.lib.outputs.compliance.cis.cis_azure import AzureCIS
|
||||
from prowler.lib.outputs.compliance.cis.cis_gcp import GCPCIS
|
||||
@@ -183,18 +183,21 @@ def get_s3_client():
|
||||
return s3_client
|
||||
|
||||
|
||||
def _upload_to_s3(tenant_id: str, zip_path: str, scan_id: str) -> str | None:
|
||||
def _upload_to_s3(
|
||||
tenant_id: str, scan_id: str, local_path: str, relative_key: str
|
||||
) -> str | None:
|
||||
"""
|
||||
Upload the specified ZIP file to an S3 bucket.
|
||||
If the S3 bucket environment variables are not configured,
|
||||
the function returns None without performing an upload.
|
||||
Upload a local artifact to an S3 bucket under the tenant/scan prefix.
|
||||
|
||||
Args:
|
||||
tenant_id (str): The tenant identifier, used as part of the S3 key prefix.
|
||||
zip_path (str): The local file system path to the ZIP file to be uploaded.
|
||||
scan_id (str): The scan identifier, used as part of the S3 key prefix.
|
||||
tenant_id (str): The tenant identifier used as the first segment of the S3 key.
|
||||
scan_id (str): The scan identifier used as the second segment of the S3 key.
|
||||
local_path (str): Filesystem path to the artifact to upload.
|
||||
relative_key (str): Object key relative to `<tenant_id>/<scan_id>/`.
|
||||
|
||||
Returns:
|
||||
str: The S3 URI of the uploaded file (e.g., "s3://<bucket>/<key>") if successful.
|
||||
None: If the required environment variables for the S3 bucket are not set.
|
||||
str | None: S3 URI of the uploaded artifact, or None if the upload is skipped.
|
||||
|
||||
Raises:
|
||||
botocore.exceptions.ClientError: If the upload attempt to S3 fails for any reason.
|
||||
"""
|
||||
@@ -202,27 +205,19 @@ def _upload_to_s3(tenant_id: str, zip_path: str, scan_id: str) -> str | None:
|
||||
if not bucket:
|
||||
return
|
||||
|
||||
if not relative_key:
|
||||
return
|
||||
|
||||
if not os.path.isfile(local_path):
|
||||
return
|
||||
|
||||
try:
|
||||
s3 = get_s3_client()
|
||||
|
||||
# Upload the ZIP file (outputs) to the S3 bucket
|
||||
zip_key = f"{tenant_id}/{scan_id}/{os.path.basename(zip_path)}"
|
||||
s3.upload_file(
|
||||
Filename=zip_path,
|
||||
Bucket=bucket,
|
||||
Key=zip_key,
|
||||
)
|
||||
s3_key = f"{tenant_id}/{scan_id}/{relative_key}"
|
||||
s3.upload_file(Filename=local_path, Bucket=bucket, Key=s3_key)
|
||||
|
||||
# Upload the compliance directory to the S3 bucket
|
||||
compliance_dir = os.path.join(os.path.dirname(zip_path), "compliance")
|
||||
for filename in os.listdir(compliance_dir):
|
||||
local_path = os.path.join(compliance_dir, filename)
|
||||
if not os.path.isfile(local_path):
|
||||
continue
|
||||
file_key = f"{tenant_id}/{scan_id}/compliance/{filename}"
|
||||
s3.upload_file(Filename=local_path, Bucket=bucket, Key=file_key)
|
||||
|
||||
return f"s3://{base.DJANGO_OUTPUT_S3_AWS_OUTPUT_BUCKET}/{zip_key}"
|
||||
return f"s3://{base.DJANGO_OUTPUT_S3_AWS_OUTPUT_BUCKET}/{s3_key}"
|
||||
except (ClientError, NoCredentialsError, ParamValidationError, ValueError) as e:
|
||||
logger.error(f"S3 upload failed: {str(e)}")
|
||||
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
from typing import Dict, Set
|
||||
|
||||
import openai
|
||||
from celery.utils.log import get_task_logger
|
||||
|
||||
from api.models import LighthouseProviderConfiguration, LighthouseProviderModels
|
||||
|
||||
logger = get_task_logger(__name__)
|
||||
|
||||
|
||||
def _extract_openai_api_key(
|
||||
provider_cfg: LighthouseProviderConfiguration,
|
||||
) -> str | None:
|
||||
"""
|
||||
Safely extract the OpenAI API key from a provider configuration.
|
||||
|
||||
Args:
|
||||
provider_cfg (LighthouseProviderConfiguration): The provider configuration instance
|
||||
containing the credentials.
|
||||
|
||||
Returns:
|
||||
str | None: The API key string if present and valid, otherwise None.
|
||||
"""
|
||||
creds = provider_cfg.credentials_decoded
|
||||
if not isinstance(creds, dict):
|
||||
return None
|
||||
api_key = creds.get("api_key")
|
||||
if not isinstance(api_key, str) or not api_key:
|
||||
return None
|
||||
return api_key
|
||||
|
||||
|
||||
def check_lighthouse_provider_connection(provider_config_id: str) -> Dict:
|
||||
"""
|
||||
Validate a Lighthouse provider configuration by calling the provider API and
|
||||
toggle its active state accordingly.
|
||||
|
||||
Currently supports the OpenAI provider by invoking `models.list` to verify that
|
||||
the provided credentials are valid.
|
||||
|
||||
Args:
|
||||
provider_config_id (str): The primary key of the `LighthouseProviderConfiguration`
|
||||
to validate.
|
||||
|
||||
Returns:
|
||||
dict: A result dictionary with the following keys:
|
||||
- "connected" (bool): Whether the provider credentials are valid.
|
||||
- "error" (str | None): The error message when not connected, otherwise None.
|
||||
|
||||
Side Effects:
|
||||
- Updates and persists `is_active` on the `LighthouseProviderConfiguration`.
|
||||
|
||||
Raises:
|
||||
LighthouseProviderConfiguration.DoesNotExist: If no configuration exists with the given ID.
|
||||
"""
|
||||
provider_cfg = LighthouseProviderConfiguration.objects.get(pk=provider_config_id)
|
||||
|
||||
# TODO: Add support for other providers
|
||||
if (
|
||||
provider_cfg.provider_type
|
||||
!= LighthouseProviderConfiguration.LLMProviderChoices.OPENAI
|
||||
):
|
||||
return {"connected": False, "error": "Unsupported provider type"}
|
||||
|
||||
api_key = _extract_openai_api_key(provider_cfg)
|
||||
if not api_key:
|
||||
provider_cfg.is_active = False
|
||||
provider_cfg.save()
|
||||
return {"connected": False, "error": "API key is invalid or missing"}
|
||||
|
||||
try:
|
||||
client = openai.OpenAI(api_key=api_key)
|
||||
_ = client.models.list()
|
||||
provider_cfg.is_active = True
|
||||
provider_cfg.save()
|
||||
return {"connected": True, "error": None}
|
||||
except Exception as e:
|
||||
logger.warning("OpenAI connection check failed: %s", str(e))
|
||||
provider_cfg.is_active = False
|
||||
provider_cfg.save()
|
||||
return {"connected": False, "error": str(e)}
|
||||
|
||||
|
||||
def refresh_lighthouse_provider_models(provider_config_id: str) -> Dict:
|
||||
"""
|
||||
Refresh the catalog of models for a Lighthouse provider configuration.
|
||||
|
||||
For the OpenAI provider, this fetches the current list of models, upserts entries
|
||||
into `LighthouseProviderModels`, and deletes stale entries no longer returned by
|
||||
the provider.
|
||||
|
||||
Args:
|
||||
provider_config_id (str): The primary key of the `LighthouseProviderConfiguration`
|
||||
whose models should be refreshed.
|
||||
|
||||
Returns:
|
||||
dict: A result dictionary with the following keys on success:
|
||||
- "created" (int): Number of new model rows created.
|
||||
- "updated" (int): Number of existing model rows updated.
|
||||
- "deleted" (int): Number of stale model rows removed.
|
||||
If an error occurs, the dictionary will contain an "error" (str) field instead.
|
||||
|
||||
Raises:
|
||||
LighthouseProviderConfiguration.DoesNotExist: If no configuration exists with the given ID.
|
||||
"""
|
||||
provider_cfg = LighthouseProviderConfiguration.objects.get(pk=provider_config_id)
|
||||
|
||||
if (
|
||||
provider_cfg.provider_type
|
||||
!= LighthouseProviderConfiguration.LLMProviderChoices.OPENAI
|
||||
):
|
||||
return {
|
||||
"created": 0,
|
||||
"updated": 0,
|
||||
"deleted": 0,
|
||||
"error": "Unsupported provider type",
|
||||
}
|
||||
|
||||
api_key = _extract_openai_api_key(provider_cfg)
|
||||
if not api_key:
|
||||
return {
|
||||
"created": 0,
|
||||
"updated": 0,
|
||||
"deleted": 0,
|
||||
"error": "API key is invalid or missing",
|
||||
}
|
||||
|
||||
try:
|
||||
client = openai.OpenAI(api_key=api_key)
|
||||
models = client.models.list()
|
||||
fetched_ids: Set[str] = {m.id for m in getattr(models, "data", [])}
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("OpenAI models refresh failed: %s", str(e))
|
||||
return {"created": 0, "updated": 0, "deleted": 0, "error": str(e)}
|
||||
|
||||
created = 0
|
||||
updated = 0
|
||||
|
||||
for model_id in fetched_ids:
|
||||
obj, was_created = LighthouseProviderModels.objects.update_or_create(
|
||||
tenant_id=provider_cfg.tenant_id,
|
||||
provider_configuration=provider_cfg,
|
||||
model_id=model_id,
|
||||
defaults={
|
||||
"model_name": model_id, # OpenAI doesn't return a separate display name
|
||||
"default_parameters": {},
|
||||
},
|
||||
)
|
||||
if was_created:
|
||||
created += 1
|
||||
else:
|
||||
updated += 1
|
||||
|
||||
# Delete stale models not present anymore
|
||||
deleted, _ = (
|
||||
LighthouseProviderModels.objects.filter(
|
||||
tenant_id=provider_cfg.tenant_id, provider_configuration=provider_cfg
|
||||
)
|
||||
.exclude(model_id__in=fetched_ids)
|
||||
.delete()
|
||||
)
|
||||
|
||||
return {"created": created, "updated": updated, "deleted": deleted}
|
||||
@@ -1317,7 +1317,12 @@ def generate_threatscore_report_job(
|
||||
min_risk_level=4,
|
||||
)
|
||||
|
||||
upload_uri = _upload_to_s3(tenant_id, pdf_path, scan_id)
|
||||
upload_uri = _upload_to_s3(
|
||||
tenant_id,
|
||||
scan_id,
|
||||
pdf_path,
|
||||
f"threatscore/{Path(pdf_path).name}",
|
||||
)
|
||||
if upload_uri:
|
||||
try:
|
||||
rmtree(Path(pdf_path).parent, ignore_errors=True)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import os
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
from shutil import rmtree
|
||||
@@ -26,6 +27,10 @@ from tasks.jobs.integrations import (
|
||||
upload_s3_integration,
|
||||
upload_security_hub_integration,
|
||||
)
|
||||
from tasks.jobs.lighthouse_providers import (
|
||||
check_lighthouse_provider_connection,
|
||||
refresh_lighthouse_provider_models,
|
||||
)
|
||||
from tasks.jobs.report import generate_threatscore_report_job
|
||||
from tasks.jobs.scan import (
|
||||
aggregate_findings,
|
||||
@@ -413,7 +418,24 @@ def generate_outputs_task(scan_id: str, provider_id: str, tenant_id: str):
|
||||
writer._data.clear()
|
||||
|
||||
compressed = _compress_output_files(out_dir)
|
||||
upload_uri = _upload_to_s3(tenant_id, compressed, scan_id)
|
||||
|
||||
upload_uri = _upload_to_s3(
|
||||
tenant_id,
|
||||
scan_id,
|
||||
compressed,
|
||||
os.path.basename(compressed),
|
||||
)
|
||||
|
||||
compliance_dir_path = Path(comp_dir).parent
|
||||
if compliance_dir_path.exists():
|
||||
for artifact_path in sorted(compliance_dir_path.iterdir()):
|
||||
if artifact_path.is_file():
|
||||
_upload_to_s3(
|
||||
tenant_id,
|
||||
scan_id,
|
||||
str(artifact_path),
|
||||
f"compliance/{artifact_path.name}",
|
||||
)
|
||||
|
||||
# S3 integrations (need output_directory)
|
||||
with rls_transaction(tenant_id, using=READ_REPLICA_ALIAS):
|
||||
@@ -506,6 +528,24 @@ def check_lighthouse_connection_task(lighthouse_config_id: str, tenant_id: str =
|
||||
return check_lighthouse_connection(lighthouse_config_id=lighthouse_config_id)
|
||||
|
||||
|
||||
@shared_task(base=RLSTask, name="lighthouse-provider-connection-check")
|
||||
@set_tenant
|
||||
def check_lighthouse_provider_connection_task(
|
||||
provider_config_id: str, tenant_id: str | None = None
|
||||
) -> dict:
|
||||
"""Task wrapper to validate provider credentials and set is_active."""
|
||||
return check_lighthouse_provider_connection(provider_config_id=provider_config_id)
|
||||
|
||||
|
||||
@shared_task(base=RLSTask, name="lighthouse-provider-models-refresh")
|
||||
@set_tenant
|
||||
def refresh_lighthouse_provider_models_task(
|
||||
provider_config_id: str, tenant_id: str | None = None
|
||||
) -> dict:
|
||||
"""Task wrapper to refresh provider models catalog for the given configuration."""
|
||||
return refresh_lighthouse_provider_models(provider_config_id=provider_config_id)
|
||||
|
||||
|
||||
@shared_task(name="integration-check")
|
||||
def check_integrations_task(tenant_id: str, provider_id: str, scan_id: str = None):
|
||||
"""
|
||||
|
||||
@@ -72,17 +72,26 @@ class TestOutputs:
|
||||
client_mock = MagicMock()
|
||||
mock_get_client.return_value = client_mock
|
||||
|
||||
result = _upload_to_s3("tenant-id", str(zip_path), "scan-id")
|
||||
result = _upload_to_s3(
|
||||
"tenant-id",
|
||||
"scan-id",
|
||||
str(zip_path),
|
||||
"outputs.zip",
|
||||
)
|
||||
|
||||
expected_uri = "s3://test-bucket/tenant-id/scan-id/outputs.zip"
|
||||
assert result == expected_uri
|
||||
assert client_mock.upload_file.call_count == 2
|
||||
client_mock.upload_file.assert_called_once_with(
|
||||
Filename=str(zip_path),
|
||||
Bucket="test-bucket",
|
||||
Key="tenant-id/scan-id/outputs.zip",
|
||||
)
|
||||
|
||||
@patch("tasks.jobs.export.get_s3_client")
|
||||
@patch("tasks.jobs.export.base")
|
||||
def test_upload_to_s3_missing_bucket(self, mock_base, mock_get_client):
|
||||
mock_base.DJANGO_OUTPUT_S3_AWS_OUTPUT_BUCKET = ""
|
||||
result = _upload_to_s3("tenant", "/tmp/fake.zip", "scan")
|
||||
result = _upload_to_s3("tenant", "scan", "/tmp/fake.zip", "fake.zip")
|
||||
assert result is None
|
||||
|
||||
@patch("tasks.jobs.export.get_s3_client")
|
||||
@@ -101,11 +110,15 @@ class TestOutputs:
|
||||
client_mock = MagicMock()
|
||||
mock_get_client.return_value = client_mock
|
||||
|
||||
result = _upload_to_s3("tenant", str(zip_path), "scan")
|
||||
result = _upload_to_s3(
|
||||
"tenant",
|
||||
"scan",
|
||||
str(compliance_dir / "subdir"),
|
||||
"compliance/subdir",
|
||||
)
|
||||
|
||||
expected_uri = "s3://test-bucket/tenant/scan/results.zip"
|
||||
assert result == expected_uri
|
||||
client_mock.upload_file.assert_called_once()
|
||||
assert result is None
|
||||
client_mock.upload_file.assert_not_called()
|
||||
|
||||
@patch(
|
||||
"tasks.jobs.export.get_s3_client",
|
||||
@@ -126,7 +139,12 @@ class TestOutputs:
|
||||
compliance_dir.mkdir()
|
||||
(compliance_dir / "report.csv").write_text("csv")
|
||||
|
||||
_upload_to_s3("tenant", str(zip_path), "scan")
|
||||
_upload_to_s3(
|
||||
"tenant",
|
||||
"scan",
|
||||
str(zip_path),
|
||||
"zipfile.zip",
|
||||
)
|
||||
mock_logger.assert_called()
|
||||
|
||||
@patch("tasks.jobs.export.rls_transaction")
|
||||
|
||||
@@ -85,6 +85,12 @@ class TestGenerateThreatscoreReport:
|
||||
only_failed=True,
|
||||
min_risk_level=4,
|
||||
)
|
||||
mock_upload.assert_called_once_with(
|
||||
self.tenant_id,
|
||||
self.scan_id,
|
||||
"/tmp/threatscore_path_threatscore_report.pdf",
|
||||
"threatscore/threatscore_path_threatscore_report.pdf",
|
||||
)
|
||||
mock_rmtree.assert_called_once_with(
|
||||
Path("/tmp/threatscore_path_threatscore_report.pdf").parent,
|
||||
ignore_errors=True,
|
||||
|
||||
+3377
-95
File diff suppressed because it is too large
Load Diff
@@ -5,8 +5,7 @@ title: 'Prowler Services'
|
||||
Here you can find how to create a new service, or to complement an existing one, for a [Prowler Provider](/developer-guide/provider).
|
||||
|
||||
<Note>
|
||||
First ensure that the provider you want to add the service is already created. It can be checked [here](https://github.com/prowler-cloud/prowler/tree/master/prowler/providers). If the provider is not present, please refer to the [Provider](/developer-guide/provider) documentation to create it from scratch.
|
||||
|
||||
First ensure that the provider you want to add the service is already created. It can be checked [here](https://github.com/prowler-cloud/prowler/tree/master/prowler/providers). If the provider is not present, please refer to the [Provider](./provider.md) documentation to create it from scratch.
|
||||
</Note>
|
||||
## Introduction
|
||||
|
||||
@@ -201,11 +200,11 @@ class <Item>(BaseModel):
|
||||
|
||||
#### Service Attributes
|
||||
|
||||
*Optimized Data Storage with Python Dictionaries*
|
||||
_Optimized Data Storage with Python Dictionaries_
|
||||
|
||||
Each group of resources within a service should be structured as a Python [dictionary](https://docs.python.org/3/tutorial/datastructures.html#dictionaries) to enable efficient lookups. The dictionary lookup operation has [O(1) complexity](https://en.wikipedia.org/wiki/Big_O_notation#Orders_of_common_functions), and lookups are constantly executed.
|
||||
|
||||
*Assigning Unique Identifiers*
|
||||
_Assigning Unique Identifiers_
|
||||
|
||||
Each dictionary key must be a unique ID to identify the resource in a univocal way.
|
||||
|
||||
@@ -241,6 +240,301 @@ Provider-Specific Permissions Documentation:
|
||||
- [M365](/user-guide/providers/microsoft365/authentication#required-permissions)
|
||||
- [GitHub](/user-guide/providers/github/authentication)
|
||||
|
||||
## Service Architecture and Cross-Service Communication
|
||||
|
||||
### Core Principle: Service Isolation with Client Communication
|
||||
|
||||
Each service must contain **ONLY** the information unique to that specific service. When a check requires information from multiple services, it must use the **client objects** of other services rather than directly accessing their data structures.
|
||||
|
||||
This architecture ensures:
|
||||
|
||||
- **Loose coupling** between services
|
||||
- **Clear separation of concerns**
|
||||
- **Maintainable and testable code**
|
||||
- **Consistent data access patterns**
|
||||
|
||||
### Cross-Service Communication Pattern
|
||||
|
||||
Instead of services directly accessing each other's internal data, checks should import and use client objects:
|
||||
|
||||
**❌ INCORRECT - Direct data access:**
|
||||
|
||||
```python
|
||||
# DON'T DO THIS
|
||||
from prowler.providers.aws.services.cloudtrail.cloudtrail_service import cloudtrail_service
|
||||
from prowler.providers.aws.services.s3.s3_service import s3_service
|
||||
|
||||
class cloudtrail_bucket_requires_mfa_delete(Check):
|
||||
def execute(self):
|
||||
# WRONG: Directly accessing service data
|
||||
for trail in cloudtrail_service.trails.values():
|
||||
for bucket in s3_service.buckets.values():
|
||||
# Direct access violates separation of concerns
|
||||
```
|
||||
|
||||
**✅ CORRECT - Client-based communication:**
|
||||
|
||||
```python
|
||||
# DO THIS INSTEAD
|
||||
from prowler.providers.aws.services.cloudtrail.cloudtrail_client import cloudtrail_client
|
||||
from prowler.providers.aws.services.s3.s3_client import s3_client
|
||||
|
||||
class cloudtrail_bucket_requires_mfa_delete(Check):
|
||||
def execute(self):
|
||||
# CORRECT: Using client objects for cross-service communication
|
||||
for trail in cloudtrail_client.trails.values():
|
||||
trail_bucket = trail.s3_bucket
|
||||
for bucket in s3_client.buckets.values():
|
||||
if trail_bucket == bucket.name:
|
||||
# Use bucket properties through s3_client
|
||||
if bucket.mfa_delete:
|
||||
# Implementation logic
|
||||
```
|
||||
|
||||
### Real-World Example: CloudTrail + S3 Integration
|
||||
|
||||
This example demonstrates how CloudTrail checks validate S3 bucket configurations:
|
||||
|
||||
```python
|
||||
from prowler.lib.check.models import Check, Check_Report_AWS
|
||||
from prowler.providers.aws.services.cloudtrail.cloudtrail_client import cloudtrail_client
|
||||
from prowler.providers.aws.services.s3.s3_client import s3_client
|
||||
|
||||
class cloudtrail_bucket_requires_mfa_delete(Check):
|
||||
def execute(self):
|
||||
findings = []
|
||||
if cloudtrail_client.trails is not None:
|
||||
for trail in cloudtrail_client.trails.values():
|
||||
if trail.is_logging:
|
||||
trail_bucket_is_in_account = False
|
||||
trail_bucket = trail.s3_bucket
|
||||
|
||||
# Cross-service communication: CloudTrail check uses S3 client
|
||||
for bucket in s3_client.buckets.values():
|
||||
if trail_bucket == bucket.name:
|
||||
trail_bucket_is_in_account = True
|
||||
if bucket.mfa_delete:
|
||||
report.status = "PASS"
|
||||
report.status_extended = f"Trail {trail.name} bucket ({trail_bucket}) has MFA delete enabled."
|
||||
|
||||
# Handle cross-account scenarios
|
||||
if not trail_bucket_is_in_account:
|
||||
report.status = "MANUAL"
|
||||
report.status_extended = f"Trail {trail.name} bucket ({trail_bucket}) is a cross-account bucket or out of Prowler's audit scope, please check it manually."
|
||||
|
||||
findings.append(report)
|
||||
return findings
|
||||
```
|
||||
|
||||
**Key Benefits:**
|
||||
|
||||
- **CloudTrail service** only contains CloudTrail-specific data (trails, configurations)
|
||||
- **S3 service** only contains S3-specific data (buckets, policies, ACLs)
|
||||
- **Check logic** orchestrates between services using their public client interfaces
|
||||
- **Cross-account detection** is handled gracefully when resources span accounts
|
||||
|
||||
### Service Consolidation Guidelines
|
||||
|
||||
**When to combine services in the same file:**
|
||||
|
||||
Implement multiple services as **separate classes in the same file** when two services are **practically the same** or one is a **direct extension** of another.
|
||||
|
||||
**Example: S3 and S3Control**
|
||||
|
||||
S3Control is an extension of S3 that provides account-level controls and access points. Both are implemented in `s3_service.py`:
|
||||
|
||||
```python
|
||||
# File: prowler/providers/aws/services/s3/s3_service.py
|
||||
|
||||
class S3(AWSService):
|
||||
"""Standard S3 service for bucket operations"""
|
||||
def __init__(self, provider):
|
||||
super().__init__(__class__.__name__, provider)
|
||||
self.buckets = {}
|
||||
self.regions_with_buckets = []
|
||||
|
||||
# S3-specific initialization
|
||||
self._list_buckets(provider)
|
||||
self._get_bucket_versioning()
|
||||
# ... other S3-specific operations
|
||||
|
||||
class S3Control(AWSService):
|
||||
"""S3Control service for account-level and access point operations"""
|
||||
def __init__(self, provider):
|
||||
super().__init__(__class__.__name__, provider)
|
||||
self.account_public_access_block = None
|
||||
self.access_points = {}
|
||||
|
||||
# S3Control-specific initialization
|
||||
self._get_public_access_block()
|
||||
self._list_access_points()
|
||||
# ... other S3Control-specific operations
|
||||
```
|
||||
|
||||
**Separate client files:**
|
||||
|
||||
```python
|
||||
# File: prowler/providers/aws/services/s3/s3_client.py
|
||||
from prowler.providers.aws.services.s3.s3_service import S3
|
||||
s3_client = S3(Provider.get_global_provider())
|
||||
|
||||
# File: prowler/providers/aws/services/s3/s3control_client.py
|
||||
from prowler.providers.aws.services.s3.s3_service import S3Control
|
||||
s3control_client = S3Control(Provider.get_global_provider())
|
||||
```
|
||||
|
||||
**When NOT to consolidate services:**
|
||||
|
||||
Keep services separate when they:
|
||||
|
||||
- **Operate on different resource types** (EC2 vs RDS)
|
||||
- **Have different authentication mechanisms** (different API endpoints)
|
||||
- **Serve different operational domains** (IAM vs CloudTrail)
|
||||
- **Have different regional behaviors** (global vs regional services)
|
||||
|
||||
### Cross-Service Dependencies Guidelines
|
||||
|
||||
**1. Always use client imports:**
|
||||
|
||||
```python
|
||||
# Correct pattern
|
||||
from prowler.providers.aws.services.service_a.service_a_client import service_a_client
|
||||
from prowler.providers.aws.services.service_b.service_b_client import service_b_client
|
||||
```
|
||||
|
||||
**2. Handle missing resources gracefully:**
|
||||
|
||||
```python
|
||||
# Handle cross-service scenarios
|
||||
resource_found_in_account = False
|
||||
for external_resource in other_service_client.resources.values():
|
||||
if target_resource_id == external_resource.id:
|
||||
resource_found_in_account = True
|
||||
# Process found resource
|
||||
break
|
||||
|
||||
if not resource_found_in_account:
|
||||
# Handle cross-account or missing resource scenarios
|
||||
report.status = "MANUAL"
|
||||
report.status_extended = "Resource is cross-account or out of audit scope"
|
||||
```
|
||||
|
||||
**3. Document cross-service dependencies:**
|
||||
|
||||
```python
|
||||
class check_with_dependencies(Check):
|
||||
"""
|
||||
Check Description
|
||||
|
||||
Dependencies:
|
||||
- service_a_client: For primary resource information
|
||||
- service_b_client: For related resource validation
|
||||
- service_c_client: For policy analysis
|
||||
"""
|
||||
```
|
||||
|
||||
## Regional Service Implementation
|
||||
|
||||
When implementing services for regional providers (like AWS, Azure, GCP), special considerations are needed to handle resource discovery across multiple geographic locations. This section provides a complete guide using AWS as the reference example.
|
||||
|
||||
### Regional vs Non-Regional Services
|
||||
|
||||
**Regional Services:** Require iteration across multiple geographic locations where resources may exist (e.g., EC2 instances, VPC, RDS databases).
|
||||
|
||||
**Non-Regional/Global Services:** Operate at a global or tenant level without regional concepts (e.g., IAM users, Route53 hosted zones).
|
||||
|
||||
### AWS Regional Implementation Example
|
||||
|
||||
AWS is the perfect example of a regional provider. Here's how Prowler handles AWS's regional architecture:
|
||||
|
||||
|
||||
```python
|
||||
# File: prowler/providers/aws/services/ec2/ec2_service.py
|
||||
class EC2(AWSService):
|
||||
def __init__(self, provider):
|
||||
super().__init__(__class__.__name__, provider)
|
||||
self.instances = {}
|
||||
self.security_groups = {}
|
||||
|
||||
# Regional resource discovery across all AWS regions
|
||||
self.__threading_call__(self._describe_instances)
|
||||
self.__threading_call__(self._describe_security_groups)
|
||||
|
||||
def _describe_instances(self, regional_client):
|
||||
"""Discover EC2 instances in a specific region"""
|
||||
try:
|
||||
describe_instances_paginator = regional_client.get_paginator("describe_instances")
|
||||
for page in describe_instances_paginator.paginate():
|
||||
for reservation in page["Reservations"]:
|
||||
for instance in reservation["Instances"]:
|
||||
# Each instance includes its region
|
||||
self.instances[instance["InstanceId"]] = Instance(
|
||||
id=instance["InstanceId"],
|
||||
region=regional_client.region,
|
||||
state=instance["State"]["Name"],
|
||||
# ... other properties
|
||||
)
|
||||
except Exception as error:
|
||||
logger.error(f"Failed to describe instances in {regional_client.region}: {error}")
|
||||
```
|
||||
|
||||
#### Regional Check Execution
|
||||
|
||||
```python
|
||||
# File: prowler/providers/aws/services/ec2/ec2_instance_public_ip/ec2_instance_public_ip.py
|
||||
class ec2_instance_public_ip(Check):
|
||||
def execute(self):
|
||||
findings = []
|
||||
|
||||
# Automatically iterates across ALL AWS regions where instances exist
|
||||
for instance in ec2_client.instances.values():
|
||||
report = Check_Report_AWS(metadata=self.metadata(), resource=instance)
|
||||
report.region = instance.region # Critical: region attribution
|
||||
report.resource_arn = f"arn:aws:ec2:{instance.region}:{instance.account_id}:instance/{instance.id}"
|
||||
|
||||
if instance.public_ip:
|
||||
report.status = "FAIL"
|
||||
report.status_extended = f"Instance {instance.id} in {instance.region} has public IP {instance.public_ip}"
|
||||
else:
|
||||
report.status = "PASS"
|
||||
report.status_extended = f"Instance {instance.id} in {instance.region} does not have a public IP"
|
||||
|
||||
findings.append(report)
|
||||
|
||||
return findings
|
||||
```
|
||||
|
||||
#### Key AWS Regional Features
|
||||
|
||||
**Region-Specific ARNs:**
|
||||
|
||||
```
|
||||
arn:aws:ec2:us-east-1:123456789012:instance/i-1234567890abcdef0
|
||||
arn:aws:s3:eu-west-1:123456789012:bucket/my-bucket
|
||||
arn:aws:rds:ap-southeast-2:123456789012:db:my-database
|
||||
```
|
||||
|
||||
**Parallel Processing:**
|
||||
|
||||
- Each region processed independently in separate threads
|
||||
- Failed regions don't affect other regions
|
||||
- User can filter specific regions: `-f us-east-1`
|
||||
|
||||
**Global vs Regional Services:**
|
||||
|
||||
- **Regional**: EC2, RDS, VPC (require region iteration)
|
||||
- **Global**: IAM, Route53, CloudFront (single `us-east-1` call)
|
||||
|
||||
This architecture allows Prowler to efficiently scan AWS accounts with resources spread across multiple regions while maintaining performance and error isolation.
|
||||
|
||||
### Regional Service Best Practices
|
||||
|
||||
1. **Use Threading for Regional Discovery**: Leverage the `__threading_call__` method to parallelize resource discovery across regions
|
||||
2. **Store Region Information**: Always include region metadata in resource objects for proper attribution
|
||||
3. **Handle Regional Failures Gracefully**: Ensure that failures in one region don't affect others
|
||||
4. **Optimize for Performance**: Use paginated calls and efficient data structures for large-scale resource discovery
|
||||
5. **Support Region Filtering**: Allow users to limit scans to specific regions for focused audits
|
||||
|
||||
## Best Practices
|
||||
|
||||
- When available in the provider, use threading or parallelization utilities for all methods that can be parallelized by to maximize performance and reduce scan time.
|
||||
@@ -252,3 +546,5 @@ Provider-Specific Permissions Documentation:
|
||||
- Collect and store resource tags and additional attributes to support richer checks and reporting.
|
||||
- Leverage shared utility helpers for session setup, identifier parsing, and other cross-cutting concerns to avoid code duplication. This kind of code is typically stored in a `lib` folder in the service folder.
|
||||
- Keep code modular, maintainable, and well-documented for ease of extension and troubleshooting.
|
||||
- **Each service should contain only information unique to that specific service** - use client objects for cross-service communication.
|
||||
- **Handle cross-account and missing resources gracefully** when checks span multiple services.
|
||||
|
||||
+22
-2
@@ -98,7 +98,7 @@
|
||||
]
|
||||
},
|
||||
"user-guide/tutorials/prowler-app-rbac",
|
||||
"user-guide/providers/prowler-app-api-keys",
|
||||
"user-guide/tutorials/prowler-app-api-keys",
|
||||
"user-guide/tutorials/prowler-app-mute-findings",
|
||||
{
|
||||
"group": "Integrations",
|
||||
@@ -114,7 +114,8 @@
|
||||
"group": "Tutorials",
|
||||
"pages": [
|
||||
"user-guide/tutorials/prowler-app-sso-entra",
|
||||
"user-guide/tutorials/bulk-provider-provisioning"
|
||||
"user-guide/tutorials/bulk-provider-provisioning",
|
||||
"user-guide/tutorials/aws-organizations-bulk-provisioning"
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -250,6 +251,25 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tab": "Workshop",
|
||||
"groups": [
|
||||
{
|
||||
"group": "Hands-On Labs",
|
||||
"pages": [
|
||||
"workshop/introduction",
|
||||
"workshop/lab-01-getting-started",
|
||||
"workshop/lab-02-threat-detection",
|
||||
"workshop/lab-03-custom-checks",
|
||||
"workshop/lab-04-azure-multicloud",
|
||||
"workshop/lab-05-gcp-multicloud",
|
||||
"workshop/lab-06-compliance-as-code",
|
||||
"workshop/lab-07-integrations",
|
||||
"workshop/lab-08-prowler-saas"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tab": "Developer Guide",
|
||||
"groups": [
|
||||
|
||||
@@ -10,7 +10,7 @@ Configure your MCP client to connect to Prowler MCP Server.
|
||||
**Authentication is optional**: Prowler Hub and Prowler Documentation features work without authentication. An API key is only required for Prowler Cloud and Prowler App (Self-Managed) features.
|
||||
</Note>
|
||||
|
||||
To use Prowler Cloud or Prowler App (Self-Managed) features. To get the API key, please refer to the [API Keys](/user-guide/providers/prowler-app-api-keys) guide.
|
||||
To use Prowler Cloud or Prowler App (Self-Managed) features. To get the API key, please refer to the [API Keys](/user-guide/tutorials/prowler-app-api-keys) guide.
|
||||
|
||||
<Warning>
|
||||
Keep the API key secure. Never share it publicly or commit it to version control.
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 71 KiB |
@@ -0,0 +1,12 @@
|
||||
export const VersionBadge = ({ version }) => {
|
||||
return (
|
||||
<code className="version-badge-container">
|
||||
<p className="version-badge">
|
||||
<span className="version-badge-label">Added in:</span>
|
||||
<code className="version-badge-version">{version}</code>
|
||||
</p>
|
||||
</code>
|
||||
|
||||
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,51 @@
|
||||
/* Version Badge Styling */
|
||||
.version-badge-container {
|
||||
display: inline-block;
|
||||
margin: 0 0 1rem 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.version-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
margin: 0;
|
||||
padding: 0.375rem 0.75rem;
|
||||
background: linear-gradient(135deg, #1a1a1a 0%, #000000 100%);
|
||||
color: #ffffff;
|
||||
border-radius: 1.25rem;
|
||||
font-weight: 400;
|
||||
font-size: 0.875rem;
|
||||
line-height: 1.25rem;
|
||||
border: 1px solid rgba(0, 0, 0, 0.15);
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.version-badge-label {
|
||||
font-weight: 400;
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.version-badge-version {
|
||||
background: rgba(255, 255, 255, 0.12);
|
||||
padding: 0.125rem 0.5rem;
|
||||
border-radius: 0.875rem;
|
||||
font-family: ui-monospace, SFMono-Regular, 'SF Mono', Menlo, Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace;
|
||||
font-weight: 600;
|
||||
font-size: 0.875rem;
|
||||
color: #ffffff;
|
||||
border: none;
|
||||
}
|
||||
|
||||
|
||||
.dark .version-badge {
|
||||
background: #55B685;
|
||||
color: #000000;
|
||||
border: 2px solid rgba(85, 182, 133, 0.3);
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.dark .version-badge-version {
|
||||
background: rgba(0, 0, 0, 0.1);
|
||||
color: #000000;
|
||||
border: none;
|
||||
}
|
||||
@@ -0,0 +1,491 @@
|
||||
---
|
||||
title: 'AWS Organizations Bulk Provisioning in Prowler'
|
||||
---
|
||||
|
||||
Prowler offers an automated tool to discover and provision all AWS accounts within an AWS Organization. This streamlines onboarding for organizations managing multiple AWS accounts by automatically generating the configuration needed for bulk provisioning.
|
||||
|
||||
The tool, `aws_org_generator.py`, complements the [Bulk Provider Provisioning](./bulk-provider-provisioning) tool and is available in the Prowler repository at: [util/prowler-bulk-provisioning](https://github.com/prowler-cloud/prowler/tree/master/util/prowler-bulk-provisioning)
|
||||
|
||||
<Note>
|
||||
Native support for bulk provisioning AWS Organizations and similar multi-account structures directly in the Prowler UI/API is on the official roadmap.
|
||||
|
||||
Track progress and vote for this feature at: [Bulk Provisioning in the UI/API for AWS Organizations](https://roadmap.prowler.com/p/builk-provisioning-in-the-uiapi-for-aws-organizations-and-alike)
|
||||
</Note>
|
||||
|
||||
{/* TODO: Add screenshot of the tool in action */}
|
||||
|
||||
## Overview
|
||||
|
||||
The AWS Organizations Bulk Provisioning tool simplifies multi-account onboarding by:
|
||||
|
||||
* Automatically discovering all active accounts in an AWS Organization
|
||||
* Generating YAML configuration files for bulk provisioning
|
||||
* Supporting account filtering and custom role configurations
|
||||
* Eliminating manual entry of account IDs and role ARNs
|
||||
|
||||
## Prerequisites
|
||||
|
||||
### Requirements
|
||||
|
||||
* Python 3.7 or higher
|
||||
* AWS credentials with Organizations read access
|
||||
* ProwlerRole (or custom role) deployed across all target accounts
|
||||
* Prowler API key (from Prowler Cloud or self-hosted Prowler App)
|
||||
* For self-hosted Prowler App, remember to [point to your API base URL](./bulk-provider-provisioning#custom-api-endpoints)
|
||||
* Learn how to create API keys: [Prowler App API Keys](../tutorials/prowler-app-api-keys)
|
||||
|
||||
### Deploying ProwlerRole Across AWS Organizations
|
||||
|
||||
Before using the AWS Organizations generator, deploy the ProwlerRole across all accounts in the organization using CloudFormation StackSets.
|
||||
|
||||
<Note>
|
||||
**Follow the official documentation:**
|
||||
[Deploying Prowler IAM Roles Across AWS Organizations](../providers/aws/organizations#deploying-prowler-iam-roles-across-aws-organizations)
|
||||
|
||||
**Key points:**
|
||||
|
||||
* Use CloudFormation StackSets from the management account
|
||||
* Deploy to all organizational units (OUs) or specific OUs
|
||||
* Use an external ID for enhanced security
|
||||
* Ensure the role has necessary permissions for Prowler scans
|
||||
</Note>
|
||||
|
||||
### Installation
|
||||
|
||||
Clone the repository and install required dependencies:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/prowler-cloud/prowler.git
|
||||
cd prowler/util/prowler-bulk-provisioning
|
||||
pip install -r requirements-aws-org.txt
|
||||
```
|
||||
|
||||
### AWS Credentials Setup
|
||||
|
||||
Configure AWS credentials with Organizations read access:
|
||||
|
||||
* **Management account credentials**, or
|
||||
* **Delegated administrator account** with `organizations:ListAccounts` permission
|
||||
|
||||
Required IAM permissions:
|
||||
|
||||
```json
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"organizations:ListAccounts",
|
||||
"organizations:DescribeOrganization"
|
||||
],
|
||||
"Resource": "*"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Prowler API Key Setup
|
||||
|
||||
Configure your Prowler API key:
|
||||
|
||||
```bash
|
||||
export PROWLER_API_KEY="pk_example-api-key"
|
||||
```
|
||||
|
||||
To create an API key:
|
||||
|
||||
1. Log in to Prowler Cloud or Prowler App
|
||||
2. Click **Profile** → **Account**
|
||||
3. Click **Create API Key**
|
||||
4. Provide a descriptive name and optionally set an expiration date
|
||||
5. Copy the generated API key (it will only be shown once)
|
||||
|
||||
For detailed instructions, see: [Prowler App API Keys](../tutorials/prowler-app-api-keys)
|
||||
|
||||
## Basic Usage
|
||||
|
||||
### Generate Configuration for All Accounts
|
||||
|
||||
To generate a YAML configuration file for all active accounts in the organization:
|
||||
|
||||
```bash
|
||||
python aws_org_generator.py -o aws-accounts.yaml --external-id prowler-ext-id-2024
|
||||
```
|
||||
|
||||
This command:
|
||||
|
||||
1. Lists all ACTIVE accounts in the organization
|
||||
2. Generates YAML entries for each account
|
||||
3. Saves the configuration to `aws-accounts.yaml`
|
||||
|
||||
**Output:**
|
||||
|
||||
```
|
||||
Fetching accounts from AWS Organizations...
|
||||
Found 47 active accounts in organization
|
||||
Generated configuration for 47 accounts
|
||||
|
||||
Configuration written to: aws-accounts.yaml
|
||||
|
||||
Next steps:
|
||||
1. Review the generated file: cat aws-accounts.yaml | head -n 20
|
||||
2. Run bulk provisioning: python prowler_bulk_provisioning.py aws-accounts.yaml
|
||||
```
|
||||
|
||||
### Review Generated Configuration
|
||||
|
||||
Review the generated YAML configuration:
|
||||
|
||||
```bash
|
||||
head -n 20 aws-accounts.yaml
|
||||
```
|
||||
|
||||
**Example output:**
|
||||
|
||||
```yaml
|
||||
- provider: aws
|
||||
uid: '111111111111'
|
||||
alias: Production-Account
|
||||
auth_method: role
|
||||
credentials:
|
||||
role_arn: arn:aws:iam::111111111111:role/ProwlerRole
|
||||
external_id: prowler-ext-id-2024
|
||||
|
||||
- provider: aws
|
||||
uid: '222222222222'
|
||||
alias: Development-Account
|
||||
auth_method: role
|
||||
credentials:
|
||||
role_arn: arn:aws:iam::222222222222:role/ProwlerRole
|
||||
external_id: prowler-ext-id-2024
|
||||
```
|
||||
|
||||
### Dry Run Mode
|
||||
|
||||
Test the configuration without writing a file:
|
||||
|
||||
```bash
|
||||
python aws_org_generator.py \
|
||||
--external-id prowler-ext-id-2024 \
|
||||
--dry-run
|
||||
```
|
||||
|
||||
## Advanced Configuration
|
||||
|
||||
### Using a Specific AWS Profile
|
||||
|
||||
Specify an AWS profile when multiple profiles are configured:
|
||||
|
||||
```bash
|
||||
python aws_org_generator.py \
|
||||
-o aws-accounts.yaml \
|
||||
--profile org-management-admin \
|
||||
--external-id prowler-ext-id-2024
|
||||
```
|
||||
|
||||
### Excluding Specific Accounts
|
||||
|
||||
Exclude the management account or other accounts from provisioning:
|
||||
|
||||
```bash
|
||||
python aws_org_generator.py \
|
||||
-o aws-accounts.yaml \
|
||||
--external-id prowler-ext-id-2024 \
|
||||
--exclude 123456789012,210987654321
|
||||
```
|
||||
|
||||
Common exclusion scenarios:
|
||||
|
||||
* Management account (requires different permissions)
|
||||
* Break-glass accounts (emergency access)
|
||||
* Suspended or archived accounts
|
||||
|
||||
### Including Only Specific Accounts
|
||||
|
||||
Generate configuration for specific accounts only:
|
||||
|
||||
```bash
|
||||
python aws_org_generator.py \
|
||||
-o aws-accounts.yaml \
|
||||
--external-id prowler-ext-id-2024 \
|
||||
--include 111111111111,222222222222,333333333333
|
||||
```
|
||||
|
||||
### Custom Role Name
|
||||
|
||||
Specify a custom role name if not using the default `ProwlerRole`:
|
||||
|
||||
```bash
|
||||
python aws_org_generator.py \
|
||||
-o aws-accounts.yaml \
|
||||
--role-name ProwlerExecutionRole \
|
||||
--external-id prowler-ext-id-2024
|
||||
```
|
||||
|
||||
### Custom Alias Format
|
||||
|
||||
Customize account aliases using template variables:
|
||||
|
||||
```bash
|
||||
# Use account name and ID
|
||||
python aws_org_generator.py \
|
||||
-o aws-accounts.yaml \
|
||||
--alias-format "{name}-{id}" \
|
||||
--external-id prowler-ext-id-2024
|
||||
|
||||
# Use email prefix
|
||||
python aws_org_generator.py \
|
||||
-o aws-accounts.yaml \
|
||||
--alias-format "{email}" \
|
||||
--external-id prowler-ext-id-2024
|
||||
```
|
||||
|
||||
Available template variables:
|
||||
|
||||
* `{name}` - Account name
|
||||
* `{id}` - Account ID
|
||||
* `{email}` - Account email
|
||||
|
||||
### Additional Role Assumption Options
|
||||
|
||||
Configure optional role assumption parameters:
|
||||
|
||||
```bash
|
||||
python aws_org_generator.py \
|
||||
-o aws-accounts.yaml \
|
||||
--role-name ProwlerRole \
|
||||
--external-id prowler-ext-id-2024 \
|
||||
--session-name prowler-scan-session \
|
||||
--duration-seconds 3600
|
||||
```
|
||||
|
||||
## Complete Workflow Example
|
||||
|
||||
<Steps>
|
||||
<Step title="Deploy ProwlerRole Using StackSets">
|
||||
1. Log in to the AWS management account
|
||||
2. Open CloudFormation → StackSets
|
||||
3. Create a new StackSet using the [Prowler role template](https://github.com/prowler-cloud/prowler/blob/master/permissions/templates/cloudformation/prowler-scan-role.yml)
|
||||
4. Deploy to all organizational units
|
||||
5. Use a unique external ID (e.g., `prowler-org-2024-abc123`)
|
||||
|
||||
{/* TODO: Add screenshot of CloudFormation StackSets deployment */}
|
||||
</Step>
|
||||
|
||||
<Step title="Generate YAML Configuration">
|
||||
Configure AWS credentials and generate the YAML file:
|
||||
|
||||
```bash
|
||||
# Using management account credentials
|
||||
export AWS_PROFILE=org-management
|
||||
|
||||
# Generate configuration
|
||||
python aws_org_generator.py \
|
||||
-o aws-org-accounts.yaml \
|
||||
--external-id prowler-org-2024-abc123 \
|
||||
--exclude 123456789012
|
||||
```
|
||||
|
||||
**Output:**
|
||||
|
||||
```
|
||||
Fetching accounts from AWS Organizations...
|
||||
Using AWS profile: org-management
|
||||
Found 47 active accounts in organization
|
||||
Generated configuration for 46 accounts
|
||||
|
||||
Configuration written to: aws-org-accounts.yaml
|
||||
|
||||
Next steps:
|
||||
1. Review the generated file: cat aws-org-accounts.yaml | head -n 20
|
||||
2. Run bulk provisioning: python prowler_bulk_provisioning.py aws-org-accounts.yaml
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Review Generated Configuration">
|
||||
Verify the generated YAML configuration:
|
||||
|
||||
```bash
|
||||
# View first 20 lines
|
||||
head -n 20 aws-org-accounts.yaml
|
||||
|
||||
# Check for unexpected accounts
|
||||
grep "uid:" aws-org-accounts.yaml
|
||||
|
||||
# Verify role ARNs
|
||||
grep "role_arn:" aws-org-accounts.yaml | head -5
|
||||
|
||||
# Count accounts
|
||||
grep "provider: aws" aws-org-accounts.yaml | wc -l
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Run Bulk Provisioning">
|
||||
Provision all accounts to Prowler Cloud or Prowler App:
|
||||
|
||||
```bash
|
||||
# Set Prowler API key
|
||||
export PROWLER_API_KEY="pk_example-api-key"
|
||||
|
||||
# Run bulk provisioning with connection testing
|
||||
python prowler_bulk_provisioning.py aws-org-accounts.yaml
|
||||
```
|
||||
|
||||
**With custom options:**
|
||||
|
||||
```bash
|
||||
python prowler_bulk_provisioning.py aws-org-accounts.yaml \
|
||||
--concurrency 10 \
|
||||
--timeout 120
|
||||
```
|
||||
|
||||
**Successful output:**
|
||||
|
||||
```
|
||||
[1] ✅ Created provider (id=db9a8985-f9ec-4dd8-b5a0-e05ab3880bed)
|
||||
[1] ✅ Created secret (id=466f76c6-5878-4602-a4bc-13f9522c1fd2)
|
||||
[1] ✅ Connection test: Connected
|
||||
|
||||
[2] ✅ Created provider (id=7a99f789-0cf5-4329-8279-2d443a962676)
|
||||
[2] ✅ Created secret (id=c5702180-f7c4-40fd-be0e-f6433479b126)
|
||||
[2] ✅ Connection test: Connected
|
||||
|
||||
Done. Success: 47 Failures: 0
|
||||
```
|
||||
|
||||
{/* TODO: Add screenshot of successful bulk provisioning output */}
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Command Reference
|
||||
|
||||
### Full Command-Line Options
|
||||
|
||||
```bash
|
||||
python aws_org_generator.py \
|
||||
-o OUTPUT_FILE \
|
||||
--role-name ROLE_NAME \
|
||||
--external-id EXTERNAL_ID \
|
||||
--session-name SESSION_NAME \
|
||||
--duration-seconds SECONDS \
|
||||
--alias-format FORMAT \
|
||||
--exclude ACCOUNT_IDS \
|
||||
--include ACCOUNT_IDS \
|
||||
--profile AWS_PROFILE \
|
||||
--region AWS_REGION \
|
||||
--dry-run
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Error: "No AWS credentials found"
|
||||
|
||||
**Solution:** Configure AWS credentials using one of these methods:
|
||||
|
||||
```bash
|
||||
# Method 1: AWS CLI configure
|
||||
aws configure
|
||||
|
||||
# Method 2: Environment variables
|
||||
export AWS_ACCESS_KEY_ID=your-key-id
|
||||
export AWS_SECRET_ACCESS_KEY=your-secret-key
|
||||
|
||||
# Method 3: Use AWS profile
|
||||
export AWS_PROFILE=org-management
|
||||
```
|
||||
|
||||
### Error: "Access denied to AWS Organizations API"
|
||||
|
||||
**Cause:** Current credentials don't have permission to list organization accounts.
|
||||
|
||||
**Solution:**
|
||||
|
||||
* Ensure management account credentials are used
|
||||
* Verify IAM permissions include `organizations:ListAccounts`
|
||||
* Check IAM policies for Organizations access
|
||||
|
||||
### Error: "AWS Organizations is not enabled"
|
||||
|
||||
**Cause:** The account is not part of an organization.
|
||||
|
||||
**Solution:** This tool requires an AWS Organization. Create one in the AWS Organizations console or use standard bulk provisioning for standalone accounts.
|
||||
|
||||
### No Accounts Generated After Filters
|
||||
|
||||
**Cause:** All accounts were filtered out by `--exclude` or `--include` options.
|
||||
|
||||
**Solution:** Review filter options and verify account IDs are correct:
|
||||
|
||||
```bash
|
||||
# List all accounts in organization
|
||||
aws organizations list-accounts --query "Accounts[?Status=='ACTIVE'].[Id,Name]" --output table
|
||||
```
|
||||
|
||||
### Connection Test Failures During Bulk Provisioning
|
||||
|
||||
**Cause:** ProwlerRole may not be deployed correctly or credentials are invalid.
|
||||
|
||||
**Solution:**
|
||||
|
||||
* Verify StackSet deployment status in CloudFormation
|
||||
* Check role trust policy includes correct external ID
|
||||
* Test role assumption manually:
|
||||
|
||||
```bash
|
||||
aws sts assume-role \
|
||||
--role-arn arn:aws:iam::123456789012:role/ProwlerRole \
|
||||
--role-session-name test \
|
||||
--external-id prowler-ext-id-2024
|
||||
```
|
||||
|
||||
## Security Best Practices
|
||||
|
||||
### Use External ID
|
||||
|
||||
Always use an external ID when assuming cross-account roles:
|
||||
|
||||
```bash
|
||||
python aws_org_generator.py \
|
||||
-o aws-accounts.yaml \
|
||||
--external-id $(uuidgen | tr '[:upper:]' '[:lower:]')
|
||||
```
|
||||
|
||||
The external ID must match the one configured in the ProwlerRole trust policy across all accounts.
|
||||
|
||||
### Exclude Sensitive Accounts
|
||||
|
||||
Exclude accounts that shouldn't be scanned or require special handling:
|
||||
|
||||
```bash
|
||||
python aws_org_generator.py \
|
||||
-o aws-accounts.yaml \
|
||||
--external-id prowler-ext-id \
|
||||
--exclude 123456789012,111111111111 # management, break-glass accounts
|
||||
```
|
||||
|
||||
### Review Generated Configuration
|
||||
|
||||
Always review the generated YAML before provisioning:
|
||||
|
||||
```bash
|
||||
# Check for unexpected accounts
|
||||
grep "uid:" aws-org-accounts.yaml
|
||||
|
||||
# Verify role ARNs
|
||||
grep "role_arn:" aws-org-accounts.yaml | head -5
|
||||
|
||||
# Count accounts
|
||||
grep "provider: aws" aws-org-accounts.yaml | wc -l
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
<Columns cols={2}>
|
||||
<Card title="Bulk Provider Provisioning" icon="terminal" href="/user-guide/tutorials/bulk-provider-provisioning">
|
||||
Learn how to bulk provision providers in Prowler.
|
||||
</Card>
|
||||
<Card title="Prowler App" icon="pen-to-square" href="/user-guide/tutorials/prowler-app">
|
||||
Detailed instructions on how to use Prowler.
|
||||
</Card>
|
||||
</Columns>
|
||||
@@ -17,14 +17,18 @@ The Bulk Provider Provisioning tool automates the creation of cloud providers in
|
||||
* Testing connections to verify successful authentication
|
||||
* Processing multiple providers concurrently for efficiency
|
||||
|
||||
<Tip>
|
||||
**Using AWS Organizations?** For organizations with many AWS accounts, use the automated [AWS Organizations Bulk Provisioning](./aws-organizations-bulk-provisioning) tool to automatically discover and generate configuration for all accounts in your organization.
|
||||
</Tip>
|
||||
|
||||
## Prerequisites
|
||||
|
||||
### Requirements
|
||||
|
||||
* Python 3.7 or higher
|
||||
* Prowler API token (from Prowler Cloud or self-hosted Prowler App)
|
||||
* Prowler API key (from Prowler Cloud or self-hosted Prowler App)
|
||||
* For self-hosted Prowler App, remember to [point to your API base URL](#custom-api-endpoints)
|
||||
* Learn how to create API keys: [Prowler App API Keys](../tutorials/prowler-app-api-keys)
|
||||
* Authentication credentials for target cloud providers
|
||||
|
||||
### Installation
|
||||
@@ -39,28 +43,21 @@ pip install -r requirements.txt
|
||||
|
||||
### Authentication Setup
|
||||
|
||||
Configure your Prowler API token:
|
||||
Configure your Prowler API key:
|
||||
|
||||
```bash
|
||||
export PROWLER_API_TOKEN="your-prowler-api-token"
|
||||
export PROWLER_API_KEY="pk_example-api-key"
|
||||
```
|
||||
|
||||
To obtain an API token programmatically:
|
||||
To create an API key:
|
||||
|
||||
```bash
|
||||
export PROWLER_API_TOKEN=$(curl --location 'https://api.prowler.com/api/v1/tokens' \
|
||||
--header 'Content-Type: application/vnd.api+json' \
|
||||
--header 'Accept: application/vnd.api+json' \
|
||||
--data-raw '{
|
||||
"data": {
|
||||
"type": "tokens",
|
||||
"attributes": {
|
||||
"email": "your@email.com",
|
||||
"password": "your-password"
|
||||
}
|
||||
}
|
||||
}' | jq -r .data.attributes.access)
|
||||
```
|
||||
1. Log in to Prowler Cloud or Prowler App
|
||||
2. Click **Profile** → **Account**
|
||||
3. Click **Create API Key**
|
||||
4. Provide a descriptive name and optionally set an expiration date
|
||||
5. Copy the generated API key (it will only be shown once)
|
||||
|
||||
For detailed instructions, see: [Prowler App API Keys](../tutorials/prowler-app-api-keys)
|
||||
|
||||
## Configuration File Structure
|
||||
|
||||
@@ -340,11 +337,11 @@ Done. Success: 2 Failures: 0
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Invalid API Token
|
||||
### Invalid API Key
|
||||
|
||||
```
|
||||
Error: 401 Unauthorized
|
||||
Solution: Verify your PROWLER_API_TOKEN or --token parameter
|
||||
Solution: Verify your PROWLER_API_KEY environment variable or --api-key parameter
|
||||
```
|
||||
|
||||
### Network Timeouts
|
||||
|
||||
+4
@@ -2,6 +2,10 @@
|
||||
title: 'API Keys'
|
||||
---
|
||||
|
||||
import { VersionBadge } from "/snippets/version-badge.mdx"
|
||||
|
||||
<VersionBadge version="5.13.0" />
|
||||
|
||||
API key authentication in Prowler App provides an alternative to JWT tokens and empowers automation, CI/CD pipelines, and third-party integrations. This guide explains how to create, manage, and safeguard API keys when working with the Prowler API.
|
||||
|
||||
## API Key Advantages
|
||||
@@ -1,6 +1,9 @@
|
||||
---
|
||||
title: "Jira Integration"
|
||||
---
|
||||
import { VersionBadge } from "/snippets/version-badge.mdx"
|
||||
|
||||
<VersionBadge version="5.12.0" />
|
||||
|
||||
Prowler App enables automatic export of security findings to Jira, providing seamless integration with Atlassian's work item tracking and project management platform. This comprehensive guide demonstrates how to configure and manage Jira integrations to streamline security incident management and enhance team collaboration across security workflows.
|
||||
|
||||
|
||||
@@ -2,6 +2,10 @@
|
||||
title: 'Prowler Lighthouse AI'
|
||||
---
|
||||
|
||||
import { VersionBadge } from "/snippets/version-badge.mdx"
|
||||
|
||||
<VersionBadge version="5.8.0" />
|
||||
|
||||
Prowler Lighthouse AI is a Cloud Security Analyst chatbot that helps you understand, prioritize, and remediate security findings in your cloud environments. It's designed to provide security expertise for teams without dedicated resources, acting as your 24/7 virtual cloud security analyst.
|
||||
|
||||
<img src="/images/prowler-app/lighthouse-intro.png" alt="Prowler Lighthouse" />
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
---
|
||||
title: 'Mute Findings (Mutelist)'
|
||||
---
|
||||
import { VersionBadge } from "/snippets/version-badge.mdx"
|
||||
|
||||
<VersionBadge version="5.9.0" />
|
||||
|
||||
Prowler App allows users to mute specific findings to focus on the most critical security issues. This comprehensive guide demonstrates how to effectively use the Mutelist feature to manage and prioritize security findings.
|
||||
|
||||
|
||||
@@ -2,6 +2,10 @@
|
||||
title: 'Managing Users and Role-Based Access Control (RBAC)'
|
||||
---
|
||||
|
||||
import { VersionBadge } from "/snippets/version-badge.mdx"
|
||||
|
||||
<VersionBadge version="5.1.0" />
|
||||
|
||||
**Prowler App** supports multiple users within a single tenant, enabling seamless collaboration by allowing team members to easily share insights and manage security findings.
|
||||
|
||||
[Roles](#roles) help you control user permissions, determining what actions each user can perform and the data they can access within Prowler. By default, each account includes an immutable **admin** role, ensuring that your account always retains administrative access.
|
||||
|
||||
@@ -2,6 +2,10 @@
|
||||
title: 'Amazon S3 Integration'
|
||||
---
|
||||
|
||||
import { VersionBadge } from "/snippets/version-badge.mdx"
|
||||
|
||||
<VersionBadge version="5.10.0" />
|
||||
|
||||
**Prowler App** allows automatic export of scan results to Amazon S3 buckets, providing seamless integration with existing data workflows and storage infrastructure. This comprehensive guide demonstrates configuration and management of Amazon S3 integrations to streamline security finding management and reporting.
|
||||
|
||||
When enabled and configured, scan results are automatically stored in the configured bucket. Results are provided in `csv`, `html` and `json-ocsf` formats, offering flexibility for custom integrations:
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
---
|
||||
title: "AWS Security Hub Integration"
|
||||
---
|
||||
import { VersionBadge } from "/snippets/version-badge.mdx"
|
||||
|
||||
<VersionBadge version="5.11.0" />
|
||||
|
||||
Prowler App enables automatic export of security findings to AWS Security Hub, providing seamless integration with AWS's native security and compliance service. This comprehensive guide demonstrates how to configure and manage AWS Security Hub integrations to centralize security findings and enhance compliance tracking across AWS environments.
|
||||
|
||||
|
||||
@@ -2,6 +2,10 @@
|
||||
title: 'Social Login Configuration'
|
||||
---
|
||||
|
||||
import { VersionBadge } from "/snippets/version-badge.mdx"
|
||||
|
||||
<VersionBadge version="5.5.0" />
|
||||
|
||||
**Prowler App** supports social login using Google and GitHub OAuth providers. This document guides you through configuring the required environment variables to enable social authentication.
|
||||
|
||||
<img src="/images/prowler-app/social-login/social_login_buttons.png" alt="Social login buttons" width="700" />
|
||||
|
||||
@@ -2,6 +2,10 @@
|
||||
title: 'SAML Single Sign-On (SSO)'
|
||||
---
|
||||
|
||||
import { VersionBadge } from "/snippets/version-badge.mdx"
|
||||
|
||||
<VersionBadge version="5.9.0" />
|
||||
|
||||
This guide provides comprehensive instructions to configure SAML-based Single Sign-On (SSO) in Prowler App. This configuration allows users to authenticate using the organization's Identity Provider (IdP).
|
||||
|
||||
This document is divided into two main sections:
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
---
|
||||
title: "Workshop Introduction"
|
||||
description: "Hands-on labs to master Prowler's cloud security capabilities across AWS, Azure, and GCP"
|
||||
---
|
||||
|
||||
# Prowler Workshop
|
||||
|
||||
Welcome to the Prowler Workshop. This hands-on training provides practical experience with Prowler's cloud security monitoring and compliance automation capabilities across multiple cloud platforms.
|
||||
|
||||
## Workshop Overview
|
||||
|
||||
This workshop consists of eight progressive labs designed to guide you through Prowler's core features and advanced capabilities:
|
||||
|
||||
* **Lab 1:** Getting Started with Prowler CLI
|
||||
* **Lab 2:** Threat Detection with Prowler
|
||||
* **Lab 3:** Custom Checks with Prowler
|
||||
* **Lab 4:** Multi-Cloud Security with Prowler (Azure)
|
||||
* **Lab 5:** Multi-Cloud Security with Prowler (GCP)
|
||||
* **Lab 6:** Compliance as Code with Prowler
|
||||
* **Lab 7:** Integrations with Prowler (AWS Security Hub)
|
||||
* **Lab 8:** Prowler SaaS Platform
|
||||
|
||||
## Lab Structure
|
||||
|
||||
Each lab is self-contained and includes:
|
||||
|
||||
* **Prerequisites:** Required cloud accounts, tools, and prior lab dependencies
|
||||
* **Objectives:** Clear learning goals for the lab
|
||||
* **Step-by-step instructions:** Detailed guidance through each task
|
||||
* **Expected outcomes:** What you should achieve by completing the lab
|
||||
* **Verification steps:** How to confirm successful completion
|
||||
|
||||
## Prerequisites Approach
|
||||
|
||||
Each lab specifies its own prerequisites, as different labs require different cloud provider accounts, tools, and access levels. Review the prerequisites section at the beginning of each lab before starting.
|
||||
|
||||
## How to Use This Workshop
|
||||
|
||||
* Labs are designed to be completed sequentially, as later labs may build on concepts from earlier ones
|
||||
* Estimated time to complete varies by lab (typically 30-60 minutes each)
|
||||
* You can pause between labs and resume later
|
||||
* Some labs can be completed independently if you have the necessary prerequisites
|
||||
|
||||
## Getting Help
|
||||
|
||||
If you encounter issues during the workshop:
|
||||
|
||||
* Refer to the [Troubleshooting](/troubleshooting) guide
|
||||
* Join the [Prowler Slack community](https://goto.prowler.com/slack)
|
||||
* Visit the [Prowler GitHub repository](https://github.com/prowler-cloud/prowler) for documentation and issues
|
||||
|
||||
## Ready to Start?
|
||||
|
||||
Begin with [Lab 1: Getting Started with Prowler CLI](/workshop/lab-01-getting-started) to set up your environment and run your first security scan.
|
||||
@@ -0,0 +1,203 @@
|
||||
---
|
||||
title: "Lab 1: Getting Started with Prowler CLI"
|
||||
description: "Install Prowler CLI and run your first cloud security assessment on AWS"
|
||||
---
|
||||
|
||||
<Note>
|
||||
**Tags:** `workshop` `aws` `getting-started` `beginner` `cli`
|
||||
</Note>
|
||||
|
||||
# Lab 1: Getting Started with Prowler CLI
|
||||
|
||||
Learn to install Prowler CLI and perform your first cloud security assessment on AWS.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
* AWS account with active resources
|
||||
* AWS CLI installed and configured
|
||||
* IAM credentials with appropriate permissions (see [AWS Authentication](/user-guide/providers/aws/authentication))
|
||||
* Python 3.9 or higher
|
||||
* Basic command-line experience
|
||||
|
||||
**Estimated Time:** 30 minutes
|
||||
|
||||
## Lab Objectives
|
||||
|
||||
By completing this lab, you will:
|
||||
|
||||
* Install Prowler CLI using pip
|
||||
* Configure AWS credentials for Prowler
|
||||
* Execute your first security scan
|
||||
* Understand Prowler's output formats
|
||||
* Review security findings
|
||||
|
||||
## Step 1: Install Prowler CLI
|
||||
|
||||
Install Prowler using pip:
|
||||
|
||||
```bash
|
||||
pip install prowler
|
||||
```
|
||||
|
||||
Verify the installation:
|
||||
|
||||
```bash
|
||||
prowler -v
|
||||
```
|
||||
|
||||
Expected output:
|
||||
```
|
||||
Prowler X.X.X
|
||||
```
|
||||
|
||||
<Tip>
|
||||
For alternative installation methods (Docker, from source), see [Prowler CLI Installation](/getting-started/installation/prowler-cli).
|
||||
</Tip>
|
||||
|
||||
## Step 2: Configure AWS Credentials
|
||||
|
||||
Ensure AWS credentials are configured. Prowler uses the same credential chain as AWS CLI.
|
||||
|
||||
Verify credentials:
|
||||
|
||||
```bash
|
||||
aws sts get-caller-identity
|
||||
```
|
||||
|
||||
Expected output:
|
||||
```json
|
||||
{
|
||||
"UserId": "AIDACKCEVSQ6C2EXAMPLE",
|
||||
"Account": "123456789012",
|
||||
"Arn": "arn:aws:iam::123456789012:user/username"
|
||||
}
|
||||
```
|
||||
|
||||
<Note>
|
||||
[Note: Screenshot of slide 8 showing AWS credential verification - to be added]
|
||||
</Note>
|
||||
|
||||
## Step 3: Run Your First Scan
|
||||
|
||||
Execute a basic Prowler scan:
|
||||
|
||||
```bash
|
||||
prowler aws
|
||||
```
|
||||
|
||||
This command:
|
||||
* Scans all enabled AWS regions
|
||||
* Runs all available security checks
|
||||
* Generates output in the current directory
|
||||
|
||||
<Note>
|
||||
The scan may take 5-15 minutes depending on the number of resources in your AWS account.
|
||||
</Note>
|
||||
|
||||
## Step 4: Understanding the Output
|
||||
|
||||
Prowler generates multiple output formats in the `output` directory:
|
||||
|
||||
* **CSV:** Detailed findings (`prowler-output-*.csv`)
|
||||
* **JSON:** Machine-readable format (`prowler-output-*.json`)
|
||||
* **HTML:** Human-readable report (`prowler-output-*.html`)
|
||||
|
||||
Review the HTML report:
|
||||
|
||||
```bash
|
||||
open output/prowler-output-*.html
|
||||
```
|
||||
|
||||
<Note>
|
||||
[Note: Screenshot of slide 10 showing HTML report - to be added]
|
||||
</Note>
|
||||
|
||||
## Step 5: Analyze Security Findings
|
||||
|
||||
Examine the findings structure in the HTML report:
|
||||
|
||||
* **Status:** PASS, FAIL, or MANUAL
|
||||
* **Severity:** critical, high, medium, low, informational
|
||||
* **Service:** AWS service affected (e.g., S3, IAM, EC2)
|
||||
* **Check ID:** Unique identifier for each check
|
||||
* **Region:** AWS region where the resource exists
|
||||
* **Resource:** Specific resource ARN or identifier
|
||||
|
||||
Example finding structure:
|
||||
|
||||
```json
|
||||
{
|
||||
"Status": "FAIL",
|
||||
"Severity": "high",
|
||||
"Service": "s3",
|
||||
"CheckID": "s3_bucket_public_access",
|
||||
"Region": "us-east-1",
|
||||
"Resource": "arn:aws:s3:::my-bucket"
|
||||
}
|
||||
```
|
||||
|
||||
## Step 6: Filter Scan by Service
|
||||
|
||||
Run a targeted scan for specific AWS services:
|
||||
|
||||
```bash
|
||||
prowler aws --services s3 iam
|
||||
```
|
||||
|
||||
This scans only S3 and IAM services, reducing execution time.
|
||||
|
||||
## Step 7: Run Checks by Severity
|
||||
|
||||
Scan for critical and high-severity findings only:
|
||||
|
||||
```bash
|
||||
prowler aws --severity critical high
|
||||
```
|
||||
|
||||
This focuses on the most important security issues.
|
||||
|
||||
<Note>
|
||||
[Note: Screenshot of slide 13 showing severity filtering - to be added]
|
||||
</Note>
|
||||
|
||||
## Verification Steps
|
||||
|
||||
Confirm successful lab completion:
|
||||
|
||||
1. Prowler CLI installed and version verified
|
||||
2. AWS credentials properly configured
|
||||
3. First scan completed successfully
|
||||
4. Output files generated in the `output` directory
|
||||
5. HTML report reviewed and findings understood
|
||||
6. Filtered scans executed by service and severity
|
||||
|
||||
## Expected Outcomes
|
||||
|
||||
After completing this lab, you should have:
|
||||
|
||||
* Working Prowler CLI installation
|
||||
* Understanding of basic Prowler commands
|
||||
* Knowledge of output formats
|
||||
* Ability to run targeted scans
|
||||
* Familiarity with finding severity levels
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
**Issue:** `prowler: command not found`
|
||||
* **Solution:** Ensure Python's bin directory is in your PATH, or use `python3 -m prowler`
|
||||
|
||||
**Issue:** AWS credentials error
|
||||
* **Solution:** Run `aws configure` to set up credentials, or use environment variables
|
||||
|
||||
**Issue:** Scan takes too long
|
||||
* **Solution:** Use `--services` to scan specific services or `--regions` to limit regions
|
||||
|
||||
## Next Steps
|
||||
|
||||
Continue to [Lab 2: Threat Detection with Prowler](/workshop/lab-02-threat-detection) to learn about identifying security threats in your AWS environment.
|
||||
|
||||
## Additional Resources
|
||||
|
||||
* [Prowler CLI Documentation](/getting-started/basic-usage/prowler-cli)
|
||||
* [AWS Authentication Methods](/user-guide/providers/aws/authentication)
|
||||
* [Output Formats](/user-guide/cli/tutorials/reporting)
|
||||
@@ -0,0 +1,263 @@
|
||||
---
|
||||
title: "Lab 2: Threat Detection with Prowler"
|
||||
description: "Identify and analyze security threats in AWS environments using Prowler's threat detection capabilities"
|
||||
---
|
||||
|
||||
<Note>
|
||||
**Tags:** `workshop` `aws` `threat-detection` `intermediate` `security`
|
||||
</Note>
|
||||
|
||||
# Lab 2: Threat Detection with Prowler
|
||||
|
||||
Learn to identify security threats, exposed resources, and potential attack vectors in AWS environments using Prowler's threat detection features.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
* Completion of [Lab 1: Getting Started with Prowler CLI](/workshop/lab-01-getting-started)
|
||||
* AWS account with resources (EC2 instances, S3 buckets, security groups)
|
||||
* Prowler CLI installed and configured
|
||||
* Basic understanding of AWS security concepts
|
||||
|
||||
**Estimated Time:** 45 minutes
|
||||
|
||||
## Lab Objectives
|
||||
|
||||
By completing this lab, you will:
|
||||
|
||||
* Understand Prowler's threat detection capabilities
|
||||
* Identify publicly exposed resources
|
||||
* Detect insecure configurations
|
||||
* Analyze CloudTrail events for suspicious activity
|
||||
* Prioritize security findings by risk
|
||||
|
||||
## Step 1: Understanding Threat Detection Checks
|
||||
|
||||
Prowler includes checks that identify:
|
||||
|
||||
* Public exposure (S3 buckets, EC2 instances, RDS databases)
|
||||
* Insecure network configurations (security groups, NACLs)
|
||||
* Weak encryption settings
|
||||
* Suspicious IAM permissions
|
||||
* CloudTrail anomalies
|
||||
|
||||
List threat detection checks:
|
||||
|
||||
```bash
|
||||
prowler aws --list-checks | grep -i "public\|exposed\|open"
|
||||
```
|
||||
|
||||
## Step 2: Scan for Publicly Exposed Resources
|
||||
|
||||
Run a scan focusing on public exposure:
|
||||
|
||||
```bash
|
||||
prowler aws --checks s3_bucket_public_access ec2_instance_public_ip rds_instance_publicly_accessible
|
||||
```
|
||||
|
||||
This identifies:
|
||||
* S3 buckets with public access
|
||||
* EC2 instances with public IPs
|
||||
* RDS databases accessible from the internet
|
||||
|
||||
<Note>
|
||||
[Note: Screenshot of slide 17 showing public exposure findings - to be added]
|
||||
</Note>
|
||||
|
||||
## Step 3: Analyze Security Group Misconfigurations
|
||||
|
||||
Security groups control network access. Scan for insecure rules:
|
||||
|
||||
```bash
|
||||
prowler aws --services ec2 --checks ec2_securitygroup*
|
||||
```
|
||||
|
||||
Look for findings related to:
|
||||
* `0.0.0.0/0` ingress rules (any IP can connect)
|
||||
* Open high-risk ports (22, 3389, 3306, 5432)
|
||||
* Overly permissive egress rules
|
||||
|
||||
Example vulnerable security group:
|
||||
```
|
||||
Port 22 (SSH) open to 0.0.0.0/0
|
||||
Port 3389 (RDP) open to 0.0.0.0/0
|
||||
```
|
||||
|
||||
<Warning>
|
||||
Security groups with `0.0.0.0/0` on sensitive ports expose resources to the entire internet and should be restricted immediately.
|
||||
</Warning>
|
||||
|
||||
## Step 4: Check for Unencrypted Data
|
||||
|
||||
Scan for unencrypted storage and data transmission:
|
||||
|
||||
```bash
|
||||
prowler aws --checks s3_bucket_default_encryption ebs_volume_encryption rds_instance_storage_encrypted
|
||||
```
|
||||
|
||||
Key checks:
|
||||
* S3 bucket default encryption disabled
|
||||
* EBS volumes without encryption
|
||||
* RDS instances with unencrypted storage
|
||||
|
||||
<Note>
|
||||
[Note: Screenshot of slide 20 showing encryption findings - to be added]
|
||||
</Note>
|
||||
|
||||
## Step 5: CloudTrail Threat Detection
|
||||
|
||||
Enable CloudTrail event analysis to detect suspicious activity:
|
||||
|
||||
```bash
|
||||
prowler aws --services cloudtrail
|
||||
```
|
||||
|
||||
Prowler checks for:
|
||||
* CloudTrail disabled in regions
|
||||
* Log file validation disabled
|
||||
* S3 bucket not encrypted
|
||||
* CloudWatch logging not configured
|
||||
|
||||
<Tip>
|
||||
CloudTrail provides audit logs of API calls. Proper configuration is essential for threat detection and incident response.
|
||||
</Tip>
|
||||
|
||||
## Step 6: Analyze IAM Security Risks
|
||||
|
||||
Identify IAM misconfigurations that could lead to privilege escalation:
|
||||
|
||||
```bash
|
||||
prowler aws --services iam --severity critical high
|
||||
```
|
||||
|
||||
Look for:
|
||||
* Root account usage
|
||||
* IAM users without MFA
|
||||
* Overly permissive IAM policies (e.g., `*:*`)
|
||||
* Inactive credentials not rotated
|
||||
|
||||
Example critical finding:
|
||||
```
|
||||
IAM user with administrative privileges without MFA enabled
|
||||
```
|
||||
|
||||
## Step 7: Generate a Threat-Focused Report
|
||||
|
||||
Create a filtered report with only security threats:
|
||||
|
||||
```bash
|
||||
prowler aws --severity critical high --status FAIL -o html json
|
||||
```
|
||||
|
||||
This generates reports containing only:
|
||||
* Critical and high-severity findings
|
||||
* Failed checks (PASS checks excluded)
|
||||
|
||||
Review the HTML report:
|
||||
|
||||
```bash
|
||||
open output/prowler-output-*.html
|
||||
```
|
||||
|
||||
<Note>
|
||||
[Note: Screenshot of slide 25 showing threat-focused report - to be added]
|
||||
</Note>
|
||||
|
||||
## Step 8: Prioritize Findings
|
||||
|
||||
Categorize findings by risk level:
|
||||
|
||||
**Critical Priority (Address Immediately):**
|
||||
* S3 buckets with public write access
|
||||
* Root account without MFA
|
||||
* Database instances publicly accessible
|
||||
* Security groups open to `0.0.0.0/0` on sensitive ports
|
||||
|
||||
**High Priority (Address Soon):**
|
||||
* Unencrypted storage volumes
|
||||
* CloudTrail logging disabled
|
||||
* IAM users without MFA
|
||||
* Overly permissive IAM policies
|
||||
|
||||
**Medium Priority (Address as Resources Allow):**
|
||||
* Old access keys not rotated
|
||||
* S3 bucket logging disabled
|
||||
* VPC flow logs not enabled
|
||||
|
||||
## Step 9: Export Findings for Remediation
|
||||
|
||||
Export findings to CSV for tracking:
|
||||
|
||||
```bash
|
||||
prowler aws --severity critical high --status FAIL -o csv
|
||||
```
|
||||
|
||||
Share the CSV with your security team for remediation tracking.
|
||||
|
||||
## Verification Steps
|
||||
|
||||
Confirm successful lab completion:
|
||||
|
||||
1. Identified publicly exposed resources
|
||||
2. Detected insecure security group configurations
|
||||
3. Found unencrypted data storage
|
||||
4. Reviewed CloudTrail security settings
|
||||
5. Analyzed IAM security risks
|
||||
6. Generated threat-focused reports
|
||||
7. Prioritized findings by risk level
|
||||
|
||||
## Expected Outcomes
|
||||
|
||||
After completing this lab, you should:
|
||||
|
||||
* Understand common AWS security threats
|
||||
* Know how to identify exposed resources
|
||||
* Be able to prioritize security findings
|
||||
* Have generated threat detection reports
|
||||
|
||||
## Remediation Examples
|
||||
|
||||
**Example 1: Remove public access from S3 bucket**
|
||||
```bash
|
||||
aws s3api put-public-access-block \
|
||||
--bucket my-bucket \
|
||||
--public-access-block-configuration \
|
||||
"BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true"
|
||||
```
|
||||
|
||||
**Example 2: Restrict security group rule**
|
||||
```bash
|
||||
aws ec2 revoke-security-group-ingress \
|
||||
--group-id sg-12345678 \
|
||||
--protocol tcp \
|
||||
--port 22 \
|
||||
--cidr 0.0.0.0/0
|
||||
```
|
||||
|
||||
**Example 3: Enable S3 bucket encryption**
|
||||
```bash
|
||||
aws s3api put-bucket-encryption \
|
||||
--bucket my-bucket \
|
||||
--server-side-encryption-configuration \
|
||||
'{"Rules":[{"ApplyServerSideEncryptionByDefault":{"SSEAlgorithm":"AES256"}}]}'
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
**Issue:** Too many findings to review
|
||||
* **Solution:** Use `--severity critical high` to focus on the most important issues first
|
||||
|
||||
**Issue:** Don't understand a finding
|
||||
* **Solution:** Use `--describe-check <check-id>` to get detailed information
|
||||
|
||||
**Issue:** Need to share findings with team
|
||||
* **Solution:** Export to CSV or JSON and use collaboration tools
|
||||
|
||||
## Next Steps
|
||||
|
||||
Continue to [Lab 3: Custom Checks with Prowler](/workshop/lab-03-custom-checks) to learn how to create organization-specific security checks.
|
||||
|
||||
## Additional Resources
|
||||
|
||||
* [AWS Threat Detection Guide](/user-guide/providers/aws/threat-detection)
|
||||
* [Security Best Practices](/user-guide/providers/aws/getting-started-aws)
|
||||
* [Prowler Check Reference](https://hub.prowler.com)
|
||||
@@ -0,0 +1,359 @@
|
||||
---
|
||||
title: "Lab 3: Custom Checks with Prowler"
|
||||
description: "Create organization-specific security checks and customize Prowler for your security requirements"
|
||||
---
|
||||
|
||||
<Note>
|
||||
**Tags:** `workshop` `aws` `custom-checks` `advanced` `development`
|
||||
</Note>
|
||||
|
||||
# Lab 3: Custom Checks with Prowler
|
||||
|
||||
Learn to create custom security checks tailored to your organization's specific security policies and compliance requirements.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
* Completion of [Lab 1: Getting Started with Prowler CLI](/workshop/lab-01-getting-started)
|
||||
* Prowler CLI installed from source (for custom check development)
|
||||
* Python 3.9 or higher
|
||||
* Basic Python programming knowledge
|
||||
* Understanding of AWS SDK (boto3)
|
||||
* Text editor or IDE (VS Code, PyCharm)
|
||||
|
||||
**Estimated Time:** 60 minutes
|
||||
|
||||
## Lab Objectives
|
||||
|
||||
By completing this lab, you will:
|
||||
|
||||
* Understand Prowler's check structure
|
||||
* Create a custom security check
|
||||
* Test and validate custom checks
|
||||
* Use custom check metadata
|
||||
* Integrate custom checks into scans
|
||||
|
||||
## Step 1: Install Prowler from Source
|
||||
|
||||
To develop custom checks, install Prowler from source:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/prowler-cloud/prowler
|
||||
cd prowler
|
||||
pip install poetry
|
||||
poetry install
|
||||
```
|
||||
|
||||
Activate the virtual environment:
|
||||
|
||||
```bash
|
||||
poetry shell
|
||||
```
|
||||
|
||||
Verify installation:
|
||||
|
||||
```bash
|
||||
prowler -v
|
||||
```
|
||||
|
||||
<Note>
|
||||
[Note: Screenshot of slide 29 showing source installation - to be added]
|
||||
</Note>
|
||||
|
||||
## Step 2: Understand Check Structure
|
||||
|
||||
Prowler checks are Python files located in:
|
||||
```
|
||||
prowler/providers/<provider>/services/<service>/
|
||||
```
|
||||
|
||||
Example check structure:
|
||||
```
|
||||
prowler/providers/aws/services/s3/s3_bucket_custom_check/
|
||||
├── s3_bucket_custom_check.py # Check logic
|
||||
└── s3_bucket_custom_check.metadata.json # Check metadata
|
||||
```
|
||||
|
||||
## Step 3: Create a Custom Check Directory
|
||||
|
||||
Create a custom check to verify S3 buckets have specific naming conventions:
|
||||
|
||||
```bash
|
||||
mkdir -p prowler/providers/aws/services/s3/s3_bucket_naming_convention
|
||||
cd prowler/providers/aws/services/s3/s3_bucket_naming_convention
|
||||
```
|
||||
|
||||
## Step 4: Write the Check Logic
|
||||
|
||||
Create `s3_bucket_naming_convention.py`:
|
||||
|
||||
```python
|
||||
from prowler.lib.check.models import Check, Check_Report_AWS
|
||||
from prowler.providers.aws.services.s3.s3_client import s3_client
|
||||
|
||||
class s3_bucket_naming_convention(Check):
|
||||
def execute(self):
|
||||
findings = []
|
||||
# Define your organization's naming pattern
|
||||
naming_pattern = "company-"
|
||||
|
||||
for bucket in s3_client.buckets:
|
||||
report = Check_Report_AWS(self.metadata())
|
||||
report.region = bucket.region
|
||||
report.resource_id = bucket.name
|
||||
report.resource_arn = bucket.arn
|
||||
report.resource_tags = bucket.tags
|
||||
|
||||
# Check if bucket name follows naming convention
|
||||
if bucket.name.startswith(naming_pattern):
|
||||
report.status = "PASS"
|
||||
report.status_extended = f"S3 bucket {bucket.name} follows naming convention."
|
||||
else:
|
||||
report.status = "FAIL"
|
||||
report.status_extended = f"S3 bucket {bucket.name} does not follow naming convention (should start with '{naming_pattern}')."
|
||||
|
||||
findings.append(report)
|
||||
|
||||
return findings
|
||||
```
|
||||
|
||||
<Tip>
|
||||
Customize the `naming_pattern` variable to match your organization's requirements (e.g., "prod-", "dev-", "projectname-").
|
||||
</Tip>
|
||||
|
||||
## Step 5: Create Check Metadata
|
||||
|
||||
Create `s3_bucket_naming_convention.metadata.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"Provider": "aws",
|
||||
"CheckID": "s3_bucket_naming_convention",
|
||||
"CheckTitle": "Check if S3 buckets follow naming convention",
|
||||
"CheckType": ["Software and Configuration Checks"],
|
||||
"ServiceName": "s3",
|
||||
"SubServiceName": "",
|
||||
"ResourceIdTemplate": "arn:aws:s3:::bucket_name",
|
||||
"Severity": "low",
|
||||
"ResourceType": "AwsS3Bucket",
|
||||
"Description": "Ensure S3 buckets follow the organization's naming convention for consistency and management.",
|
||||
"Risk": "S3 buckets not following naming conventions may lead to management difficulties and confusion.",
|
||||
"RelatedUrl": "https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucketnamingrules.html",
|
||||
"Remediation": {
|
||||
"Code": {
|
||||
"CLI": "",
|
||||
"NativeIaC": "",
|
||||
"Other": "Rename the S3 bucket to follow the organization's naming convention or update bucket policies.",
|
||||
"Terraform": ""
|
||||
},
|
||||
"Recommendation": {
|
||||
"Text": "Ensure all S3 buckets follow the defined naming convention for your organization.",
|
||||
"Url": "https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucketnamingrules.html"
|
||||
}
|
||||
},
|
||||
"Categories": [
|
||||
"forensics-ready"
|
||||
],
|
||||
"DependsOn": [],
|
||||
"RelatedTo": [],
|
||||
"Notes": "This is a custom check created for organization-specific requirements."
|
||||
}
|
||||
```
|
||||
|
||||
<Note>
|
||||
[Note: Screenshot of slide 33 showing metadata structure - to be added]
|
||||
</Note>
|
||||
|
||||
## Step 6: Test the Custom Check
|
||||
|
||||
Run only your custom check:
|
||||
|
||||
```bash
|
||||
prowler aws --checks s3_bucket_naming_convention
|
||||
```
|
||||
|
||||
Review the output to verify:
|
||||
* Check executes without errors
|
||||
* Findings are generated for each S3 bucket
|
||||
* Status is correct (PASS/FAIL) based on naming convention
|
||||
|
||||
## Step 7: Create a Custom Check for EC2 Instance Tags
|
||||
|
||||
Create another custom check to enforce EC2 tagging policies:
|
||||
|
||||
```bash
|
||||
mkdir -p prowler/providers/aws/services/ec2/ec2_instance_required_tags
|
||||
cd prowler/providers/aws/services/ec2/ec2_instance_required_tags
|
||||
```
|
||||
|
||||
Create `ec2_instance_required_tags.py`:
|
||||
|
||||
```python
|
||||
from prowler.lib.check.models import Check, Check_Report_AWS
|
||||
from prowler.providers.aws.services.ec2.ec2_client import ec2_client
|
||||
|
||||
class ec2_instance_required_tags(Check):
|
||||
def execute(self):
|
||||
findings = []
|
||||
# Define required tags
|
||||
required_tags = ["Environment", "Owner", "CostCenter"]
|
||||
|
||||
for instance in ec2_client.instances:
|
||||
report = Check_Report_AWS(self.metadata())
|
||||
report.region = instance.region
|
||||
report.resource_id = instance.id
|
||||
report.resource_arn = instance.arn
|
||||
report.resource_tags = instance.tags
|
||||
|
||||
# Get instance tag keys
|
||||
instance_tag_keys = [tag["Key"] for tag in instance.tags] if instance.tags else []
|
||||
|
||||
# Check if all required tags are present
|
||||
missing_tags = [tag for tag in required_tags if tag not in instance_tag_keys]
|
||||
|
||||
if not missing_tags:
|
||||
report.status = "PASS"
|
||||
report.status_extended = f"EC2 instance {instance.id} has all required tags."
|
||||
else:
|
||||
report.status = "FAIL"
|
||||
report.status_extended = f"EC2 instance {instance.id} is missing required tags: {', '.join(missing_tags)}."
|
||||
|
||||
findings.append(report)
|
||||
|
||||
return findings
|
||||
```
|
||||
|
||||
Create `ec2_instance_required_tags.metadata.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"Provider": "aws",
|
||||
"CheckID": "ec2_instance_required_tags",
|
||||
"CheckTitle": "Check if EC2 instances have required tags",
|
||||
"CheckType": ["Software and Configuration Checks"],
|
||||
"ServiceName": "ec2",
|
||||
"SubServiceName": "",
|
||||
"ResourceIdTemplate": "arn:aws:ec2:region:account-id:instance/instance-id",
|
||||
"Severity": "medium",
|
||||
"ResourceType": "AwsEc2Instance",
|
||||
"Description": "Ensure EC2 instances have required tags for proper resource management and cost allocation.",
|
||||
"Risk": "EC2 instances without required tags may lead to difficulties in cost tracking, ownership identification, and resource management.",
|
||||
"RelatedUrl": "https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html",
|
||||
"Remediation": {
|
||||
"Code": {
|
||||
"CLI": "aws ec2 create-tags --resources <instance-id> --tags Key=Environment,Value=<value> Key=Owner,Value=<value> Key=CostCenter,Value=<value>",
|
||||
"NativeIaC": "",
|
||||
"Other": "",
|
||||
"Terraform": "resource \"aws_ec2_tag\" \"example\" {\n resource_id = aws_instance.example.id\n key = \"Environment\"\n value = \"Production\"\n}"
|
||||
},
|
||||
"Recommendation": {
|
||||
"Text": "Add the required tags (Environment, Owner, CostCenter) to all EC2 instances.",
|
||||
"Url": "https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html"
|
||||
}
|
||||
},
|
||||
"Categories": [
|
||||
"tagging"
|
||||
],
|
||||
"DependsOn": [],
|
||||
"RelatedTo": [],
|
||||
"Notes": "Customize the required_tags list in the check code to match your organization's tagging policy."
|
||||
}
|
||||
```
|
||||
|
||||
## Step 8: Test Multiple Custom Checks
|
||||
|
||||
Run both custom checks together:
|
||||
|
||||
```bash
|
||||
prowler aws --checks s3_bucket_naming_convention ec2_instance_required_tags
|
||||
```
|
||||
|
||||
## Step 9: Create a Custom Checks Group
|
||||
|
||||
Create a file to group your custom checks:
|
||||
|
||||
Create `prowler/config/custom_checks.yaml`:
|
||||
|
||||
```yaml
|
||||
custom-checks:
|
||||
- s3_bucket_naming_convention
|
||||
- ec2_instance_required_tags
|
||||
```
|
||||
|
||||
Run all custom checks:
|
||||
|
||||
```bash
|
||||
prowler aws --checks-file prowler/config/custom_checks.yaml
|
||||
```
|
||||
|
||||
<Note>
|
||||
[Note: Screenshot of slide 38 showing custom checks output - to be added]
|
||||
</Note>
|
||||
|
||||
## Step 10: Validate Check Metadata
|
||||
|
||||
Prowler includes metadata validation. Ensure your metadata follows guidelines:
|
||||
|
||||
```bash
|
||||
python -m prowler.lib.check.check_metadata_validator
|
||||
```
|
||||
|
||||
This validates:
|
||||
* Required metadata fields are present
|
||||
* Severity values are valid
|
||||
* URLs are properly formatted
|
||||
* JSON structure is correct
|
||||
|
||||
## Verification Steps
|
||||
|
||||
Confirm successful lab completion:
|
||||
|
||||
1. Prowler installed from source
|
||||
2. Custom S3 naming convention check created
|
||||
3. Custom EC2 tagging check created
|
||||
4. Both checks execute successfully
|
||||
5. Metadata files are properly formatted
|
||||
6. Custom checks grouped for easy execution
|
||||
|
||||
## Expected Outcomes
|
||||
|
||||
After completing this lab, you should:
|
||||
|
||||
* Understand Prowler's check architecture
|
||||
* Be able to create custom security checks
|
||||
* Know how to write check metadata
|
||||
* Be capable of testing and validating checks
|
||||
* Have created reusable custom security policies
|
||||
|
||||
## Best Practices for Custom Checks
|
||||
|
||||
1. **Follow naming conventions:** Use descriptive check IDs (e.g., `service_resource_requirement`)
|
||||
2. **Set appropriate severity:** Match severity to the security impact
|
||||
3. **Provide clear descriptions:** Help users understand what the check validates
|
||||
4. **Include remediation guidance:** Provide actionable steps to fix findings
|
||||
5. **Test thoroughly:** Verify checks work across different AWS regions and account configurations
|
||||
6. **Document assumptions:** Note any specific requirements or limitations
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
**Issue:** Check not found when running
|
||||
* **Solution:** Ensure the check directory and files follow the correct naming convention and location
|
||||
|
||||
**Issue:** Import errors in check code
|
||||
* **Solution:** Verify you're using the Poetry virtual environment (`poetry shell`)
|
||||
|
||||
**Issue:** Metadata validation fails
|
||||
* **Solution:** Review the metadata format against Prowler's schema requirements
|
||||
|
||||
**Issue:** Check returns no findings
|
||||
* **Solution:** Add print statements or use a debugger to verify the service client has data
|
||||
|
||||
## Next Steps
|
||||
|
||||
Continue to [Lab 4: Multi-Cloud Security with Prowler (Azure)](/workshop/lab-04-azure-multicloud) to extend security monitoring to Azure environments.
|
||||
|
||||
## Additional Resources
|
||||
|
||||
* [Custom Checks Development Guide](/developer-guide/checks)
|
||||
* [Check Metadata Guidelines](/developer-guide/check-metadata-guidelines)
|
||||
* [Prowler Development Documentation](/developer-guide/introduction)
|
||||
* [Prowler Check Kreator](/user-guide/cli/tutorials/prowler-check-kreator)
|
||||
@@ -0,0 +1,346 @@
|
||||
---
|
||||
title: "Lab 4: Multi-Cloud Security with Prowler (Azure)"
|
||||
description: "Extend security monitoring to Azure environments using Prowler's multi-cloud capabilities"
|
||||
---
|
||||
|
||||
<Note>
|
||||
**Tags:** `workshop` `azure` `multi-cloud` `intermediate` `authentication`
|
||||
</Note>
|
||||
|
||||
# Lab 4: Multi-Cloud Security with Prowler (Azure)
|
||||
|
||||
Learn to secure Azure environments using Prowler's multi-cloud security assessment capabilities.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
* Prowler CLI installed ([Lab 1](/workshop/lab-01-getting-started))
|
||||
* Active Azure subscription
|
||||
* Azure CLI installed
|
||||
* Azure account with appropriate permissions (Reader role minimum)
|
||||
* Basic understanding of Azure services
|
||||
|
||||
**Estimated Time:** 45 minutes
|
||||
|
||||
## Lab Objectives
|
||||
|
||||
By completing this lab, you will:
|
||||
|
||||
* Configure Azure authentication for Prowler
|
||||
* Run security assessments on Azure subscriptions
|
||||
* Understand Azure-specific security checks
|
||||
* Compare security findings across cloud providers
|
||||
* Implement multi-cloud security strategies
|
||||
|
||||
## Step 1: Install Azure CLI
|
||||
|
||||
Install Azure CLI if not already present:
|
||||
|
||||
**macOS:**
|
||||
```bash
|
||||
brew install azure-cli
|
||||
```
|
||||
|
||||
**Linux:**
|
||||
```bash
|
||||
curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash
|
||||
```
|
||||
|
||||
**Windows:**
|
||||
```powershell
|
||||
winget install Microsoft.AzureCLI
|
||||
```
|
||||
|
||||
Verify installation:
|
||||
```bash
|
||||
az --version
|
||||
```
|
||||
|
||||
## Step 2: Authenticate to Azure
|
||||
|
||||
Sign in to Azure:
|
||||
|
||||
```bash
|
||||
az login
|
||||
```
|
||||
|
||||
This opens a browser window for authentication.
|
||||
|
||||
Verify authentication:
|
||||
```bash
|
||||
az account show
|
||||
```
|
||||
|
||||
Expected output:
|
||||
```json
|
||||
{
|
||||
"id": "12345678-1234-1234-1234-123456789012",
|
||||
"name": "My Subscription",
|
||||
"tenantId": "87654321-4321-4321-4321-210987654321",
|
||||
"state": "Enabled"
|
||||
}
|
||||
```
|
||||
|
||||
<Note>
|
||||
[Note: Screenshot of slide 43 showing Azure authentication - to be added]
|
||||
</Note>
|
||||
|
||||
## Step 3: List Azure Subscriptions
|
||||
|
||||
If you have multiple subscriptions, list them:
|
||||
|
||||
```bash
|
||||
az account list --output table
|
||||
```
|
||||
|
||||
Set the active subscription:
|
||||
```bash
|
||||
az account set --subscription "subscription-id"
|
||||
```
|
||||
|
||||
## Step 4: Configure Azure Service Principal (Optional)
|
||||
|
||||
For automated scans, create a service principal:
|
||||
|
||||
```bash
|
||||
az ad sp create-for-rbac --name "prowler-scanner" --role Reader --scopes /subscriptions/{subscription-id}
|
||||
```
|
||||
|
||||
This returns:
|
||||
```json
|
||||
{
|
||||
"appId": "app-id",
|
||||
"displayName": "prowler-scanner",
|
||||
"password": "password",
|
||||
"tenant": "tenant-id"
|
||||
}
|
||||
```
|
||||
|
||||
<Warning>
|
||||
Store service principal credentials securely. These provide programmatic access to your Azure subscription.
|
||||
</Warning>
|
||||
|
||||
Export credentials as environment variables:
|
||||
```bash
|
||||
export AZURE_CLIENT_ID="app-id"
|
||||
export AZURE_CLIENT_SECRET="password"
|
||||
export AZURE_TENANT_ID="tenant-id"
|
||||
export AZURE_SUBSCRIPTION_ID="subscription-id"
|
||||
```
|
||||
|
||||
## Step 5: Run Your First Azure Scan
|
||||
|
||||
Execute Prowler against Azure:
|
||||
|
||||
```bash
|
||||
prowler azure
|
||||
```
|
||||
|
||||
This command:
|
||||
* Uses Azure CLI credentials (or service principal if configured)
|
||||
* Scans the active subscription
|
||||
* Runs all Azure security checks
|
||||
* Generates output in multiple formats
|
||||
|
||||
<Note>
|
||||
Azure scans typically take 5-10 minutes depending on resource count.
|
||||
</Note>
|
||||
|
||||
<Note>
|
||||
[Note: Screenshot of slide 47 showing Azure scan execution - to be added]
|
||||
</Note>
|
||||
|
||||
## Step 6: Scan Specific Azure Services
|
||||
|
||||
Run targeted scans for specific services:
|
||||
|
||||
```bash
|
||||
prowler azure --services storage network
|
||||
```
|
||||
|
||||
This focuses on:
|
||||
* Azure Storage accounts
|
||||
* Virtual networks
|
||||
* Network security groups
|
||||
|
||||
## Step 7: Analyze Azure Security Findings
|
||||
|
||||
Review Azure-specific security checks:
|
||||
|
||||
**Storage Account Security:**
|
||||
* Public blob access disabled
|
||||
* Secure transfer required (HTTPS)
|
||||
* Storage encryption enabled
|
||||
* Soft delete enabled
|
||||
|
||||
**Network Security:**
|
||||
* Network security groups properly configured
|
||||
* No overly permissive rules
|
||||
* DDoS protection enabled
|
||||
* Network watcher enabled
|
||||
|
||||
**Identity and Access:**
|
||||
* Multi-factor authentication enabled
|
||||
* Conditional access policies configured
|
||||
* Privileged identity management enabled
|
||||
|
||||
Open the HTML report:
|
||||
```bash
|
||||
open output/prowler-output-azure-*.html
|
||||
```
|
||||
|
||||
<Note>
|
||||
[Note: Screenshot of slide 50 showing Azure findings report - to be added]
|
||||
</Note>
|
||||
|
||||
## Step 8: Compare AWS and Azure Security Posture
|
||||
|
||||
If you completed Lab 1, compare security findings:
|
||||
|
||||
**AWS findings:**
|
||||
```bash
|
||||
cat output/prowler-output-aws-*.csv | wc -l
|
||||
```
|
||||
|
||||
**Azure findings:**
|
||||
```bash
|
||||
cat output/prowler-output-azure-*.csv | wc -l
|
||||
```
|
||||
|
||||
Key comparison metrics:
|
||||
* Total findings by severity
|
||||
* Service coverage
|
||||
* Compliance status
|
||||
* Resource exposure
|
||||
|
||||
## Step 9: Multi-Cloud Security Dashboard
|
||||
|
||||
Generate a combined security view:
|
||||
|
||||
Create a directory for multi-cloud reports:
|
||||
```bash
|
||||
mkdir -p multi-cloud-reports
|
||||
cp output/prowler-output-aws-*.json multi-cloud-reports/
|
||||
cp output/prowler-output-azure-*.json multi-cloud-reports/
|
||||
```
|
||||
|
||||
<Tip>
|
||||
Use Prowler Cloud or custom dashboards to visualize multi-cloud security posture in a unified interface.
|
||||
</Tip>
|
||||
|
||||
## Step 10: Azure-Specific Remediation
|
||||
|
||||
Example remediations for common Azure findings:
|
||||
|
||||
**Enable secure transfer for storage account:**
|
||||
```bash
|
||||
az storage account update \
|
||||
--name mystorageaccount \
|
||||
--resource-group myresourcegroup \
|
||||
--https-only true
|
||||
```
|
||||
|
||||
**Enable storage encryption:**
|
||||
```bash
|
||||
az storage account update \
|
||||
--name mystorageaccount \
|
||||
--resource-group myresourcegroup \
|
||||
--encryption-services blob
|
||||
```
|
||||
|
||||
**Disable public blob access:**
|
||||
```bash
|
||||
az storage account update \
|
||||
--name mystorageaccount \
|
||||
--resource-group myresourcegroup \
|
||||
--allow-blob-public-access false
|
||||
```
|
||||
|
||||
**Update network security group rule:**
|
||||
```bash
|
||||
az network nsg rule update \
|
||||
--resource-group myresourcegroup \
|
||||
--nsg-name mynsg \
|
||||
--name mynsgrule \
|
||||
--source-address-prefixes 10.0.0.0/16
|
||||
```
|
||||
|
||||
## Step 11: Scan Multiple Azure Subscriptions
|
||||
|
||||
Scan all subscriptions in your tenant:
|
||||
|
||||
```bash
|
||||
prowler azure --subscription-ids subscription-id-1 subscription-id-2
|
||||
```
|
||||
|
||||
Or scan all accessible subscriptions:
|
||||
```bash
|
||||
prowler azure --az-cli-auth
|
||||
```
|
||||
|
||||
<Note>
|
||||
[Note: Screenshot of slide 56 showing multi-subscription scan - to be added]
|
||||
</Note>
|
||||
|
||||
## Verification Steps
|
||||
|
||||
Confirm successful lab completion:
|
||||
|
||||
1. Azure CLI installed and authenticated
|
||||
2. First Azure scan completed successfully
|
||||
3. Azure security findings reviewed
|
||||
4. Service-specific scans executed
|
||||
5. Multi-cloud comparison performed
|
||||
6. Azure-specific remediations understood
|
||||
|
||||
## Expected Outcomes
|
||||
|
||||
After completing this lab, you should:
|
||||
|
||||
* Be able to authenticate Prowler with Azure
|
||||
* Understand Azure security checks
|
||||
* Know how to scan multiple subscriptions
|
||||
* Have compared security posture across AWS and Azure
|
||||
* Be familiar with Azure-specific remediation commands
|
||||
|
||||
## Common Azure Security Findings
|
||||
|
||||
**Storage Accounts:**
|
||||
* Public blob access enabled
|
||||
* Secure transfer (HTTPS) not required
|
||||
* Storage encryption disabled
|
||||
* Logging not configured
|
||||
|
||||
**Virtual Networks:**
|
||||
* Network security groups allow 0.0.0.0/0 access
|
||||
* DDoS protection not enabled
|
||||
* Network watcher not configured
|
||||
|
||||
**Identity:**
|
||||
* MFA not enabled for all users
|
||||
* Guest users have excessive permissions
|
||||
* Password policies are weak
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
**Issue:** Azure authentication fails
|
||||
* **Solution:** Run `az login` and ensure you have the correct subscription selected
|
||||
|
||||
**Issue:** Permission errors during scan
|
||||
* **Solution:** Ensure your account or service principal has Reader role at subscription level
|
||||
|
||||
**Issue:** Subscription not found
|
||||
* **Solution:** Verify subscription ID with `az account list` and check it's enabled
|
||||
|
||||
**Issue:** Slow scan performance
|
||||
* **Solution:** Use `--services` flag to scan specific services instead of all
|
||||
|
||||
## Next Steps
|
||||
|
||||
Continue to [Lab 5: Multi-Cloud Security with Prowler (GCP)](/workshop/lab-05-gcp-multicloud) to add Google Cloud Platform to your multi-cloud security monitoring.
|
||||
|
||||
## Additional Resources
|
||||
|
||||
* [Azure Getting Started Guide](/user-guide/providers/azure/getting-started-azure)
|
||||
* [Azure Authentication Methods](/user-guide/providers/azure/authentication)
|
||||
* [Create Prowler Service Principal](/user-guide/providers/azure/create-prowler-service-principal)
|
||||
* [Azure Subscriptions Management](/user-guide/providers/azure/subscriptions)
|
||||
@@ -0,0 +1,377 @@
|
||||
---
|
||||
title: "Lab 5: Multi-Cloud Security with Prowler (GCP)"
|
||||
description: "Complete your multi-cloud security coverage by adding Google Cloud Platform assessments"
|
||||
---
|
||||
|
||||
<Note>
|
||||
**Tags:** `workshop` `gcp` `multi-cloud` `intermediate` `authentication`
|
||||
</Note>
|
||||
|
||||
# Lab 5: Multi-Cloud Security with Prowler (GCP)
|
||||
|
||||
Learn to secure Google Cloud Platform environments and achieve comprehensive multi-cloud security coverage with Prowler.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
* Prowler CLI installed ([Lab 1](/workshop/lab-01-getting-started))
|
||||
* Active GCP project
|
||||
* Google Cloud SDK (gcloud) installed
|
||||
* GCP account with appropriate permissions (Viewer role minimum)
|
||||
* Basic understanding of GCP services
|
||||
|
||||
**Estimated Time:** 45 minutes
|
||||
|
||||
## Lab Objectives
|
||||
|
||||
By completing this lab, you will:
|
||||
|
||||
* Configure GCP authentication for Prowler
|
||||
* Run security assessments on GCP projects
|
||||
* Understand GCP-specific security checks
|
||||
* Achieve comprehensive multi-cloud security coverage (AWS, Azure, GCP)
|
||||
* Implement unified security policies across cloud providers
|
||||
|
||||
## Step 1: Install Google Cloud SDK
|
||||
|
||||
Install gcloud CLI if not already present:
|
||||
|
||||
**macOS:**
|
||||
```bash
|
||||
brew install google-cloud-sdk
|
||||
```
|
||||
|
||||
**Linux:**
|
||||
```bash
|
||||
curl https://sdk.cloud.google.com | bash
|
||||
exec -l $SHELL
|
||||
```
|
||||
|
||||
**Windows:**
|
||||
Download and install from: https://cloud.google.com/sdk/docs/install
|
||||
|
||||
Verify installation:
|
||||
```bash
|
||||
gcloud --version
|
||||
```
|
||||
|
||||
## Step 2: Authenticate to GCP
|
||||
|
||||
Initialize gcloud and authenticate:
|
||||
|
||||
```bash
|
||||
gcloud init
|
||||
```
|
||||
|
||||
This prompts you to:
|
||||
1. Log in to your Google account
|
||||
2. Select or create a GCP project
|
||||
3. Configure default region/zone (optional)
|
||||
|
||||
Verify authentication:
|
||||
```bash
|
||||
gcloud auth list
|
||||
```
|
||||
|
||||
Display active project:
|
||||
```bash
|
||||
gcloud config get-value project
|
||||
```
|
||||
|
||||
<Note>
|
||||
[Note: Screenshot of slide 60 showing GCP authentication - to be added]
|
||||
</Note>
|
||||
|
||||
## Step 3: Configure Application Default Credentials
|
||||
|
||||
Prowler uses Application Default Credentials (ADC):
|
||||
|
||||
```bash
|
||||
gcloud auth application-default login
|
||||
```
|
||||
|
||||
This creates credentials file at:
|
||||
* **Linux/macOS:** `~/.config/gcloud/application_default_credentials.json`
|
||||
* **Windows:** `%APPDATA%\gcloud\application_default_credentials.json`
|
||||
|
||||
## Step 4: Set Up Service Account (Optional)
|
||||
|
||||
For automated scans, create a service account:
|
||||
|
||||
```bash
|
||||
# Create service account
|
||||
gcloud iam service-accounts create prowler-scanner \
|
||||
--display-name="Prowler Security Scanner"
|
||||
|
||||
# Get project ID
|
||||
PROJECT_ID=$(gcloud config get-value project)
|
||||
|
||||
# Grant Viewer role
|
||||
gcloud projects add-iam-policy-binding $PROJECT_ID \
|
||||
--member="serviceAccount:prowler-scanner@${PROJECT_ID}.iam.gserviceaccount.com" \
|
||||
--role="roles/viewer"
|
||||
|
||||
# Generate key file
|
||||
gcloud iam service-accounts keys create ~/prowler-credentials.json \
|
||||
--iam-account=prowler-scanner@${PROJECT_ID}.iam.gserviceaccount.com
|
||||
```
|
||||
|
||||
<Warning>
|
||||
Store service account key files securely. These provide programmatic access to your GCP project.
|
||||
</Warning>
|
||||
|
||||
Use service account credentials:
|
||||
```bash
|
||||
export GOOGLE_APPLICATION_CREDENTIALS=~/prowler-credentials.json
|
||||
```
|
||||
|
||||
## Step 5: Run Your First GCP Scan
|
||||
|
||||
Execute Prowler against GCP:
|
||||
|
||||
```bash
|
||||
prowler gcp
|
||||
```
|
||||
|
||||
This command:
|
||||
* Uses Application Default Credentials (or service account)
|
||||
* Scans the active project
|
||||
* Runs all GCP security checks
|
||||
* Generates output in multiple formats
|
||||
|
||||
<Note>
|
||||
GCP scans typically take 5-10 minutes depending on resource count.
|
||||
</Note>
|
||||
|
||||
<Note>
|
||||
[Note: Screenshot of slide 65 showing GCP scan execution - to be added]
|
||||
</Note>
|
||||
|
||||
## Step 6: Scan Specific GCP Projects
|
||||
|
||||
Scan a specific project:
|
||||
|
||||
```bash
|
||||
prowler gcp --project-id my-project-id
|
||||
```
|
||||
|
||||
Scan multiple projects:
|
||||
```bash
|
||||
prowler gcp --project-id project-1 project-2 project-3
|
||||
```
|
||||
|
||||
## Step 7: Scan Specific GCP Services
|
||||
|
||||
Run targeted scans for specific services:
|
||||
|
||||
```bash
|
||||
prowler gcp --services storage compute iam
|
||||
```
|
||||
|
||||
This focuses on:
|
||||
* Cloud Storage buckets
|
||||
* Compute Engine instances
|
||||
* IAM policies and permissions
|
||||
|
||||
## Step 8: Analyze GCP Security Findings
|
||||
|
||||
Review GCP-specific security checks:
|
||||
|
||||
**Cloud Storage Security:**
|
||||
* Buckets not publicly accessible
|
||||
* Uniform bucket-level access enabled
|
||||
* Encryption at rest enabled
|
||||
* Versioning enabled
|
||||
|
||||
**Compute Engine Security:**
|
||||
* OS Login enabled
|
||||
* Serial port access disabled
|
||||
* Shielded VMs enabled
|
||||
* IP forwarding disabled
|
||||
|
||||
**IAM Security:**
|
||||
* Service accounts with minimal permissions
|
||||
* No primitive roles (Owner, Editor, Viewer) assigned to users
|
||||
* Service account keys rotated regularly
|
||||
* Cloud Identity-Aware Proxy (IAP) enabled
|
||||
|
||||
Open the HTML report:
|
||||
```bash
|
||||
open output/prowler-output-gcp-*.html
|
||||
```
|
||||
|
||||
<Note>
|
||||
[Note: Screenshot of slide 69 showing GCP findings report - to be added]
|
||||
</Note>
|
||||
|
||||
## Step 9: Multi-Cloud Security Overview
|
||||
|
||||
You now have security coverage across three major cloud providers:
|
||||
|
||||
Create a comprehensive multi-cloud report directory:
|
||||
|
||||
```bash
|
||||
mkdir -p multi-cloud-security-reports
|
||||
cp output/prowler-output-aws-*.json multi-cloud-security-reports/
|
||||
cp output/prowler-output-azure-*.json multi-cloud-security-reports/
|
||||
cp output/prowler-output-gcp-*.json multi-cloud-security-reports/
|
||||
```
|
||||
|
||||
Compare security posture metrics:
|
||||
|
||||
```bash
|
||||
# Count findings by provider
|
||||
echo "AWS findings:"
|
||||
jq '.findings | length' multi-cloud-security-reports/prowler-output-aws-*.json
|
||||
|
||||
echo "Azure findings:"
|
||||
jq '.findings | length' multi-cloud-security-reports/prowler-output-azure-*.json
|
||||
|
||||
echo "GCP findings:"
|
||||
jq '.findings | length' multi-cloud-security-reports/prowler-output-gcp-*.json
|
||||
```
|
||||
|
||||
## Step 10: GCP-Specific Remediation
|
||||
|
||||
Example remediations for common GCP findings:
|
||||
|
||||
**Enable uniform bucket-level access:**
|
||||
```bash
|
||||
gsutil uniformbucketlevelaccess set on gs://bucket-name
|
||||
```
|
||||
|
||||
**Disable public access to bucket:**
|
||||
```bash
|
||||
gsutil iam ch -d allUsers gs://bucket-name
|
||||
gsutil iam ch -d allAuthenticatedUsers gs://bucket-name
|
||||
```
|
||||
|
||||
**Enable OS Login on project:**
|
||||
```bash
|
||||
gcloud compute project-info add-metadata \
|
||||
--metadata enable-oslogin=TRUE
|
||||
```
|
||||
|
||||
**Disable serial port access:**
|
||||
```bash
|
||||
gcloud compute instances add-metadata instance-name \
|
||||
--metadata serial-port-enable=FALSE
|
||||
```
|
||||
|
||||
**Remove primitive role binding:**
|
||||
```bash
|
||||
gcloud projects remove-iam-policy-binding PROJECT_ID \
|
||||
--member='user:email@example.com' \
|
||||
--role='roles/editor'
|
||||
```
|
||||
|
||||
## Step 11: Scan GCP Organization
|
||||
|
||||
If you have organization-level access:
|
||||
|
||||
```bash
|
||||
prowler gcp --organization-id org-id
|
||||
```
|
||||
|
||||
This scans all projects within the organization.
|
||||
|
||||
<Tip>
|
||||
Organization-level scanning requires `resourcemanager.organizations.get` permission at the organization level.
|
||||
</Tip>
|
||||
|
||||
<Note>
|
||||
[Note: Screenshot of slide 74 showing organization scan - to be added]
|
||||
</Note>
|
||||
|
||||
## Step 12: Multi-Cloud Security Strategy
|
||||
|
||||
Establish consistent security controls across clouds:
|
||||
|
||||
**Identity and Access:**
|
||||
* Enforce MFA across all providers
|
||||
* Implement least privilege access
|
||||
* Regular access reviews
|
||||
* Centralized identity management
|
||||
|
||||
**Data Protection:**
|
||||
* Encryption at rest and in transit
|
||||
* Regular backups
|
||||
* Data retention policies
|
||||
* Access logging enabled
|
||||
|
||||
**Network Security:**
|
||||
* Zero-trust network architecture
|
||||
* Network segmentation
|
||||
* DDoS protection
|
||||
* Traffic inspection
|
||||
|
||||
**Monitoring and Compliance:**
|
||||
* Centralized logging
|
||||
* Security information and event management (SIEM)
|
||||
* Regular compliance scans
|
||||
* Automated remediation where possible
|
||||
|
||||
## Verification Steps
|
||||
|
||||
Confirm successful lab completion:
|
||||
|
||||
1. Google Cloud SDK installed and authenticated
|
||||
2. First GCP scan completed successfully
|
||||
3. GCP security findings reviewed
|
||||
4. Service-specific scans executed
|
||||
5. Multi-cloud reports collected (AWS, Azure, GCP)
|
||||
6. GCP-specific remediations understood
|
||||
|
||||
## Expected Outcomes
|
||||
|
||||
After completing this lab, you should:
|
||||
|
||||
* Be able to authenticate Prowler with GCP
|
||||
* Understand GCP security checks
|
||||
* Know how to scan multiple projects and organizations
|
||||
* Have achieved multi-cloud security coverage
|
||||
* Be familiar with GCP-specific remediation commands
|
||||
|
||||
## Common GCP Security Findings
|
||||
|
||||
**Cloud Storage:**
|
||||
* Buckets with public access
|
||||
* Uniform bucket-level access not enabled
|
||||
* Versioning disabled
|
||||
* Logging not configured
|
||||
|
||||
**Compute Engine:**
|
||||
* OS Login not enabled
|
||||
* Legacy metadata endpoints enabled
|
||||
* Serial port access enabled
|
||||
* IP forwarding enabled on instances
|
||||
|
||||
**IAM:**
|
||||
* Primitive roles assigned to users
|
||||
* Service account keys not rotated
|
||||
* Over-permissive service accounts
|
||||
* No organization policies enforced
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
**Issue:** GCP authentication fails
|
||||
* **Solution:** Run `gcloud auth application-default login` and ensure project is set
|
||||
|
||||
**Issue:** Permission errors during scan
|
||||
* **Solution:** Ensure account has Viewer role at project or organization level
|
||||
|
||||
**Issue:** Project not found
|
||||
* **Solution:** Verify project ID with `gcloud projects list` and check it's active
|
||||
|
||||
**Issue:** API not enabled errors
|
||||
* **Solution:** Enable required APIs: `gcloud services enable cloudresourcemanager.googleapis.com`
|
||||
|
||||
## Next Steps
|
||||
|
||||
Continue to [Lab 6: Compliance as Code with Prowler](/workshop/lab-06-compliance-as-code) to learn how to automate compliance reporting across all cloud providers.
|
||||
|
||||
## Additional Resources
|
||||
|
||||
* [GCP Getting Started Guide](/user-guide/providers/gcp/getting-started-gcp)
|
||||
* [GCP Authentication Methods](/user-guide/providers/gcp/authentication)
|
||||
* [GCP Projects Management](/user-guide/providers/gcp/projects)
|
||||
* [GCP Organization Scanning](/user-guide/providers/gcp/organization)
|
||||
@@ -0,0 +1,465 @@
|
||||
---
|
||||
title: "Lab 6: Compliance as Code with Prowler"
|
||||
description: "Automate compliance reporting and validation against industry standards and regulatory frameworks"
|
||||
---
|
||||
|
||||
<Note>
|
||||
**Tags:** `workshop` `aws` `compliance` `intermediate` `automation` `frameworks`
|
||||
</Note>
|
||||
|
||||
# Lab 6: Compliance as Code with Prowler
|
||||
|
||||
Learn to automate compliance validation and reporting against industry standards such as CIS, PCI-DSS, HIPAA, and custom compliance frameworks.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
* Completion of [Lab 1: Getting Started with Prowler CLI](/workshop/lab-01-getting-started)
|
||||
* AWS account with resources
|
||||
* Prowler CLI installed and configured
|
||||
* Understanding of compliance frameworks (CIS, PCI-DSS, HIPAA)
|
||||
|
||||
**Estimated Time:** 50 minutes
|
||||
|
||||
## Lab Objectives
|
||||
|
||||
By completing this lab, you will:
|
||||
|
||||
* Understand compliance frameworks in Prowler
|
||||
* Generate compliance reports for industry standards
|
||||
* Validate compliance status programmatically
|
||||
* Create custom compliance frameworks
|
||||
* Automate compliance reporting in CI/CD pipelines
|
||||
|
||||
## Step 1: List Available Compliance Frameworks
|
||||
|
||||
View all supported compliance frameworks:
|
||||
|
||||
```bash
|
||||
prowler aws --list-compliance
|
||||
```
|
||||
|
||||
This displays frameworks such as:
|
||||
* CIS AWS Foundations Benchmark (multiple versions)
|
||||
* PCI-DSS v4.0
|
||||
* HIPAA
|
||||
* SOC2
|
||||
* GDPR
|
||||
* ISO 27001
|
||||
* NIST 800-53
|
||||
* AWS Foundational Security Best Practices
|
||||
* Custom frameworks
|
||||
|
||||
<Note>
|
||||
[Note: Screenshot of slide 78 showing compliance frameworks list - to be added]
|
||||
</Note>
|
||||
|
||||
## Step 2: Run CIS Benchmark Compliance Scan
|
||||
|
||||
Execute a CIS AWS Foundations Benchmark scan:
|
||||
|
||||
```bash
|
||||
prowler aws --compliance cis_2.0_aws
|
||||
```
|
||||
|
||||
This command:
|
||||
* Runs only checks mapped to CIS Benchmark v2.0
|
||||
* Generates a compliance report
|
||||
* Shows compliance percentage
|
||||
* Identifies non-compliant controls
|
||||
|
||||
Review compliance summary:
|
||||
```bash
|
||||
open output/compliance/prowler-compliance-cis_2.0_aws-*.html
|
||||
```
|
||||
|
||||
<Note>
|
||||
[Note: Screenshot of slide 80 showing CIS compliance report - to be added]
|
||||
</Note>
|
||||
|
||||
## Step 3: Analyze Compliance Requirements
|
||||
|
||||
Understanding compliance report structure:
|
||||
|
||||
**Requirement ID:** Control identifier (e.g., 1.1, 1.2)
|
||||
**Requirement Description:** What the control validates
|
||||
**Status:** PASS or FAIL
|
||||
**Related Checks:** Prowler checks that map to this requirement
|
||||
**Resources Affected:** Specific resources that failed
|
||||
|
||||
Example CIS requirement:
|
||||
|
||||
```
|
||||
ID: 1.4
|
||||
Description: Ensure no root account access key exists
|
||||
Status: FAIL
|
||||
Checks: iam_root_user_no_access_keys
|
||||
Resources: Root account has 1 active access key
|
||||
```
|
||||
|
||||
## Step 4: Generate Multiple Compliance Reports
|
||||
|
||||
Run scans for multiple frameworks:
|
||||
|
||||
```bash
|
||||
prowler aws --compliance cis_2.0_aws pci_dss_v4.0_aws hipaa_aws
|
||||
```
|
||||
|
||||
This generates three separate compliance reports:
|
||||
* `prowler-compliance-cis_2.0_aws-*.html`
|
||||
* `prowler-compliance-pci_dss_v4.0_aws-*.html`
|
||||
* `prowler-compliance-hipaa_aws-*.html`
|
||||
|
||||
Compare compliance posture across frameworks:
|
||||
```bash
|
||||
grep "Compliance Status" output/compliance/*.html
|
||||
```
|
||||
|
||||
## Step 5: Export Compliance Data
|
||||
|
||||
Export compliance results to JSON for automation:
|
||||
|
||||
```bash
|
||||
prowler aws --compliance cis_2.0_aws -o json-ocsf
|
||||
```
|
||||
|
||||
The JSON output includes:
|
||||
* Compliance score (percentage)
|
||||
* Passed requirements
|
||||
* Failed requirements
|
||||
* Resource-level details
|
||||
* Remediation guidance
|
||||
|
||||
Query compliance status programmatically:
|
||||
```bash
|
||||
jq '.compliance.cis_2.0_aws.score' output/prowler-output-*.json-ocsf
|
||||
```
|
||||
|
||||
<Note>
|
||||
[Note: Screenshot of slide 84 showing JSON compliance output - to be added]
|
||||
</Note>
|
||||
|
||||
## Step 6: Create a Custom Compliance Framework
|
||||
|
||||
Create a custom framework for organization-specific requirements:
|
||||
|
||||
Create `custom_compliance.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"Framework": "custom_security_baseline",
|
||||
"Version": "1.0",
|
||||
"Provider": "aws",
|
||||
"Description": "Organization Security Baseline Requirements",
|
||||
"Requirements": [
|
||||
{
|
||||
"Id": "1.1",
|
||||
"Description": "S3 buckets must have encryption enabled",
|
||||
"Attributes": [
|
||||
{
|
||||
"Section": "Data Protection",
|
||||
"SubSection": "Encryption at Rest",
|
||||
"Type": "automated",
|
||||
"Service": "s3"
|
||||
}
|
||||
],
|
||||
"Checks": [
|
||||
"s3_bucket_default_encryption",
|
||||
"s3_bucket_secure_transport_policy"
|
||||
]
|
||||
},
|
||||
{
|
||||
"Id": "1.2",
|
||||
"Description": "CloudTrail must be enabled in all regions",
|
||||
"Attributes": [
|
||||
{
|
||||
"Section": "Logging and Monitoring",
|
||||
"SubSection": "Audit Logging",
|
||||
"Type": "automated",
|
||||
"Service": "cloudtrail"
|
||||
}
|
||||
],
|
||||
"Checks": [
|
||||
"cloudtrail_multi_region_enabled",
|
||||
"cloudtrail_log_file_validation_enabled"
|
||||
]
|
||||
},
|
||||
{
|
||||
"Id": "2.1",
|
||||
"Description": "IAM users must have MFA enabled",
|
||||
"Attributes": [
|
||||
{
|
||||
"Section": "Identity and Access Management",
|
||||
"SubSection": "Multi-Factor Authentication",
|
||||
"Type": "automated",
|
||||
"Service": "iam"
|
||||
}
|
||||
],
|
||||
"Checks": [
|
||||
"iam_user_mfa_enabled_console_access",
|
||||
"iam_root_mfa_enabled"
|
||||
]
|
||||
},
|
||||
{
|
||||
"Id": "3.1",
|
||||
"Description": "Security groups must not allow unrestricted access",
|
||||
"Attributes": [
|
||||
{
|
||||
"Section": "Network Security",
|
||||
"SubSection": "Firewall Rules",
|
||||
"Type": "automated",
|
||||
"Service": "ec2"
|
||||
}
|
||||
],
|
||||
"Checks": [
|
||||
"ec2_securitygroup_allow_ingress_from_internet_to_tcp_port_22",
|
||||
"ec2_securitygroup_allow_ingress_from_internet_to_tcp_port_3389"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Save to `prowler/compliance/aws/`:
|
||||
```bash
|
||||
cp custom_compliance.json ~/.prowler/compliance/aws/
|
||||
```
|
||||
|
||||
## Step 7: Run Custom Compliance Framework
|
||||
|
||||
Execute scan against custom framework:
|
||||
|
||||
```bash
|
||||
prowler aws --compliance-framework custom_compliance.json
|
||||
```
|
||||
|
||||
Or if placed in Prowler's compliance directory:
|
||||
```bash
|
||||
prowler aws --compliance custom_security_baseline
|
||||
```
|
||||
|
||||
Review custom compliance report:
|
||||
```bash
|
||||
open output/compliance/prowler-compliance-custom_security_baseline-*.html
|
||||
```
|
||||
|
||||
<Note>
|
||||
[Note: Screenshot of slide 88 showing custom compliance report - to be added]
|
||||
</Note>
|
||||
|
||||
## Step 8: Compliance Reporting for Audits
|
||||
|
||||
Generate audit-ready compliance reports:
|
||||
|
||||
```bash
|
||||
prowler aws \
|
||||
--compliance cis_2.0_aws \
|
||||
-o html csv json \
|
||||
--output-directory ./audit-reports-$(date +%Y%m%d)
|
||||
```
|
||||
|
||||
This creates:
|
||||
* HTML report for human review
|
||||
* CSV for spreadsheet analysis
|
||||
* JSON for programmatic processing
|
||||
|
||||
Package for auditors:
|
||||
```bash
|
||||
tar -czf compliance-audit-$(date +%Y%m%d).tar.gz audit-reports-*
|
||||
```
|
||||
|
||||
## Step 9: Automate Compliance Validation
|
||||
|
||||
Create a compliance validation script:
|
||||
|
||||
Create `compliance-check.sh`:
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
|
||||
# Configuration
|
||||
COMPLIANCE_FRAMEWORK="cis_2.0_aws"
|
||||
REQUIRED_SCORE=85
|
||||
OUTPUT_DIR="./compliance-reports"
|
||||
|
||||
# Run Prowler
|
||||
prowler aws \
|
||||
--compliance $COMPLIANCE_FRAMEWORK \
|
||||
-o json \
|
||||
--output-directory $OUTPUT_DIR
|
||||
|
||||
# Extract compliance score
|
||||
SCORE=$(jq -r ".compliance.${COMPLIANCE_FRAMEWORK}.score" \
|
||||
$OUTPUT_DIR/prowler-output-*.json | head -1)
|
||||
|
||||
echo "Compliance Score: ${SCORE}%"
|
||||
|
||||
# Validate compliance threshold
|
||||
if (( $(echo "$SCORE >= $REQUIRED_SCORE" | bc -l) )); then
|
||||
echo "✓ Compliance check PASSED (score: ${SCORE}% >= ${REQUIRED_SCORE}%)"
|
||||
exit 0
|
||||
else
|
||||
echo "✗ Compliance check FAILED (score: ${SCORE}% < ${REQUIRED_SCORE}%)"
|
||||
exit 1
|
||||
fi
|
||||
```
|
||||
|
||||
Make executable:
|
||||
```bash
|
||||
chmod +x compliance-check.sh
|
||||
```
|
||||
|
||||
Run validation:
|
||||
```bash
|
||||
./compliance-check.sh
|
||||
```
|
||||
|
||||
## Step 10: Integrate with CI/CD Pipeline
|
||||
|
||||
Example GitHub Actions workflow:
|
||||
|
||||
Create `.github/workflows/compliance-check.yml`:
|
||||
|
||||
```yaml
|
||||
name: Compliance Validation
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: '0 0 * * *' # Daily at midnight
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
prowler-compliance:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: '3.11'
|
||||
|
||||
- name: Install Prowler
|
||||
run: pip install prowler
|
||||
|
||||
- name: Configure AWS credentials
|
||||
uses: aws-actions/configure-aws-credentials@v2
|
||||
with:
|
||||
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
|
||||
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
|
||||
aws-region: us-east-1
|
||||
|
||||
- name: Run compliance scan
|
||||
run: |
|
||||
prowler aws \
|
||||
--compliance cis_2.0_aws \
|
||||
-o html json \
|
||||
--output-directory ./reports
|
||||
|
||||
- name: Upload compliance reports
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: compliance-reports
|
||||
path: ./reports/
|
||||
|
||||
- name: Check compliance threshold
|
||||
run: |
|
||||
SCORE=$(jq -r '.compliance.cis_2.0_aws.score' reports/prowler-output-*.json)
|
||||
if (( $(echo "$SCORE < 85" | bc -l) )); then
|
||||
echo "Compliance score ${SCORE}% is below threshold"
|
||||
exit 1
|
||||
fi
|
||||
```
|
||||
|
||||
<Note>
|
||||
[Note: Screenshot of slide 92 showing CI/CD integration - to be added]
|
||||
</Note>
|
||||
|
||||
## Step 11: Continuous Compliance Monitoring
|
||||
|
||||
Implement continuous compliance monitoring:
|
||||
|
||||
**Daily Scans:**
|
||||
* Schedule automated scans
|
||||
* Track compliance trends over time
|
||||
* Alert on compliance score drops
|
||||
|
||||
**Drift Detection:**
|
||||
* Compare current state vs. baseline
|
||||
* Identify new non-compliant resources
|
||||
* Generate remediation tickets automatically
|
||||
|
||||
**Compliance Dashboard:**
|
||||
* Visualize compliance status
|
||||
* Track remediation progress
|
||||
* Generate executive reports
|
||||
|
||||
## Verification Steps
|
||||
|
||||
Confirm successful lab completion:
|
||||
|
||||
1. Listed available compliance frameworks
|
||||
2. Generated CIS compliance report
|
||||
3. Created multiple framework reports
|
||||
4. Built custom compliance framework
|
||||
5. Automated compliance validation
|
||||
6. Integrated compliance checks in CI/CD
|
||||
|
||||
## Expected Outcomes
|
||||
|
||||
After completing this lab, you should:
|
||||
|
||||
* Understand Prowler compliance capabilities
|
||||
* Be able to generate compliance reports
|
||||
* Know how to create custom frameworks
|
||||
* Have automated compliance validation
|
||||
* Be ready for audit processes
|
||||
|
||||
## Compliance Framework Mapping
|
||||
|
||||
Common frameworks supported:
|
||||
|
||||
**AWS:**
|
||||
* CIS AWS Foundations Benchmark v1.4, v1.5, v2.0, v3.0
|
||||
* AWS Foundational Security Best Practices
|
||||
* PCI-DSS v4.0
|
||||
* HIPAA
|
||||
* SOC2
|
||||
* GDPR
|
||||
* ISO 27001
|
||||
* NIST 800-53
|
||||
* FedRAMP
|
||||
* ENS (Spanish National Security Scheme)
|
||||
|
||||
**Azure:**
|
||||
* CIS Microsoft Azure Foundations Benchmark
|
||||
* Azure Security Benchmark
|
||||
|
||||
**GCP:**
|
||||
* CIS Google Cloud Platform Foundation Benchmark
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
**Issue:** Compliance framework not found
|
||||
* **Solution:** Use `--list-compliance` to see exact framework names
|
||||
|
||||
**Issue:** Low compliance score
|
||||
* **Solution:** Review failed checks and prioritize remediation by severity
|
||||
|
||||
**Issue:** Missing compliance report
|
||||
* **Solution:** Check `output/compliance/` directory for framework-specific reports
|
||||
|
||||
**Issue:** Custom framework not loading
|
||||
* **Solution:** Validate JSON syntax and ensure file is in correct directory
|
||||
|
||||
## Next Steps
|
||||
|
||||
Continue to [Lab 7: Integrations with Prowler](/workshop/lab-07-integrations) to learn how to integrate Prowler with AWS Security Hub and other security tools.
|
||||
|
||||
## Additional Resources
|
||||
|
||||
* [Compliance Reporting Guide](/user-guide/cli/tutorials/compliance)
|
||||
* [Compliance Frameworks Documentation](/user-guide/cli/tutorials/compliance)
|
||||
* [Custom Compliance Framework Guide](/developer-guide/security-compliance-framework)
|
||||
* [Prowler Hub Compliance Frameworks](https://hub.prowler.com/compliance)
|
||||
@@ -0,0 +1,425 @@
|
||||
---
|
||||
title: "Lab 7: Integrations with Prowler"
|
||||
description: "Integrate Prowler findings with AWS Security Hub and other security tools for centralized security management"
|
||||
---
|
||||
|
||||
<Note>
|
||||
**Tags:** `workshop` `aws` `integrations` `intermediate` `security-hub` `automation`
|
||||
</Note>
|
||||
|
||||
# Lab 7: Integrations with Prowler
|
||||
|
||||
Learn to integrate Prowler with AWS Security Hub and other security tools to centralize security findings and automate remediation workflows.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
* Completion of [Lab 1: Getting Started with Prowler CLI](/workshop/lab-01-getting-started)
|
||||
* AWS account with Security Hub enabled
|
||||
* IAM permissions for Security Hub operations
|
||||
* Prowler CLI installed and configured
|
||||
* Basic understanding of AWS Security Hub
|
||||
|
||||
**Estimated Time:** 45 minutes
|
||||
|
||||
## Lab Objectives
|
||||
|
||||
By completing this lab, you will:
|
||||
|
||||
* Enable AWS Security Hub integration
|
||||
* Send Prowler findings to Security Hub
|
||||
* Understand finding formats and mapping
|
||||
* Configure automated finding synchronization
|
||||
* Integrate with third-party security tools
|
||||
* Implement centralized security dashboards
|
||||
|
||||
## Step 1: Enable AWS Security Hub
|
||||
|
||||
Enable Security Hub in your AWS account:
|
||||
|
||||
**Via AWS Console:**
|
||||
1. Navigate to AWS Security Hub
|
||||
2. Click "Go to Security Hub"
|
||||
3. Click "Enable Security Hub"
|
||||
|
||||
**Via AWS CLI:**
|
||||
```bash
|
||||
aws securityhub enable-security-hub
|
||||
```
|
||||
|
||||
Verify Security Hub is enabled:
|
||||
```bash
|
||||
aws securityhub get-enabled-standards
|
||||
```
|
||||
|
||||
<Note>
|
||||
[Note: Screenshot of slide 96 showing Security Hub enablement - to be added]
|
||||
</Note>
|
||||
|
||||
## Step 2: Configure IAM Permissions
|
||||
|
||||
Ensure your IAM role/user has Security Hub permissions:
|
||||
|
||||
Required permissions:
|
||||
```json
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"securityhub:BatchImportFindings",
|
||||
"securityhub:GetFindings"
|
||||
],
|
||||
"Resource": "*"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Create and attach policy:
|
||||
```bash
|
||||
aws iam create-policy \
|
||||
--policy-name ProwlerSecurityHubIntegration \
|
||||
--policy-document file://securityhub-policy.json
|
||||
|
||||
aws iam attach-user-policy \
|
||||
--user-name prowler-user \
|
||||
--policy-arn arn:aws:iam::ACCOUNT_ID:policy/ProwlerSecurityHubIntegration
|
||||
```
|
||||
|
||||
## Step 3: Run Prowler with Security Hub Integration
|
||||
|
||||
Execute Prowler and send findings to Security Hub:
|
||||
|
||||
```bash
|
||||
prowler aws --security-hub
|
||||
```
|
||||
|
||||
This command:
|
||||
* Runs all security checks
|
||||
* Transforms findings to AWS Security Finding Format (ASFF)
|
||||
* Sends findings to Security Hub via `BatchImportFindings` API
|
||||
* Generates local reports
|
||||
|
||||
<Warning>
|
||||
Security Hub has API rate limits. For large environments, findings are sent in batches automatically.
|
||||
</Warning>
|
||||
|
||||
<Note>
|
||||
[Note: Screenshot of slide 99 showing Prowler sending findings to Security Hub - to be added]
|
||||
</Note>
|
||||
|
||||
## Step 4: View Findings in Security Hub
|
||||
|
||||
Navigate to AWS Security Hub console and review Prowler findings:
|
||||
|
||||
**Filter by Product:**
|
||||
1. Go to "Findings" in Security Hub
|
||||
2. Add filter: `Product name is Prowler`
|
||||
3. Review findings by severity
|
||||
|
||||
**View Finding Details:**
|
||||
* Severity (CRITICAL, HIGH, MEDIUM, LOW, INFORMATIONAL)
|
||||
* Affected resource
|
||||
* Compliance framework mapping
|
||||
* Remediation guidance
|
||||
* Workflow status
|
||||
|
||||
<Note>
|
||||
[Note: Screenshot of slide 101 showing Security Hub findings view - to be added]
|
||||
</Note>
|
||||
|
||||
## Step 5: Understanding ASFF Mapping
|
||||
|
||||
Prowler findings are mapped to AWS Security Finding Format:
|
||||
|
||||
**Prowler Status → Security Hub Compliance Status:**
|
||||
* PASS → PASSED
|
||||
* FAIL → FAILED
|
||||
* MANUAL → NOT_AVAILABLE
|
||||
|
||||
**Prowler Severity → Security Hub Severity:**
|
||||
* critical → CRITICAL (90-100)
|
||||
* high → HIGH (70-89)
|
||||
* medium → MEDIUM (40-69)
|
||||
* low → LOW (1-39)
|
||||
* informational → INFORMATIONAL (0)
|
||||
|
||||
Example ASFF finding structure:
|
||||
```json
|
||||
{
|
||||
"SchemaVersion": "2018-10-08",
|
||||
"Id": "prowler-aws/account/region/check/resource",
|
||||
"ProductArn": "arn:aws:securityhub:region::product/prowler/prowler",
|
||||
"GeneratorId": "prowler-check-id",
|
||||
"AwsAccountId": "123456789012",
|
||||
"Types": ["Software and Configuration Checks"],
|
||||
"CreatedAt": "2024-01-01T00:00:00.000Z",
|
||||
"UpdatedAt": "2024-01-01T00:00:00.000Z",
|
||||
"Severity": {
|
||||
"Label": "HIGH"
|
||||
},
|
||||
"Title": "Check title",
|
||||
"Description": "Check description",
|
||||
"Resources": [
|
||||
{
|
||||
"Type": "AwsS3Bucket",
|
||||
"Id": "arn:aws:s3:::bucket-name"
|
||||
}
|
||||
],
|
||||
"Compliance": {
|
||||
"Status": "FAILED"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Step 6: Update Existing Findings
|
||||
|
||||
Run subsequent scans to update Security Hub findings:
|
||||
|
||||
```bash
|
||||
prowler aws --security-hub
|
||||
```
|
||||
|
||||
Prowler automatically:
|
||||
* Updates existing findings (same resource, same check)
|
||||
* Marks remediated issues as PASSED
|
||||
* Creates new findings for new resources
|
||||
* Archives findings for deleted resources
|
||||
|
||||
## Step 7: Regional Security Hub Integration
|
||||
|
||||
Send findings to Security Hub in specific regions:
|
||||
|
||||
```bash
|
||||
prowler aws --security-hub --region us-east-1 us-west-2
|
||||
```
|
||||
|
||||
Or enable aggregation in a single region:
|
||||
|
||||
```bash
|
||||
# Configure finding aggregator in Security Hub
|
||||
aws securityhub create-finding-aggregator \
|
||||
--region-linking-mode ALL_REGIONS
|
||||
```
|
||||
|
||||
<Tip>
|
||||
Use Security Hub finding aggregation to centralize findings from multiple regions in a single dashboard.
|
||||
</Tip>
|
||||
|
||||
## Step 8: Filter Findings Sent to Security Hub
|
||||
|
||||
Send only critical and high-severity findings:
|
||||
|
||||
```bash
|
||||
prowler aws --security-hub --severity critical high
|
||||
```
|
||||
|
||||
Send findings for specific compliance frameworks:
|
||||
|
||||
```bash
|
||||
prowler aws --security-hub --compliance cis_2.0_aws
|
||||
```
|
||||
|
||||
## Step 9: Integrate with S3 for Long-Term Storage
|
||||
|
||||
Store Prowler reports in S3 alongside Security Hub integration:
|
||||
|
||||
```bash
|
||||
prowler aws \
|
||||
--security-hub \
|
||||
-o html json csv \
|
||||
--output-bucket-no-assume s3://my-security-reports-bucket
|
||||
```
|
||||
|
||||
This enables:
|
||||
* Long-term retention of historical reports
|
||||
* Compliance audit trails
|
||||
* Trend analysis over time
|
||||
* Cost-effective storage
|
||||
|
||||
Configure S3 bucket lifecycle policies:
|
||||
```bash
|
||||
aws s3api put-bucket-lifecycle-configuration \
|
||||
--bucket my-security-reports-bucket \
|
||||
--lifecycle-configuration file://lifecycle.json
|
||||
```
|
||||
|
||||
`lifecycle.json`:
|
||||
```json
|
||||
{
|
||||
"Rules": [
|
||||
{
|
||||
"Id": "ArchiveOldReports",
|
||||
"Status": "Enabled",
|
||||
"Transitions": [
|
||||
{
|
||||
"Days": 90,
|
||||
"StorageClass": "GLACIER"
|
||||
}
|
||||
],
|
||||
"Expiration": {
|
||||
"Days": 365
|
||||
},
|
||||
"Filter": {
|
||||
"Prefix": "prowler-reports/"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
<Note>
|
||||
[Note: Screenshot of slide 107 showing S3 integration - to be added]
|
||||
</Note>
|
||||
|
||||
## Step 10: Integrate with Third-Party Tools
|
||||
|
||||
**Send to Slack:**
|
||||
```bash
|
||||
prowler aws --security-hub | \
|
||||
jq -r '.findings[] | select(.status=="FAIL" and .severity=="critical")' | \
|
||||
curl -X POST -H 'Content-type: application/json' \
|
||||
--data @- https://hooks.slack.com/services/YOUR/WEBHOOK/URL
|
||||
```
|
||||
|
||||
**Send to Jira:**
|
||||
Create Jira tickets for critical findings using Jira API:
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
JIRA_URL="https://your-domain.atlassian.net"
|
||||
JIRA_API_TOKEN="your-api-token"
|
||||
JIRA_PROJECT="SEC"
|
||||
|
||||
# Extract critical findings
|
||||
FINDINGS=$(prowler aws -o json-ocsf | \
|
||||
jq '.findings[] | select(.status=="FAIL" and .severity=="critical")')
|
||||
|
||||
# Create Jira tickets
|
||||
echo "$FINDINGS" | jq -c '.' | while read finding; do
|
||||
TITLE=$(echo $finding | jq -r '.check_title')
|
||||
DESCRIPTION=$(echo $finding | jq -r '.status_extended')
|
||||
|
||||
curl -X POST "$JIRA_URL/rest/api/2/issue" \
|
||||
-H "Authorization: Bearer $JIRA_API_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{
|
||||
\"fields\": {
|
||||
\"project\": {\"key\": \"$JIRA_PROJECT\"},
|
||||
\"summary\": \"$TITLE\",
|
||||
\"description\": \"$DESCRIPTION\",
|
||||
\"issuetype\": {\"name\": \"Task\"}
|
||||
}
|
||||
}"
|
||||
done
|
||||
```
|
||||
|
||||
**Send to Splunk:**
|
||||
```bash
|
||||
prowler aws -o json-ocsf | \
|
||||
curl -k https://splunk-server:8088/services/collector/event \
|
||||
-H "Authorization: Splunk YOUR-HEC-TOKEN" \
|
||||
-d @-
|
||||
```
|
||||
|
||||
## Step 11: Automate Security Hub Updates
|
||||
|
||||
Create a Lambda function to run Prowler periodically:
|
||||
|
||||
**Lambda Function (Python):**
|
||||
```python
|
||||
import subprocess
|
||||
import boto3
|
||||
|
||||
def lambda_handler(event, context):
|
||||
# Run Prowler with Security Hub integration
|
||||
result = subprocess.run(
|
||||
['prowler', 'aws', '--security-hub'],
|
||||
capture_output=True,
|
||||
text=True
|
||||
)
|
||||
|
||||
return {
|
||||
'statusCode': 200,
|
||||
'body': f'Prowler scan completed. Output: {result.stdout}'
|
||||
}
|
||||
```
|
||||
|
||||
**Schedule with EventBridge:**
|
||||
```bash
|
||||
aws events put-rule \
|
||||
--name DailyProwlerScan \
|
||||
--schedule-expression "cron(0 2 * * ? *)"
|
||||
|
||||
aws events put-targets \
|
||||
--rule DailyProwlerScan \
|
||||
--targets "Id"="1","Arn"="arn:aws:lambda:region:account:function:ProwlerScanFunction"
|
||||
```
|
||||
|
||||
<Note>
|
||||
[Note: Screenshot of slide 111 showing automated integration - to be added]
|
||||
</Note>
|
||||
|
||||
## Verification Steps
|
||||
|
||||
Confirm successful lab completion:
|
||||
|
||||
1. AWS Security Hub enabled
|
||||
2. Prowler findings sent to Security Hub
|
||||
3. Findings visible in Security Hub console
|
||||
4. Subsequent scans update existing findings
|
||||
5. S3 integration configured for report storage
|
||||
6. Third-party integration examples tested
|
||||
|
||||
## Expected Outcomes
|
||||
|
||||
After completing this lab, you should:
|
||||
|
||||
* Understand Security Hub integration
|
||||
* Know how to send findings to Security Hub
|
||||
* Be able to configure automated synchronization
|
||||
* Have integrated with S3 for storage
|
||||
* Be familiar with third-party tool integrations
|
||||
|
||||
## Security Hub Benefits
|
||||
|
||||
**Centralized Security:**
|
||||
* Aggregate findings from multiple tools
|
||||
* Unified view across AWS accounts and regions
|
||||
* Compliance dashboard
|
||||
|
||||
**Automated Workflows:**
|
||||
* Trigger remediation workflows
|
||||
* Create incidents automatically
|
||||
* Integrate with SIEM tools
|
||||
|
||||
**Prioritization:**
|
||||
* Filter by severity and compliance status
|
||||
* Track remediation progress
|
||||
* Generate executive reports
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
**Issue:** Security Hub not enabled
|
||||
* **Solution:** Run `aws securityhub enable-security-hub` to enable
|
||||
|
||||
**Issue:** Permission denied sending findings
|
||||
* **Solution:** Ensure IAM role has `securityhub:BatchImportFindings` permission
|
||||
|
||||
**Issue:** Findings not appearing in Security Hub
|
||||
* **Solution:** Check Prowler output for errors, verify region configuration
|
||||
|
||||
**Issue:** Rate limit errors
|
||||
* **Solution:** Prowler batches findings automatically; retry if transient failures occur
|
||||
|
||||
## Next Steps
|
||||
|
||||
Continue to [Lab 8: Prowler SaaS Platform](/workshop/lab-08-prowler-saas) to explore the managed Prowler Cloud platform with advanced features.
|
||||
|
||||
## Additional Resources
|
||||
|
||||
* [Security Hub Integration Guide](/user-guide/providers/aws/securityhub)
|
||||
* [S3 Integration Guide](/user-guide/providers/aws/s3)
|
||||
* [Integrations Documentation](/user-guide/cli/tutorials/integrations)
|
||||
* [AWS Security Hub Documentation](https://docs.aws.amazon.com/securityhub/)
|
||||
@@ -0,0 +1,440 @@
|
||||
---
|
||||
title: "Lab 8: Prowler SaaS Platform"
|
||||
description: "Explore Prowler Cloud's managed platform with advanced features, team collaboration, and continuous monitoring"
|
||||
---
|
||||
|
||||
<Note>
|
||||
**Tags:** `workshop` `prowler-cloud` `saas` `intermediate` `platform` `collaboration`
|
||||
</Note>
|
||||
|
||||
# Lab 8: Prowler SaaS Platform
|
||||
|
||||
Learn to use Prowler Cloud, the managed SaaS platform that provides advanced security monitoring, team collaboration, compliance dashboards, and AI-powered security insights.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
* Completion of previous labs (recommended but not required)
|
||||
* Prowler Cloud account (free trial available)
|
||||
* Cloud provider accounts (AWS, Azure, or GCP)
|
||||
* Basic understanding of Prowler concepts
|
||||
|
||||
**Estimated Time:** 60 minutes
|
||||
|
||||
## Lab Objectives
|
||||
|
||||
By completing this lab, you will:
|
||||
|
||||
* Set up Prowler Cloud account
|
||||
* Connect cloud providers to Prowler Cloud
|
||||
* Navigate the Prowler Cloud interface
|
||||
* Use team collaboration features
|
||||
* Leverage AI-powered security insights
|
||||
* Configure continuous monitoring and alerts
|
||||
* Generate executive compliance reports
|
||||
|
||||
## Step 1: Create Prowler Cloud Account
|
||||
|
||||
Sign up for Prowler Cloud:
|
||||
|
||||
1. Visit [https://cloud.prowler.com](https://cloud.prowler.com)
|
||||
2. Click "Start Free Trial"
|
||||
3. Choose authentication method:
|
||||
* Email/password
|
||||
* Google authentication
|
||||
* GitHub authentication
|
||||
* SSO (for enterprise plans)
|
||||
4. Verify email address
|
||||
5. Complete onboarding wizard
|
||||
|
||||
<Note>
|
||||
[Note: Screenshot of slide 115 showing Prowler Cloud signup - to be added]
|
||||
</Note>
|
||||
|
||||
## Step 2: Connect Your First Cloud Provider
|
||||
|
||||
**Connect AWS Account:**
|
||||
|
||||
1. Navigate to "Providers" in Prowler Cloud
|
||||
2. Click "Add Provider"
|
||||
3. Select "AWS"
|
||||
4. Choose connection method:
|
||||
* **CloudFormation Stack** (recommended)
|
||||
* **Manual IAM Role**
|
||||
5. Deploy CloudFormation template
|
||||
6. Copy Role ARN and External ID
|
||||
7. Test connection
|
||||
8. Click "Save"
|
||||
|
||||
**CloudFormation Stack Deployment:**
|
||||
```bash
|
||||
aws cloudformation create-stack \
|
||||
--stack-name prowler-integration \
|
||||
--template-url https://prowler-public.s3.amazonaws.com/prowler-role.yaml \
|
||||
--parameters ParameterKey=ExternalId,ParameterValue=<your-external-id> \
|
||||
--capabilities CAPABILITY_NAMED_IAM
|
||||
```
|
||||
|
||||
<Note>
|
||||
[Note: Screenshot of slide 118 showing provider connection - to be added]
|
||||
</Note>
|
||||
|
||||
<Tip>
|
||||
The CloudFormation template creates a read-only IAM role with the minimum permissions required for Prowler scans.
|
||||
</Tip>
|
||||
|
||||
## Step 3: Run Your First Cloud Scan
|
||||
|
||||
Initiate a security scan:
|
||||
|
||||
1. Go to "Scans" page
|
||||
2. Click "New Scan"
|
||||
3. Select provider(s) to scan
|
||||
4. Choose scan type:
|
||||
* **Quick Scan:** Essential security checks
|
||||
* **Full Scan:** Comprehensive assessment
|
||||
* **Compliance Scan:** Framework-specific validation
|
||||
5. Click "Start Scan"
|
||||
|
||||
Monitor scan progress:
|
||||
* Real-time progress indicator
|
||||
* Checks completed
|
||||
* Resources discovered
|
||||
* Findings identified
|
||||
|
||||
<Note>
|
||||
[Note: Screenshot of slide 121 showing scan execution - to be added]
|
||||
</Note>
|
||||
|
||||
## Step 4: Explore the Findings Dashboard
|
||||
|
||||
Navigate findings dashboard:
|
||||
|
||||
**Overview Statistics:**
|
||||
* Total findings by severity
|
||||
* Compliance score
|
||||
* Trend over time
|
||||
* Top affected services
|
||||
|
||||
**Filtering Options:**
|
||||
* Severity (Critical, High, Medium, Low)
|
||||
* Status (Open, In Progress, Resolved)
|
||||
* Cloud provider
|
||||
* Service
|
||||
* Compliance framework
|
||||
* Resource tags
|
||||
|
||||
**Finding Details:**
|
||||
* Detailed description
|
||||
* Affected resources
|
||||
* Risk assessment
|
||||
* Remediation steps
|
||||
* Related compliance requirements
|
||||
|
||||
<Note>
|
||||
[Note: Screenshot of slide 124 showing findings dashboard - to be added]
|
||||
</Note>
|
||||
|
||||
## Step 5: Use AI-Powered Security Insights
|
||||
|
||||
Leverage Prowler Lighthouse AI features:
|
||||
|
||||
**AI Security Assistant:**
|
||||
1. Click "Lighthouse" in navigation
|
||||
2. Ask questions about your security posture:
|
||||
* "What are my critical security risks?"
|
||||
* "Show me publicly exposed resources"
|
||||
* "How can I improve my compliance score?"
|
||||
* "What encryption issues exist?"
|
||||
|
||||
**AI Remediation Guidance:**
|
||||
* Select any finding
|
||||
* Click "AI Remediation"
|
||||
* Review generated remediation steps
|
||||
* Get customized code/CLI commands
|
||||
* Apply fixes with confidence
|
||||
|
||||
**AI Threat Analysis:**
|
||||
* Identifies attack patterns
|
||||
* Correlates related findings
|
||||
* Suggests priority order for remediation
|
||||
* Explains security impact
|
||||
|
||||
<Note>
|
||||
[Note: Screenshot of slide 127 showing Lighthouse AI - to be added]
|
||||
</Note>
|
||||
|
||||
## Step 6: Configure Team Collaboration
|
||||
|
||||
Set up team access and workflows:
|
||||
|
||||
**Invite Team Members:**
|
||||
1. Go to "Settings" → "Team"
|
||||
2. Click "Invite Member"
|
||||
3. Enter email address
|
||||
4. Assign role:
|
||||
* **Admin:** Full access
|
||||
* **Editor:** Scan and remediate
|
||||
* **Viewer:** Read-only access
|
||||
5. Send invitation
|
||||
|
||||
**Assign Findings:**
|
||||
1. Select findings
|
||||
2. Click "Assign"
|
||||
3. Choose team member
|
||||
4. Add due date
|
||||
5. Add comments/notes
|
||||
|
||||
**Workflow States:**
|
||||
* Open → New finding
|
||||
* In Progress → Being investigated/fixed
|
||||
* Resolved → Remediated
|
||||
* False Positive → Not applicable
|
||||
* Risk Accepted → Acknowledged but not fixed
|
||||
|
||||
<Note>
|
||||
[Note: Screenshot of slide 130 showing team collaboration - to be added]
|
||||
</Note>
|
||||
|
||||
## Step 7: Configure Continuous Monitoring
|
||||
|
||||
Set up automated scanning:
|
||||
|
||||
**Scheduled Scans:**
|
||||
1. Go to "Scans" → "Schedules"
|
||||
2. Click "Create Schedule"
|
||||
3. Configure:
|
||||
* Name: "Daily Security Scan"
|
||||
* Frequency: Daily, Weekly, or Custom cron
|
||||
* Time: 2:00 AM UTC
|
||||
* Providers: Select all
|
||||
* Notification preferences
|
||||
4. Save schedule
|
||||
|
||||
**Real-Time Monitoring:**
|
||||
* Enable CloudTrail integration
|
||||
* Receive alerts for security events
|
||||
* Detect configuration drift
|
||||
* Identify new resources
|
||||
|
||||
<Tip>
|
||||
Schedule scans during off-peak hours to minimize performance impact on your cloud APIs.
|
||||
</Tip>
|
||||
|
||||
## Step 8: Configure Alerts and Notifications
|
||||
|
||||
Set up security alerts:
|
||||
|
||||
**Alert Rules:**
|
||||
1. Navigate to "Alerts"
|
||||
2. Click "Create Alert Rule"
|
||||
3. Define conditions:
|
||||
* Finding severity ≥ High
|
||||
* Compliance score drops below 80%
|
||||
* New critical findings discovered
|
||||
* Public exposure detected
|
||||
4. Choose notification channels:
|
||||
* Email
|
||||
* Slack
|
||||
* Microsoft Teams
|
||||
* PagerDuty
|
||||
* Webhooks
|
||||
5. Save rule
|
||||
|
||||
**Slack Integration:**
|
||||
1. Go to "Integrations" → "Slack"
|
||||
2. Click "Connect to Slack"
|
||||
3. Authorize Prowler app
|
||||
4. Select channel for notifications
|
||||
5. Configure alert preferences
|
||||
|
||||
<Note>
|
||||
[Note: Screenshot of slide 134 showing alert configuration - to be added]
|
||||
</Note>
|
||||
|
||||
## Step 9: Generate Compliance Reports
|
||||
|
||||
Create compliance reports for auditors:
|
||||
|
||||
**Compliance Dashboard:**
|
||||
1. Navigate to "Compliance"
|
||||
2. View compliance scores by framework:
|
||||
* CIS Benchmarks
|
||||
* PCI-DSS
|
||||
* HIPAA
|
||||
* SOC2
|
||||
* ISO 27001
|
||||
3. Drill down into requirements
|
||||
4. View evidence for each control
|
||||
|
||||
**Export Reports:**
|
||||
1. Select compliance framework
|
||||
2. Click "Generate Report"
|
||||
3. Choose format:
|
||||
* PDF (executive summary)
|
||||
* Excel (detailed findings)
|
||||
* CSV (raw data)
|
||||
4. Schedule recurring reports:
|
||||
* Weekly status updates
|
||||
* Monthly compliance reports
|
||||
* Quarterly audit packages
|
||||
|
||||
**Report Customization:**
|
||||
* Add company logo
|
||||
* Include executive summary
|
||||
* Filter by business unit
|
||||
* Show remediation progress
|
||||
* Include trend analysis
|
||||
|
||||
<Note>
|
||||
[Note: Screenshot of slide 137 showing compliance reports - to be added]
|
||||
</Note>
|
||||
|
||||
## Step 10: Multi-Account and Multi-Cloud Management
|
||||
|
||||
Manage multiple cloud environments:
|
||||
|
||||
**Add Multiple Providers:**
|
||||
1. Connect AWS accounts (dev, staging, production)
|
||||
2. Connect Azure subscriptions
|
||||
3. Connect GCP projects
|
||||
4. Organize with tags/labels
|
||||
|
||||
**Provider Groups:**
|
||||
1. Create provider groups:
|
||||
* Production environments
|
||||
* Development environments
|
||||
* By business unit
|
||||
* By geographic region
|
||||
2. Run group-wide scans
|
||||
3. Generate consolidated reports
|
||||
|
||||
**Cross-Cloud Insights:**
|
||||
* Compare security posture across providers
|
||||
* Identify configuration inconsistencies
|
||||
* Standardize security policies
|
||||
* Track multi-cloud compliance
|
||||
|
||||
<Note>
|
||||
[Note: Screenshot of slide 140 showing multi-cloud management - to be added]
|
||||
</Note>
|
||||
|
||||
## Step 11: Advanced Features
|
||||
|
||||
Explore advanced Prowler Cloud capabilities:
|
||||
|
||||
**Custom Checks:**
|
||||
* Create organization-specific security policies
|
||||
* Define custom compliance requirements
|
||||
* Share with team
|
||||
|
||||
**API Access:**
|
||||
* Programmatic access to findings
|
||||
* Integrate with internal tools
|
||||
* Automate workflows
|
||||
|
||||
**RBAC (Role-Based Access Control):**
|
||||
* Fine-grained permissions
|
||||
* Provider-level access control
|
||||
* Audit logging
|
||||
|
||||
**Security Integrations:**
|
||||
* AWS Security Hub
|
||||
* Jira
|
||||
* ServiceNow
|
||||
* Splunk
|
||||
* Custom webhooks
|
||||
|
||||
## Verification Steps
|
||||
|
||||
Confirm successful lab completion:
|
||||
|
||||
1. Prowler Cloud account created
|
||||
2. Cloud provider(s) connected
|
||||
3. Security scan completed
|
||||
4. Findings dashboard explored
|
||||
5. AI insights leveraged
|
||||
6. Team collaboration configured
|
||||
7. Continuous monitoring set up
|
||||
8. Compliance reports generated
|
||||
|
||||
## Expected Outcomes
|
||||
|
||||
After completing this lab, you should:
|
||||
|
||||
* Understand Prowler Cloud platform capabilities
|
||||
* Be able to connect and scan cloud providers
|
||||
* Know how to use AI-powered insights
|
||||
* Have configured team collaboration
|
||||
* Be able to generate compliance reports
|
||||
* Have set up continuous monitoring
|
||||
|
||||
## Prowler Cloud vs. Prowler CLI
|
||||
|
||||
**Prowler Cloud Advantages:**
|
||||
* Managed infrastructure (no installation)
|
||||
* Web-based interface
|
||||
* Team collaboration features
|
||||
* AI-powered insights (Lighthouse)
|
||||
* Continuous monitoring
|
||||
* Historical trend analysis
|
||||
* Executive dashboards
|
||||
* Built-in integrations
|
||||
* Scheduled scans
|
||||
* Role-based access control
|
||||
|
||||
**Prowler CLI Advantages:**
|
||||
* Self-hosted (on-premises)
|
||||
* No data leaves your environment
|
||||
* Scriptable and automatable
|
||||
* Free and open source
|
||||
* Custom integrations
|
||||
* Offline scanning
|
||||
|
||||
<Tip>
|
||||
Many organizations use both: Prowler CLI for automated CI/CD pipelines and Prowler Cloud for centralized visibility and team collaboration.
|
||||
</Tip>
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
**Issue:** Cannot connect cloud provider
|
||||
* **Solution:** Verify IAM role permissions and trust relationship, check External ID
|
||||
|
||||
**Issue:** Scan fails or times out
|
||||
* **Solution:** Check provider credentials are valid, ensure APIs are not rate-limited
|
||||
|
||||
**Issue:** No findings appearing
|
||||
* **Solution:** Verify scan completed successfully, check filtering settings
|
||||
|
||||
**Issue:** Alert notifications not received
|
||||
* **Solution:** Verify integration configuration, check notification channel settings
|
||||
|
||||
## Workshop Completion
|
||||
|
||||
Congratulations on completing the Prowler Workshop! You have learned:
|
||||
|
||||
* Prowler CLI installation and basic usage
|
||||
* Threat detection techniques
|
||||
* Custom check development
|
||||
* Multi-cloud security (AWS, Azure, GCP)
|
||||
* Compliance automation
|
||||
* Security tool integrations
|
||||
* Prowler Cloud platform capabilities
|
||||
|
||||
## Next Steps
|
||||
|
||||
Continue your Prowler journey:
|
||||
|
||||
* Join the [Prowler Community](https://goto.prowler.com/slack)
|
||||
* Contribute to [Prowler Open Source](https://github.com/prowler-cloud/prowler)
|
||||
* Explore [Prowler Hub](https://hub.prowler.com) for checks and frameworks
|
||||
* Read the [Prowler Documentation](https://docs.prowler.com)
|
||||
* Follow [Prowler on Twitter](https://twitter.com/prowlercloud)
|
||||
* Subscribe to [Prowler YouTube](https://www.youtube.com/@prowlercloud)
|
||||
|
||||
## Additional Resources
|
||||
|
||||
* [Prowler Cloud Documentation](/getting-started/products/prowler-cloud)
|
||||
* [Prowler Cloud Pricing](/getting-started/products/prowler-cloud-pricing)
|
||||
* [AWS Marketplace Listing](/getting-started/products/prowler-cloud-aws-marketplace)
|
||||
* [Prowler API Reference](/getting-started/goto/prowler-api-reference)
|
||||
* [Prowler Lighthouse AI](/user-guide/tutorials/prowler-app-lighthouse)
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
All notable changes to the **Prowler MCP Server** are documented in this file.
|
||||
|
||||
## [0.1.0] (Prowler UNRELEASED)
|
||||
## [0.1.0] (Prowler 5.13.0)
|
||||
|
||||
### Added
|
||||
- Initial release of Prowler MCP Server [(#8695)](https://github.com/prowler-cloud/prowler/pull/8695)
|
||||
|
||||
@@ -0,0 +1,366 @@
|
||||
# Prowler SDK Agent Guide
|
||||
|
||||
**Complete guide for AI agents and developers working on the Prowler SDK - the core Python security scanning engine.**
|
||||
|
||||
## Project Overview
|
||||
|
||||
The Prowler SDK is the core Python engine that powers Prowler's cloud security assessment capabilities. It provides:
|
||||
|
||||
- **Multi-cloud Security Scanning**: AWS, Azure, GCP, Kubernetes, GitHub, M365, Oracle Cloud, MongoDB Atlas, and more
|
||||
- **Compliance Frameworks**: 30+ frameworks including CIS, NIST, PCI-DSS, SOC2, GDPR
|
||||
- **1000+ Security Checks**: Comprehensive coverage across all supported providers
|
||||
- **Multiple Output Formats**: JSON, CSV, HTML, ASFF, OCSF, and compliance-specific formats
|
||||
|
||||
## Mission & Scope
|
||||
|
||||
- Maintain and enhance the core Prowler SDK functionality with security and stability as top priorities
|
||||
- Follow best practices for Python patterns, code style, security, and comprehensive testing
|
||||
- To get more information about development guidelines, please refer to the Prowler Developer Guide in `docs/developer-guide/`
|
||||
|
||||
---
|
||||
|
||||
## Architecture Rules
|
||||
|
||||
### 1. Provider Architecture Pattern
|
||||
|
||||
All Prowler providers MUST follow the established pattern:
|
||||
|
||||
```
|
||||
prowler/providers/{provider}/
|
||||
├── {provider}_provider.py # Main provider class
|
||||
├── models.py # Provider-specific models
|
||||
├── config.py # Provider configuration
|
||||
├── exceptions/ # Provider-specific exceptions
|
||||
├── lib/ # Provider libraries (as minimun it should have implemented the next folders: service, arguments, mutelist)
|
||||
│ ├── service/ # Provider-specific service class to be inherited by all services of the provider
|
||||
│ ├── arguments/ # Provider-specific CLI arguments parser
|
||||
│ └── mutelist/ # Provider-specific mutelist functionality
|
||||
└── services/ # All provider services to be audited
|
||||
└── {service}/ # Individual service
|
||||
├── {service}_service.py # Class to fetch the needed resources from the API and store them to be used by the checks
|
||||
├── {service}_client.py # Python instance of the service class to be used by the checks
|
||||
└── {check_name}/ # Individual check folder
|
||||
├── {check_name}.py # Python class to implement the check logic
|
||||
└── {check_name}.metadata.json # JSON file to store the check metadata
|
||||
└── {check_name_2}/ # Other checks can be added to the same service folder
|
||||
├── {check_name_2}.py
|
||||
└── {check_name_2}.metadata.json
|
||||
...
|
||||
└── {service_2}/ # Other services can be added to the same provider folder
|
||||
...
|
||||
```
|
||||
|
||||
### 2. Check Implementation Standards
|
||||
|
||||
Every security check MUST implement:
|
||||
|
||||
```python
|
||||
from prowler.lib.check.models import Check, CheckReport<Provider>
|
||||
from prowler.providers.<provider>.services.<service>.<service>_client import <service>_client
|
||||
|
||||
class check_name(Check):
|
||||
"""Ensure that <resource> meets <security_requirement>."""
|
||||
def execute(self) -> list[CheckReport<Provider>]:
|
||||
"""Execute the check logic.
|
||||
|
||||
Returns:
|
||||
A list of reports containing the result of the check.
|
||||
"""
|
||||
findings = []
|
||||
# Check implementation here
|
||||
for resource in <service>_client.<resources>:
|
||||
# Security validation logic
|
||||
report = CheckReport<Provider>(metadata=self.metadata(), resource=resource)
|
||||
report.status = "PASS" | "FAIL"
|
||||
report.status_extended = "Detailed explanation"
|
||||
findings.append(report) # Add the report to the list of findings
|
||||
return findings
|
||||
```
|
||||
|
||||
### 3. Compliance Framework Integration
|
||||
|
||||
All compliance frameworks must be defined in:
|
||||
- `prowler/compliance/{provider}/{framework}.json`
|
||||
- Follow the established Compliance model structure
|
||||
- Include proper requirement mappings and metadata
|
||||
|
||||
---
|
||||
|
||||
## Tech Stack
|
||||
|
||||
- **Language**: Python 3.9+
|
||||
- **Dependency Management**: Poetry 2+
|
||||
- **CLI Framework**: Custom argument parser with provider-specific subcommands
|
||||
- **Testing**: Pytest with extensive unit and integration tests
|
||||
- **Code Quality**: Pre-commit hooks for Black, Flake8, Pylint, Bandit for security scanning
|
||||
|
||||
## Commands
|
||||
|
||||
### Development Environment
|
||||
|
||||
```bash
|
||||
# Core development setup
|
||||
poetry install --with dev # Install all dependencies
|
||||
poetry run pre-commit install # Install pre-commit hooks
|
||||
|
||||
# Code quality
|
||||
poetry run pre-commit run --all-files
|
||||
|
||||
# Run tests
|
||||
poetry run pytest -n auto -vvv -s -x tests/
|
||||
```
|
||||
|
||||
### Running Prowler CLI
|
||||
|
||||
```bash
|
||||
# Run Prowler
|
||||
poetry run python prowler-cli.py --help
|
||||
|
||||
# Run Prowler with a specific provider
|
||||
poetry run python prowler-cli.py <provider>
|
||||
|
||||
# Run Prowler with error logging
|
||||
poetry run python prowler-cli.py <provider> --log-level ERROR --verbose
|
||||
|
||||
# Run specific checks
|
||||
poetry run python prowler-cli.py <provider> --checks <check_name_1> <check_name_2>
|
||||
```
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
prowler/
|
||||
├── __main__.py # Main CLI entry point
|
||||
├── config/ # Global configuration
|
||||
│ ├── config.py # Core configuration settings
|
||||
│ └── __init__.py
|
||||
├── lib/ # Core library functions
|
||||
│ ├── check/ # Check execution engine
|
||||
│ │ ├── check.py # Check execution logic
|
||||
│ │ ├── checks_loader.py # Dynamic check loading
|
||||
│ │ ├── compliance.py # Compliance framework handling
|
||||
│ │ └── models.py # Check and report models
|
||||
│ ├── cli/ # Command-line interface
|
||||
│ │ └── parser.py # Argument parsing
|
||||
│ ├── outputs/ # Output format handlers
|
||||
│ │ ├── csv/ # CSV output
|
||||
│ │ ├── html/ # HTML reports
|
||||
│ │ ├── json/ # JSON formats
|
||||
│ │ └── compliance/ # Compliance reports
|
||||
│ ├── scan/ # Scan orchestration
|
||||
│ ├── utils/ # Utility functions
|
||||
│ └── mutelist/ # Mute list functionality
|
||||
├── providers/ # Cloud provider implementations
|
||||
│ ├── aws/ # AWS provider
|
||||
│ ├── azure/ # Azure provider
|
||||
│ ├── gcp/ # Google Cloud provider
|
||||
│ ├── kubernetes/ # Kubernetes provider
|
||||
│ ├── github/ # GitHub provider
|
||||
│ ├── m365/ # Microsoft 365 provider
|
||||
│ ├── mongodbatlas/ # MongoDB Atlas provider
|
||||
│ ├── oci/ # Oracle Cloud provider
|
||||
│ ├── ...
|
||||
│ └── common/ # Shared provider utilities
|
||||
├── compliance/ # Compliance framework definitions
|
||||
│ ├── aws/ # AWS compliance frameworks
|
||||
│ ├── azure/ # Azure compliance frameworks
|
||||
│ ├── gcp/ # GCP compliance frameworks
|
||||
│ ├── ...
|
||||
└── exceptions/ # Global exception definitions
|
||||
```
|
||||
|
||||
## Key Components
|
||||
|
||||
### 1. Provider System
|
||||
|
||||
Each cloud provider implements:
|
||||
|
||||
```python
|
||||
class Provider:
|
||||
"""Base provider class"""
|
||||
|
||||
def __init__(self, arguments):
|
||||
self.session = self._setup_session(arguments)
|
||||
self.regions = self._get_regions()
|
||||
# Initialize all services
|
||||
|
||||
def _setup_session(self, arguments):
|
||||
"""Provider-specific authentication"""
|
||||
pass
|
||||
|
||||
def _get_regions(self):
|
||||
"""Get available regions for provider"""
|
||||
pass
|
||||
```
|
||||
|
||||
### 2. Check Engine
|
||||
|
||||
The check execution system:
|
||||
|
||||
- **Dynamic Loading**: Automatically discovers and loads checks
|
||||
- **Parallel Execution**: Runs checks in parallel for performance
|
||||
- **Error Isolation**: Individual check failures don't affect others
|
||||
- **Comprehensive Reporting**: Detailed findings with remediation guidance
|
||||
|
||||
### 3. Compliance Framework Engine
|
||||
|
||||
Compliance frameworks are defined as JSON files mapping checks to requirements:
|
||||
|
||||
```json
|
||||
{
|
||||
"Framework": "CIS",
|
||||
"Name": "CIS Amazon Web Services Foundations Benchmark v2.0.0",
|
||||
"Version": "2.0",
|
||||
"Provider": "AWS",
|
||||
"Description": "The CIS Amazon Web Services Foundations Benchmark provides prescriptive guidance for configuring security options for a subset of Amazon Web Services with an emphasis on foundational, testable, and architecture agnostic settings.",
|
||||
"Requirements": [
|
||||
{
|
||||
"Id": "1.1",
|
||||
"Description": "Maintain current contact details",
|
||||
"Checks": ["account_contact_details_configured"]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### 4. Output System
|
||||
|
||||
Multiple output formats supported:
|
||||
|
||||
- **JSON**: Machine-readable findings
|
||||
- **CSV**: Spreadsheet-compatible format
|
||||
- **HTML**: Interactive web reports
|
||||
- **ASFF**: AWS Security Finding Format
|
||||
- **OCSF**: Open Cybersecurity Schema Framework
|
||||
|
||||
## Development Patterns
|
||||
|
||||
### Adding New Cloud Providers
|
||||
|
||||
1. **Create Provider Structure**:
|
||||
```bash
|
||||
mkdir -p prowler/providers/{provider}
|
||||
mkdir -p prowler/providers/{provider}/services
|
||||
mkdir -p prowler/providers/{provider}/lib/{service,arguments,mutelist}
|
||||
mkdir -p prowler/providers/{provider}/exceptions
|
||||
```
|
||||
|
||||
2. **Implement Provider Class**:
|
||||
```python
|
||||
from prowler.providers.common.provider import Provider
|
||||
|
||||
class NewProvider(Provider):
|
||||
def __init__(self, arguments):
|
||||
super().__init__(arguments)
|
||||
# Provider-specific initialization
|
||||
```
|
||||
|
||||
3. **Add Provider to CLI**:
|
||||
Update `prowler/lib/cli/parser.py` to include new provider arguments.
|
||||
|
||||
### Adding New Security Checks
|
||||
|
||||
The most common high level steps to create a new check are:
|
||||
|
||||
1. Prerequisites:
|
||||
- Verify the check does not already exist by searching in the same service folder as `prowler/providers/<provider>/services/<service>/<check_name_want_to_implement>/`.
|
||||
- Ensure required provider and service exist. If not, you will need to create them first.
|
||||
- Confirm the service has implemented all required methods and attributes for the check (in most cases, you will need to add or modify some methods in the service to get the data you need for the check).
|
||||
2. Navigate to the service directory. The path should be as follows: `prowler/providers/<provider>/services/<service>`.
|
||||
3. Create a check-specific folder. The path should follow this pattern: `prowler/providers/<provider>/services/<service>/<check_name_want_to_implement>`. Adhere to the [Naming Format for Checks](/developer-guide/checks#naming-format-for-checks).
|
||||
4. Create the check files, you can use next commands:
|
||||
```bash
|
||||
mkdir -p prowler/providers/<provider>/services/<service>/<check_name_want_to_implement>
|
||||
touch prowler/providers/<provider>/services/<service>/<check_name_want_to_implement>/__init__.py
|
||||
touch prowler/providers/<provider>/services/<service>/<check_name_want_to_implement>/<check_name_want_to_implement>.py
|
||||
touch prowler/providers/<provider>/services/<service>/<check_name_want_to_implement>/<check_name_want_to_implement>.metadata.json
|
||||
```
|
||||
5. Run the check locally to ensure it works as expected. For checking you can use the CLI in the next way:
|
||||
- To ensure the check has been detected by Prowler: `poetry run python prowler-cli.py <provider> --list-checks | grep <check_name>`.
|
||||
- To run the check, to find possible issues: `poetry run python prowler-cli.py <provider> --log-level ERROR --verbose --check <check_name>`.
|
||||
6. Create comprehensive tests for the check that cover multiple scenarios including both PASS (compliant) and FAIL (non-compliant) cases. For detailed information about test structure and implementation guidelines, refer to the [Testing](/developer-guide/unit-testing) documentation.
|
||||
7. If the check and its corresponding tests are working as expected, you can submit a PR to Prowler.
|
||||
|
||||
### Adding Compliance Frameworks
|
||||
|
||||
1. **Create Framework File**:
|
||||
```bash
|
||||
# Create prowler/compliance/{provider}/{framework}.json
|
||||
```
|
||||
|
||||
2. **Define Requirements**:
|
||||
Map framework requirements to existing checks.
|
||||
|
||||
3. **Test Compliance**:
|
||||
```bash
|
||||
poetry run python -m prowler {provider} --compliance {framework}
|
||||
```
|
||||
|
||||
## Code Quality Standards
|
||||
|
||||
### 1. Python Style
|
||||
|
||||
- **PEP 8 Compliance**: Enforced by black and flake8
|
||||
- **Type Hints**: Required for all public functions
|
||||
- **Docstrings**: Required for all classes and methods
|
||||
- **Import Organization**: Use isort for consistent import ordering
|
||||
|
||||
```python
|
||||
import standard_library
|
||||
|
||||
from third_party import library
|
||||
|
||||
from prowler.lib import internal_module
|
||||
|
||||
class ExampleClass:
|
||||
"""Class docstring."""
|
||||
|
||||
def method(self, param: str) -> dict | list | None:
|
||||
"""Method docstring.
|
||||
|
||||
Args:
|
||||
param: Description of parameter
|
||||
|
||||
Returns:
|
||||
Description of return value
|
||||
"""
|
||||
return None
|
||||
```
|
||||
|
||||
### 2. Error Handling
|
||||
|
||||
```python
|
||||
from prowler.lib.logger import logger
|
||||
|
||||
try:
|
||||
# Risky operation
|
||||
result = api_call()
|
||||
except ProviderSpecificException as e:
|
||||
logger.error(f"Provider error: {e}")
|
||||
# Graceful handling
|
||||
except Exception as e:
|
||||
logger.error(f"Unexpected error: {e}")
|
||||
# Never let checks crash the entire scan
|
||||
```
|
||||
|
||||
### 3. Security Practices
|
||||
|
||||
- **No Hardcoded Secrets**: Use environment variables or secure credential management
|
||||
- **Input Validation**: Validate all external inputs
|
||||
- **Principle of Least Privilege**: Request minimal necessary permissions
|
||||
- **Secure Defaults**: Default to secure configurations
|
||||
|
||||
## Testing Guidelines
|
||||
|
||||
### Unit Tests
|
||||
|
||||
- **100% Coverage Goal**: Aim for complete test coverage
|
||||
- **Mock External Services**: Use mock objects to simulate the external services
|
||||
- **Test Edge Cases**: Include error conditions and boundary cases
|
||||
|
||||
## References
|
||||
|
||||
- **Root Project Guide**: `../AGENTS.md` (takes priority for cross-component guidance)
|
||||
- **Provider Examples**: Reference existing providers for implementation patterns
|
||||
- **Check Examples**: Study existing checks for proper implementation patterns
|
||||
- **Compliance Framework Examples**: Review existing frameworks for structure
|
||||
+19
-7
@@ -2,7 +2,23 @@
|
||||
|
||||
All notable changes to the **Prowler SDK** are documented in this file.
|
||||
|
||||
## [v5.13.0] (Prowler UNRELEASED)
|
||||
## [v5.14.0] (Prowler UNRELEASED)
|
||||
|
||||
### Added
|
||||
- GitHub provider check `organization_default_repository_permission_strict` [(#8785)](https://github.com/prowler-cloud/prowler/pull/8785)
|
||||
- Update AWS Direct Connect service metadata to new format [(#8855)](https://github.com/prowler-cloud/prowler/pull/8855)
|
||||
|
||||
---
|
||||
|
||||
## [v5.13.1] (Prowler UNRELEASED)
|
||||
|
||||
### Fixed
|
||||
- Add `resource_name` for checks under `logging` for the GCP provider [(#9023)](https://github.com/prowler-cloud/prowler/pull/9023)
|
||||
|
||||
|
||||
---
|
||||
|
||||
## [v5.13.0] (Prowler v5.13.0)
|
||||
|
||||
### Added
|
||||
- Support for AdditionalURLs in outputs [(#8651)](https://github.com/prowler-cloud/prowler/pull/8651)
|
||||
@@ -17,6 +33,7 @@ All notable changes to the **Prowler SDK** are documented in this file.
|
||||
- Oracle Cloud provider with CIS 3.0 benchmark [(#8893)](https://github.com/prowler-cloud/prowler/pull/8893)
|
||||
- Support for Atlassian Document Format (ADF) in Jira integration [(#8878)](https://github.com/prowler-cloud/prowler/pull/8878)
|
||||
- Add Common Cloud Controls for AWS, Azure and GCP [(#8000)](https://github.com/prowler-cloud/prowler/pull/8000)
|
||||
- Improve Provider documentation guide [(#8430)](https://github.com/prowler-cloud/prowler/pull/8430)
|
||||
- `cloudstorage_bucket_lifecycle_management_enabled` check for GCP provider [(#8936)](https://github.com/prowler-cloud/prowler/pull/8936)
|
||||
|
||||
### Changed
|
||||
@@ -51,13 +68,8 @@ All notable changes to the **Prowler SDK** are documented in this file.
|
||||
- Prowler ThreatScore scoring calculation CLI [(#8582)](https://github.com/prowler-cloud/prowler/pull/8582)
|
||||
- Add missing attributes for Mitre Attack AWS, Azure and GCP [(#8907)](https://github.com/prowler-cloud/prowler/pull/8907)
|
||||
- Fix KeyError in CloudSQL and Monitoring services in GCP provider [(#8909)](https://github.com/prowler-cloud/prowler/pull/8909)
|
||||
- Fix Value Errors in Entra service for M365 provider [(#8919)](https://github.com/prowler-cloud/prowler/pull/8919)
|
||||
- Fix ResourceName in GCP provider [(#8928)](https://github.com/prowler-cloud/prowler/pull/8928)
|
||||
|
||||
---
|
||||
|
||||
## [v5.12.4] (Prowler UNRELEASED)
|
||||
|
||||
### Fixed
|
||||
- Fix KeyError in `elb_ssl_listeners_use_acm_certificate` check and handle None cluster version in `eks_cluster_uses_a_supported_version` check [(#8791)](https://github.com/prowler-cloud/prowler/pull/8791)
|
||||
- Fix file extension parsing for compliance reports [(#8791)](https://github.com/prowler-cloud/prowler/pull/8791)
|
||||
- Added user pagination to Entra and Admincenter services [(#8858)](https://github.com/prowler-cloud/prowler/pull/8858)
|
||||
|
||||
@@ -753,7 +753,9 @@
|
||||
{
|
||||
"Id": "1.3.8",
|
||||
"Description": "Base permissions define the permission level automatically granted to all organization members. Define strict base access permissions for all of the repositories in the organization, including new ones.",
|
||||
"Checks": [],
|
||||
"Checks": [
|
||||
"organization_default_repository_permission_strict"
|
||||
],
|
||||
"Attributes": [
|
||||
{
|
||||
"Section": "1 Source Code",
|
||||
|
||||
@@ -12,7 +12,7 @@ from prowler.lib.logger import logger
|
||||
|
||||
timestamp = datetime.today()
|
||||
timestamp_utc = datetime.now(timezone.utc).replace(tzinfo=timezone.utc)
|
||||
prowler_version = "5.13.0"
|
||||
prowler_version = "5.14.0"
|
||||
html_logo_url = "https://github.com/prowler-cloud/prowler/"
|
||||
square_logo_img = "https://prowler.com/wp-content/uploads/logo-html.png"
|
||||
aws_logo = "https://user-images.githubusercontent.com/38561120/235953920-3e3fba08-0795-41dc-b480-9bea57db9f2e.png"
|
||||
|
||||
@@ -199,6 +199,7 @@
|
||||
"aws": [
|
||||
"ap-south-1",
|
||||
"ap-southeast-2",
|
||||
"ca-central-1",
|
||||
"eu-west-1",
|
||||
"eu-west-2",
|
||||
"us-east-1",
|
||||
@@ -1211,6 +1212,7 @@
|
||||
"b2bi": {
|
||||
"regions": {
|
||||
"aws": [
|
||||
"eu-west-1",
|
||||
"us-east-1",
|
||||
"us-east-2",
|
||||
"us-west-2"
|
||||
@@ -1562,6 +1564,7 @@
|
||||
"ap-southeast-2",
|
||||
"ap-southeast-3",
|
||||
"ap-southeast-4",
|
||||
"ap-southeast-5",
|
||||
"ca-central-1",
|
||||
"ca-west-1",
|
||||
"eu-central-1",
|
||||
@@ -2940,6 +2943,7 @@
|
||||
"ap-southeast-3",
|
||||
"ap-southeast-4",
|
||||
"ap-southeast-5",
|
||||
"ap-southeast-6",
|
||||
"ap-southeast-7",
|
||||
"ca-central-1",
|
||||
"ca-west-1",
|
||||
@@ -3606,6 +3610,7 @@
|
||||
"ap-northeast-1",
|
||||
"ap-northeast-2",
|
||||
"ap-northeast-3",
|
||||
"eu-central-1",
|
||||
"eu-west-1",
|
||||
"eu-west-2",
|
||||
"eu-west-3",
|
||||
@@ -5182,6 +5187,7 @@
|
||||
"aws": [
|
||||
"af-south-1",
|
||||
"ap-east-1",
|
||||
"ap-east-2",
|
||||
"ap-northeast-1",
|
||||
"ap-northeast-2",
|
||||
"ap-northeast-3",
|
||||
@@ -5192,6 +5198,7 @@
|
||||
"ap-southeast-3",
|
||||
"ap-southeast-4",
|
||||
"ap-southeast-5",
|
||||
"ap-southeast-7",
|
||||
"ca-central-1",
|
||||
"ca-west-1",
|
||||
"eu-central-1",
|
||||
@@ -7119,6 +7126,7 @@
|
||||
"ap-southeast-1",
|
||||
"ap-southeast-2",
|
||||
"ap-southeast-3",
|
||||
"ap-southeast-5",
|
||||
"ca-central-1",
|
||||
"eu-central-1",
|
||||
"eu-north-1",
|
||||
@@ -7706,6 +7714,7 @@
|
||||
"ap-southeast-3",
|
||||
"ap-southeast-4",
|
||||
"ap-southeast-5",
|
||||
"ap-southeast-6",
|
||||
"ap-southeast-7",
|
||||
"ca-central-1",
|
||||
"ca-west-1",
|
||||
@@ -8383,6 +8392,7 @@
|
||||
"payment-cryptography": {
|
||||
"regions": {
|
||||
"aws": [
|
||||
"af-south-1",
|
||||
"ap-northeast-1",
|
||||
"ap-northeast-3",
|
||||
"ap-south-1",
|
||||
|
||||
+18
-12
@@ -1,32 +1,38 @@
|
||||
{
|
||||
"Provider": "aws",
|
||||
"CheckID": "directconnect_connection_redundancy",
|
||||
"CheckTitle": "Ensure Direct Connect connections are redundant",
|
||||
"CheckTitle": "Direct Connect connections span at least two locations per region",
|
||||
"CheckType": [
|
||||
"Resilience"
|
||||
"Software and Configuration Checks/AWS Security Best Practices",
|
||||
"Software and Configuration Checks/AWS Security Best Practices/Network Reachability"
|
||||
],
|
||||
"ServiceName": "directconnect",
|
||||
"SubServiceName": "",
|
||||
"ResourceIdTemplate": "arn:partition:directconnect:region:account-id:directconnect/resource-id",
|
||||
"ResourceIdTemplate": "",
|
||||
"Severity": "medium",
|
||||
"ResourceType": "Other",
|
||||
"Description": "Checks the resilience of the AWS Direct Connect used to connect your on-premises.",
|
||||
"Risk": "This check alerts you if any Direct Connect connections are not redundant and the connections are coming from two distinct Direct Connect locations. Lack of location resiliency can result in unexpected downtime during maintenance, a fiber cut, a device failure, or a complete location failure.",
|
||||
"RelatedUrl": "https://docs.aws.amazon.com/awssupport/latest/user/fault-tolerance-checks.html#amazon-direct-connect-location-resiliency",
|
||||
"Description": "**AWS Direct Connect** connectivity is provisioned with **connection and location redundancy**-multiple connections spread across **at least two distinct Direct Connect locations** in each Region.",
|
||||
"Risk": "Missing **connection/location redundancy** creates a **single point of failure**, degrading **availability**. A router, fiber, or site outage can sever private paths to AWS, stalling app traffic, data replication, and admin access, leading to timeouts or extended downtime until alternate paths are restored.",
|
||||
"RelatedUrl": "",
|
||||
"AdditionalURLs": [
|
||||
"https://docs.aws.amazon.com/awssupport/latest/user/fault-tolerance-checks.html#amazon-direct-connect-location-resiliency",
|
||||
"https://repost.aws/knowledge-center/direct-connect-physical-redundancy",
|
||||
"https://aws.amazon.com/directconnect/resiliency-recommendation/"
|
||||
],
|
||||
"Remediation": {
|
||||
"Code": {
|
||||
"CLI": "",
|
||||
"CLI": "aws directconnect create-connection --region <REGION> --location <NEW_DX_LOCATION_CODE> --bandwidth 1Gbps --connection-name <example_resource_name>",
|
||||
"NativeIaC": "",
|
||||
"Other": "",
|
||||
"Terraform": ""
|
||||
"Other": "1. In the AWS Console, go to Direct Connect > Connections\n2. Click Create connection\n3. Region: select the Region where the existing connection resides\n4. Name: enter <example_resource_name>\n5. Location: select a different Direct Connect location than your existing connection\n6. Bandwidth: choose a supported value (e.g., 1 Gbps)\n7. Click Create connection",
|
||||
"Terraform": "```hcl\n# Create an additional Direct Connect connection in a different location\nresource \"aws_dx_connection\" \"example\" {\n name = \"<example_resource_name>\"\n bandwidth = \"1Gbps\"\n location = \"<NEW_DX_LOCATION_CODE>\" # Critical: choose a different DX location in the same Region to achieve location redundancy\n}\n```"
|
||||
},
|
||||
"Recommendation": {
|
||||
"Text": "To build Direct Connect location resiliency, you should have at least two connections from at least two distinct Direct Connect locations.",
|
||||
"Url": "https://aws.amazon.com/directconnect/resiliency-recommendation/"
|
||||
"Text": "Apply **redundancy** and **defense in depth**:\n- Deploy 2 Direct Connect connections across **two distinct locations**\n- Use **dynamic, active/active routing** for automatic failover\n- Ensure **provider/device diversity**\n- Size capacity so one link loss doesn't overload remaining paths\n- Consider a **VPN** as tertiary backup",
|
||||
"Url": "https://hub.prowler.com/check/directconnect_connection_redundancy"
|
||||
}
|
||||
},
|
||||
"Categories": [
|
||||
"redundancy"
|
||||
"resilience"
|
||||
],
|
||||
"DependsOn": [],
|
||||
"RelatedTo": [],
|
||||
|
||||
+18
-12
@@ -1,32 +1,38 @@
|
||||
{
|
||||
"Provider": "aws",
|
||||
"CheckID": "directconnect_virtual_interface_redundancy",
|
||||
"CheckTitle": "Ensure Direct Connect virtual interface(s) are providing redundant connections",
|
||||
"CheckTitle": "Direct Connect gateway or virtual private gateway has at least two virtual interfaces on different Direct Connect connections",
|
||||
"CheckType": [
|
||||
"Resilience"
|
||||
"Software and Configuration Checks/AWS Security Best Practices",
|
||||
"Effects/Denial of Service"
|
||||
],
|
||||
"ServiceName": "directconnect",
|
||||
"SubServiceName": "",
|
||||
"ResourceIdTemplate": "arn:partition:directconnect:region:account-id:directconnect/resource-id",
|
||||
"ResourceIdTemplate": "",
|
||||
"Severity": "medium",
|
||||
"ResourceType": "Other",
|
||||
"Description": "Checks the resilience of the AWS Direct Connect used to connect your on-premises to each Direct Connect gateway or virtual private gateway.",
|
||||
"Risk": "This check alerts you if any Direct Connect gateway or virtual private gateway isn't configured with virtual interfaces across at least two distinct Direct Connect locations. Lack of location resiliency can result in unexpected downtime during maintenance, a fiber cut, a device failure, or a complete location failure.",
|
||||
"RelatedUrl": "https://docs.aws.amazon.com/awssupport/latest/user/fault-tolerance-checks.html#amazon-direct-connect-location-resiliency",
|
||||
"Description": "**Direct Connect gateways** and **virtual private gateways** are assessed for **interface redundancy**: multiple virtual interfaces (`VIFs`) distributed across more than one **Direct Connect connection**.\n\n*Gateways with only one VIF or with all VIFs on a single connection are identified.*",
|
||||
"Risk": "Missing connection diversity undermines **availability**. A single device, fiber, or location failure can cut on-prem to VPC connectivity, causing **outages**, **packet loss**, or routing blackholes. Fallback to internet VPN can add latency and throttle throughput, delaying recovery and impacting operations.",
|
||||
"RelatedUrl": "",
|
||||
"AdditionalURLs": [
|
||||
"https://docs.aws.amazon.com/awssupport/latest/user/fault-tolerance-checks.html#amazon-direct-connect-location-resiliency",
|
||||
"https://repost.aws/knowledge-center/direct-connect-physical-redundancy",
|
||||
"https://aws.amazon.com/directconnect/resiliency-recommendation/"
|
||||
],
|
||||
"Remediation": {
|
||||
"Code": {
|
||||
"CLI": "",
|
||||
"CLI": "aws directconnect create-private-virtual-interface --connection-id <CONNECTION_ID_DIFFERENT_FROM_EXISTING_VIF> --new-private-virtual-interface '{\"virtualInterfaceName\":\"<NAME>\",\"vlan\":<VLAN>,\"asn\":<BGP_ASN>,\"addressFamily\":\"ipv4\",\"amazonAddress\":\"<AMAZON_IP/30>\",\"customerAddress\":\"<CUSTOMER_IP/30>\",\"directConnectGatewayId\":\"<DIRECT_CONNECT_GATEWAY_ID>\"}'",
|
||||
"NativeIaC": "",
|
||||
"Other": "",
|
||||
"Terraform": ""
|
||||
"Other": "1. In the AWS Console, open Direct Connect\n2. Go to Connections and select a different connection than the one used by your existing VIF\n3. Click Create virtual interface and choose Private\n4. For Gateway, select your Direct Connect gateway (or Virtual private gateway for VGW)\n5. Enter VLAN, BGP ASN, and IPv4 peer IPs (Amazon/Customer), then Create\n6. Verify the gateway now has at least two VIFs on different Direct Connect connections",
|
||||
"Terraform": "```hcl\n# Create a second Private VIF on a different DX connection and attach to the gateway\nresource \"aws_dx_private_virtual_interface\" \"example\" {\n connection_id = \"<example_resource_id>\" # CRITICAL: use a DIFFERENT Direct Connect connection than existing VIFs\n dx_gateway_id = \"<example_resource_id>\" # CRITICAL: attaches the VIF to the Direct Connect gateway (use virtual_gateway_id for VGW)\n name = \"<NAME>\"\n vlan = 100\n bgp_asn = 65000\n address_family = \"ipv4\"\n amazon_address = \"169.254.100.1/30\"\n customer_address = \"169.254.100.2/30\"\n}\n```"
|
||||
},
|
||||
"Recommendation": {
|
||||
"Text": "To build Direct Connect location resiliency, you can configure the Direct Connect gateway or virtual private gateway to connect to at least two distinct Direct Connect locations.",
|
||||
"Url": "https://aws.amazon.com/directconnect/resiliency-recommendation/"
|
||||
"Text": "Apply connectivity **defense in depth**:\n- Attach at least two `VIFs` per gateway on separate **Direct Connect connections** in distinct locations\n- Prefer active/active dynamic routing and size capacity to survive a link loss\n- *Optionally* add a **VPN/Transit Gateway** path to sustain operations during provider outages",
|
||||
"Url": "https://hub.prowler.com/check/directconnect_virtual_interface_redundancy"
|
||||
}
|
||||
},
|
||||
"Categories": [
|
||||
"redundancy"
|
||||
"resilience"
|
||||
],
|
||||
"DependsOn": [],
|
||||
"RelatedTo": [],
|
||||
|
||||
+12
-10
@@ -14,35 +14,37 @@ class logging_log_metric_filter_and_alert_for_bucket_permission_changes_enabled(
|
||||
'resource.type="gcs_bucket" AND protoPayload.methodName="storage.setIamPermissions"'
|
||||
in metric.filter
|
||||
):
|
||||
metric_name = getattr(metric, "name", None) or "unknown"
|
||||
report = Check_Report_GCP(
|
||||
metadata=self.metadata(),
|
||||
resource=metric,
|
||||
resource_id=metric_name,
|
||||
project_id=metric.project_id,
|
||||
location=logging_client.region,
|
||||
resource_name=metric.name if metric.name else "Log Metric Filter",
|
||||
resource_name=(
|
||||
metric_name if metric_name != "unknown" else "Log Metric Filter"
|
||||
),
|
||||
)
|
||||
projects_with_metric.add(metric.project_id)
|
||||
report.status = "FAIL"
|
||||
report.status_extended = f"Log metric filter {metric.name} found but no alerts associated in project {metric.project_id}."
|
||||
report.status_extended = f"Log metric filter {metric_name} found but no alerts associated in project {metric.project_id}."
|
||||
for alert_policy in monitoring_client.alert_policies:
|
||||
for filter in alert_policy.filters:
|
||||
if metric.name in filter:
|
||||
if metric_name in filter:
|
||||
report.status = "PASS"
|
||||
report.status_extended = f"Log metric filter {metric.name} found with alert policy {alert_policy.display_name} associated in project {metric.project_id}."
|
||||
report.status_extended = f"Log metric filter {metric_name} found with alert policy {alert_policy.display_name} associated in project {metric.project_id}."
|
||||
break
|
||||
findings.append(report)
|
||||
|
||||
for project in logging_client.project_ids:
|
||||
if project not in projects_with_metric:
|
||||
project_obj = logging_client.projects.get(project)
|
||||
report = Check_Report_GCP(
|
||||
metadata=self.metadata(),
|
||||
resource=logging_client.projects[project],
|
||||
resource=project_obj,
|
||||
project_id=project,
|
||||
location=logging_client.region,
|
||||
resource_name=(
|
||||
logging_client.projects[project].name
|
||||
if logging_client.projects[project].name
|
||||
else "GCP Project"
|
||||
),
|
||||
resource_name=(getattr(project_obj, "name", None) or "GCP Project"),
|
||||
)
|
||||
report.status = "FAIL"
|
||||
report.status_extended = f"There are no log metric filters or alerts associated in project {project}."
|
||||
|
||||
+13
-10
@@ -14,35 +14,38 @@ class logging_log_metric_filter_and_alert_for_project_ownership_changes_enabled(
|
||||
'(protoPayload.serviceName="cloudresourcemanager.googleapis.com") AND (ProjectOwnership OR projectOwnerInvitee) OR (protoPayload.serviceData.policyDelta.bindingDeltas.action="REMOVE" AND protoPayload.serviceData.policyDelta.bindingDeltas.role="roles/owner") OR (protoPayload.serviceData.policyDelta.bindingDeltas.action="ADD" AND protoPayload.serviceData.policyDelta.bindingDeltas.role="roles/owner")'
|
||||
in metric.filter
|
||||
):
|
||||
metric_name = getattr(metric, "name", None) or "unknown"
|
||||
report = Check_Report_GCP(
|
||||
metadata=self.metadata(),
|
||||
resource=metric,
|
||||
resource_id=metric_name,
|
||||
project_id=metric.project_id,
|
||||
location=logging_client.region,
|
||||
resource_name=metric.name if metric.name else "Log Metric Filter",
|
||||
resource_name=(
|
||||
metric_name if metric_name != "unknown" else "Log Metric Filter"
|
||||
),
|
||||
)
|
||||
projects_with_metric.add(metric.project_id)
|
||||
report.status = "FAIL"
|
||||
report.status_extended = f"Log metric filter {metric.name} found but no alerts associated in project {metric.project_id}."
|
||||
report.status_extended = f"Log metric filter {metric_name} found but no alerts associated in project {metric.project_id}."
|
||||
for alert_policy in monitoring_client.alert_policies:
|
||||
for filter in alert_policy.filters:
|
||||
if metric.name in filter:
|
||||
if metric_name in filter:
|
||||
report.status = "PASS"
|
||||
report.status_extended = f"Log metric filter {metric.name} found with alert policy {alert_policy.display_name} associated in project {metric.project_id}."
|
||||
report.status_extended = f"Log metric filter {metric_name} found with alert policy {alert_policy.display_name} associated in project {metric.project_id}."
|
||||
break
|
||||
findings.append(report)
|
||||
|
||||
for project in logging_client.project_ids:
|
||||
if project not in projects_with_metric:
|
||||
project_obj = logging_client.projects.get(project)
|
||||
report = Check_Report_GCP(
|
||||
metadata=self.metadata(),
|
||||
resource=logging_client.projects[project],
|
||||
resource=project_obj,
|
||||
resource_id=project,
|
||||
project_id=project,
|
||||
location=logging_client.region,
|
||||
resource_name=(
|
||||
logging_client.projects[project].name
|
||||
if logging_client.projects[project].name
|
||||
else "GCP Project"
|
||||
),
|
||||
resource_name=(getattr(project_obj, "name", None) or "GCP Project"),
|
||||
)
|
||||
report.status = "FAIL"
|
||||
report.status_extended = f"There are no log metric filters or alerts associated in project {project}."
|
||||
|
||||
+11
-11
@@ -12,32 +12,32 @@ class logging_sink_created(Check):
|
||||
|
||||
for project in logging_client.project_ids:
|
||||
if project not in projects_with_logging_sink.keys():
|
||||
project_obj = logging_client.projects.get(project)
|
||||
report = Check_Report_GCP(
|
||||
metadata=self.metadata(),
|
||||
resource=logging_client.projects[project],
|
||||
resource=project_obj,
|
||||
resource_id=project,
|
||||
project_id=project,
|
||||
location=logging_client.region,
|
||||
resource_name=(
|
||||
logging_client.projects[project].name
|
||||
if logging_client.projects[project].name
|
||||
else "GCP Project"
|
||||
),
|
||||
resource_name=(getattr(project_obj, "name", None) or "GCP Project"),
|
||||
)
|
||||
report.status = "FAIL"
|
||||
report.status_extended = f"There are no logging sinks to export copies of all the log entries in project {project}."
|
||||
findings.append(report)
|
||||
else:
|
||||
sink = projects_with_logging_sink[project]
|
||||
sink_name = getattr(sink, "name", None) or "unknown"
|
||||
report = Check_Report_GCP(
|
||||
metadata=self.metadata(),
|
||||
resource=projects_with_logging_sink[project],
|
||||
resource=sink,
|
||||
resource_id=sink_name,
|
||||
project_id=project,
|
||||
location=logging_client.region,
|
||||
resource_name=(
|
||||
projects_with_logging_sink[project].name
|
||||
if projects_with_logging_sink[project].name
|
||||
else "Logging Sink"
|
||||
sink_name if sink_name != "unknown" else "Logging Sink"
|
||||
),
|
||||
)
|
||||
report.status = "PASS"
|
||||
report.status_extended = f"Sink {projects_with_logging_sink[project].name} is enabled exporting copies of all the log entries in project {project}."
|
||||
report.status_extended = f"Sink {sink_name} is enabled exporting copies of all the log entries in project {project}."
|
||||
findings.append(report)
|
||||
return findings
|
||||
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"Provider": "github",
|
||||
"CheckID": "organization_default_repository_permission_strict",
|
||||
"CheckTitle": "Ensure strict base repository permissions are set for the organization",
|
||||
"CheckType": [],
|
||||
"ServiceName": "organization",
|
||||
"SubServiceName": "",
|
||||
"ResourceIdTemplate": "",
|
||||
"Severity": "high",
|
||||
"ResourceType": "GitHubOrganization",
|
||||
"Description": "Ensure the organization's base repository permission for members is set to 'read' or 'none' to minimize risk.",
|
||||
"Risk": "If base repository permissions allow 'write' or 'admin' by default, organization members may unintentionally gain excessive privileges across repositories, increasing the risk of unauthorized changes or accidental modifications.",
|
||||
"RelatedUrl": "https://docs.github.com/en/organizations/managing-user-access-to-your-organizations-repositories/managing-repository-roles/setting-base-permissions-for-an-organization",
|
||||
"Remediation": {
|
||||
"Code": {
|
||||
"CLI": "",
|
||||
"NativeIaC": "",
|
||||
"Other": "",
|
||||
"Terraform": ""
|
||||
},
|
||||
"Recommendation": {
|
||||
"Text": "Set the organization's base repository permission to 'read' or 'none' for members, unless stricter requirements are needed.",
|
||||
"Url": "https://docs.github.com/en/organizations/managing-user-access-to-your-organizations-repositories/managing-repository-roles/setting-base-permissions-for-an-organization"
|
||||
}
|
||||
},
|
||||
"AdditionalURLs": [],
|
||||
"Categories": [],
|
||||
"DependsOn": [],
|
||||
"RelatedTo": [],
|
||||
"Notes": ""
|
||||
}
|
||||
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
from typing import List
|
||||
|
||||
from prowler.lib.check.models import Check, CheckReportGithub
|
||||
from prowler.providers.github.services.organization.organization_client import (
|
||||
organization_client,
|
||||
)
|
||||
|
||||
|
||||
class organization_default_repository_permission_strict(Check):
|
||||
"""Check if an organization's base repository permission is set to a strict level.
|
||||
|
||||
PASS: base permission is "read" or "none"
|
||||
FAIL: base permission is "write" or "admin" (or any other non-strict value)
|
||||
"""
|
||||
|
||||
def execute(self) -> List[CheckReportGithub]:
|
||||
findings = []
|
||||
for org in organization_client.organizations.values():
|
||||
base_perm = getattr(org, "base_permission", None)
|
||||
if base_perm is None:
|
||||
# Unknown / no permission to read → skip producing a finding
|
||||
continue
|
||||
|
||||
p = str(base_perm).lower()
|
||||
report = CheckReportGithub(metadata=self.metadata(), resource=org)
|
||||
|
||||
if p in ("read", "none"):
|
||||
report.status = "PASS"
|
||||
report.status_extended = f"Organization {org.name} base repository permission is '{p}', which is strict."
|
||||
else:
|
||||
report.status = "FAIL"
|
||||
report.status_extended = f"Organization {org.name} base repository permission is '{p}', which is not strict."
|
||||
|
||||
findings.append(report)
|
||||
|
||||
return findings
|
||||
@@ -5,7 +5,7 @@ from pydantic.v1 import BaseModel
|
||||
|
||||
from prowler.lib.logger import logger
|
||||
from prowler.providers.github.lib.service.service import GithubService
|
||||
from prowler.providers.github.models import GithubAppIdentityInfo, GithubIdentityInfo
|
||||
from prowler.providers.github.models import GithubAppIdentityInfo
|
||||
|
||||
|
||||
class Organization(GithubService):
|
||||
@@ -38,13 +38,15 @@ class Organization(GithubService):
|
||||
org_names_to_check = set()
|
||||
|
||||
try:
|
||||
for client in self.clients:
|
||||
if self.provider.organizations:
|
||||
for client in getattr(self, "clients", []) or []:
|
||||
if getattr(self.provider, "organizations", None):
|
||||
org_names_to_check.update(self.provider.organizations)
|
||||
|
||||
# If repositories are specified without organizations, don't perform organization checks
|
||||
# Only add repository owners to organization checks if organizations are also specified
|
||||
if self.provider.repositories and self.provider.organizations:
|
||||
if getattr(self.provider, "repositories", None) and getattr(
|
||||
self.provider, "organizations", None
|
||||
):
|
||||
for repo_name in self.provider.repositories:
|
||||
if "/" in repo_name:
|
||||
owner_name = repo_name.split("/")[0]
|
||||
@@ -111,18 +113,19 @@ class Organization(GithubService):
|
||||
logger.error(
|
||||
f"{error.__class__.__name__}[{error.__traceback__.tb_lineno}]: {error}"
|
||||
)
|
||||
elif not self.provider.repositories:
|
||||
elif not getattr(self.provider, "repositories", None):
|
||||
# Default behavior: get all organizations the user is a member of
|
||||
# Only when no repositories are specified
|
||||
if isinstance(self.provider.identity, GithubIdentityInfo):
|
||||
if isinstance(self.provider.identity, GithubAppIdentityInfo):
|
||||
orgs = client.get_organizations()
|
||||
if getattr(orgs, "totalCount", 0) > 0:
|
||||
for org in orgs:
|
||||
self._process_organization(org, organizations)
|
||||
else:
|
||||
# Default (personal access/OAuth): use user organizations
|
||||
orgs = client.get_user().get_orgs()
|
||||
for org in orgs:
|
||||
self._process_organization(org, organizations)
|
||||
elif isinstance(self.provider.identity, GithubAppIdentityInfo):
|
||||
orgs = client.get_organizations()
|
||||
if orgs.totalCount > 0:
|
||||
for org in orgs:
|
||||
self._process_organization(org, organizations)
|
||||
|
||||
except github.RateLimitExceededException as error:
|
||||
logger.error(f"GitHub API rate limit exceeded: {error}")
|
||||
@@ -144,10 +147,22 @@ class Organization(GithubService):
|
||||
logger.error(
|
||||
f"{error.__class__.__name__}[{error.__traceback__.tb_lineno}]: {error}"
|
||||
)
|
||||
|
||||
# Base permission (default repository permission for members)
|
||||
base_perm: Optional[str] = None
|
||||
try:
|
||||
base_perm = getattr(org, "default_repository_permission", None)
|
||||
except Exception as error:
|
||||
logger.error(
|
||||
f"{error.__class__.__name__}[{error.__traceback__.tb_lineno}]: {error}"
|
||||
)
|
||||
base_perm = None
|
||||
|
||||
organizations[org.id] = Org(
|
||||
id=org.id,
|
||||
name=org.login,
|
||||
mfa_required=require_mfa,
|
||||
base_permission=base_perm,
|
||||
)
|
||||
|
||||
|
||||
@@ -157,3 +172,4 @@ class Org(BaseModel):
|
||||
id: int
|
||||
name: str
|
||||
mfa_required: Optional[bool] = False
|
||||
base_permission: Optional[str] = None
|
||||
|
||||
+19
-2
@@ -2,7 +2,6 @@ from prowler.lib.check.models import Check, CheckReportM365
|
||||
from prowler.providers.m365.services.entra.entra_client import entra_client
|
||||
from prowler.providers.m365.services.entra.entra_service import (
|
||||
AdminRoles,
|
||||
AuthenticationStrength,
|
||||
ConditionalAccessPolicyState,
|
||||
)
|
||||
|
||||
@@ -47,7 +46,25 @@ class entra_admin_users_phishing_resistant_mfa_enabled(Check):
|
||||
if (
|
||||
policy.grant_controls.authentication_strength is not None
|
||||
and policy.grant_controls.authentication_strength
|
||||
== AuthenticationStrength.PHISHING_RESISTANT_MFA
|
||||
!= "Multifactor authentication"
|
||||
and policy.grant_controls.authentication_strength != "Passwordless MFA"
|
||||
and policy.grant_controls.authentication_strength
|
||||
!= "Phishing-resistant MFA"
|
||||
):
|
||||
report = CheckReportM365(
|
||||
metadata=self.metadata(),
|
||||
resource=policy,
|
||||
resource_name=policy.display_name,
|
||||
resource_id=policy.id,
|
||||
)
|
||||
report.status = "MANUAL"
|
||||
report.status_extended = f"Conditional Access Policy '{policy.display_name}' has a custom authentication strength, review it is Phishing-resistant MFA."
|
||||
continue
|
||||
|
||||
if (
|
||||
policy.grant_controls.authentication_strength is not None
|
||||
and policy.grant_controls.authentication_strength
|
||||
== "Phishing-resistant MFA"
|
||||
):
|
||||
report = CheckReportM365(
|
||||
metadata=self.metadata(),
|
||||
|
||||
@@ -253,9 +253,7 @@ class Entra(M365Service):
|
||||
)
|
||||
),
|
||||
authentication_strength=(
|
||||
AuthenticationStrength(
|
||||
policy.grant_controls.authentication_strength.display_name
|
||||
)
|
||||
policy.grant_controls.authentication_strength.display_name
|
||||
if policy.grant_controls is not None
|
||||
and policy.grant_controls.authentication_strength
|
||||
is not None
|
||||
@@ -455,6 +453,7 @@ class ConditionalAccessPolicyState(Enum):
|
||||
|
||||
class UserAction(Enum):
|
||||
REGISTER_SECURITY_INFO = "urn:user:registersecurityinfo"
|
||||
REGISTER_DEVICE = "urn:user:registerdevice"
|
||||
|
||||
|
||||
class ApplicationsConditions(BaseModel):
|
||||
@@ -523,11 +522,19 @@ class SessionControls(BaseModel):
|
||||
|
||||
|
||||
class ConditionalAccessGrantControl(Enum):
|
||||
"""
|
||||
Built-in grant controls for Conditional Access policies.
|
||||
Reference: https://learn.microsoft.com/en-us/graph/api/resources/conditionalaccessgrantcontrols
|
||||
"""
|
||||
|
||||
MFA = "mfa"
|
||||
BLOCK = "block"
|
||||
DOMAIN_JOINED_DEVICE = "domainJoinedDevice"
|
||||
PASSWORD_CHANGE = "passwordChange"
|
||||
COMPLIANT_DEVICE = "compliantDevice"
|
||||
APPROVED_APPLICATION = "approvedApplication"
|
||||
COMPLIANT_APPLICATION = "compliantApplication"
|
||||
TERMS_OF_USE = "termsOfUse"
|
||||
|
||||
|
||||
class GrantControlOperator(Enum):
|
||||
@@ -535,16 +542,10 @@ class GrantControlOperator(Enum):
|
||||
OR = "OR"
|
||||
|
||||
|
||||
class AuthenticationStrength(Enum):
|
||||
MFA = "Multifactor authentication"
|
||||
PASSWORDLESS_MFA = "Passwordless MFA"
|
||||
PHISHING_RESISTANT_MFA = "Phishing-resistant MFA"
|
||||
|
||||
|
||||
class GrantControls(BaseModel):
|
||||
built_in_controls: List[ConditionalAccessGrantControl]
|
||||
operator: GrantControlOperator
|
||||
authentication_strength: Optional[AuthenticationStrength]
|
||||
authentication_strength: Optional[str]
|
||||
|
||||
|
||||
class ConditionalAccessPolicy(BaseModel):
|
||||
|
||||
+1
-1
@@ -76,7 +76,7 @@ maintainers = [{name = "Prowler Engineering", email = "engineering@prowler.com"}
|
||||
name = "prowler"
|
||||
readme = "README.md"
|
||||
requires-python = ">3.9.1,<3.13"
|
||||
version = "5.13.0"
|
||||
version = "5.14.0"
|
||||
|
||||
[project.scripts]
|
||||
prowler = "prowler.__main__:prowler"
|
||||
|
||||
+138
@@ -259,3 +259,141 @@ class Test_logging_log_metric_filter_and_alert_for_bucket_permission_changes_ena
|
||||
assert result[0].resource_name == "metric_name"
|
||||
assert result[0].project_id == GCP_PROJECT_ID
|
||||
assert result[0].location == GCP_EU1_LOCATION
|
||||
|
||||
def test_log_metric_filters_with_none_name(self):
|
||||
"""Test that metric with None name uses fallback 'Log Metric Filter'"""
|
||||
logging_client = MagicMock()
|
||||
monitoring_client = MagicMock()
|
||||
|
||||
with (
|
||||
patch(
|
||||
"prowler.providers.common.provider.Provider.get_global_provider",
|
||||
return_value=set_mocked_gcp_provider(),
|
||||
),
|
||||
patch(
|
||||
"prowler.providers.gcp.services.logging.logging_log_metric_filter_and_alert_for_bucket_permission_changes_enabled.logging_log_metric_filter_and_alert_for_bucket_permission_changes_enabled.logging_client",
|
||||
new=logging_client,
|
||||
),
|
||||
patch(
|
||||
"prowler.providers.gcp.services.logging.logging_log_metric_filter_and_alert_for_bucket_permission_changes_enabled.logging_log_metric_filter_and_alert_for_bucket_permission_changes_enabled.monitoring_client",
|
||||
new=monitoring_client,
|
||||
),
|
||||
):
|
||||
from prowler.providers.gcp.services.logging.logging_log_metric_filter_and_alert_for_bucket_permission_changes_enabled.logging_log_metric_filter_and_alert_for_bucket_permission_changes_enabled import (
|
||||
logging_log_metric_filter_and_alert_for_bucket_permission_changes_enabled,
|
||||
)
|
||||
|
||||
# Create a MagicMock metric object with name=None
|
||||
metric = MagicMock()
|
||||
metric.name = None
|
||||
metric.filter = 'resource.type="gcs_bucket" AND protoPayload.methodName="storage.setIamPermissions"'
|
||||
metric.project_id = GCP_PROJECT_ID
|
||||
|
||||
logging_client.metrics = [metric]
|
||||
logging_client.project_ids = [GCP_PROJECT_ID]
|
||||
logging_client.region = GCP_EU1_LOCATION
|
||||
|
||||
monitoring_client.alert_policies = []
|
||||
|
||||
check = (
|
||||
logging_log_metric_filter_and_alert_for_bucket_permission_changes_enabled()
|
||||
)
|
||||
result = check.execute()
|
||||
assert len(result) == 1
|
||||
assert result[0].status == "FAIL"
|
||||
assert result[0].resource_name == "Log Metric Filter"
|
||||
assert (
|
||||
result[0].resource_id == "unknown"
|
||||
) # resource_id should never be None
|
||||
assert result[0].project_id == GCP_PROJECT_ID
|
||||
assert result[0].location == GCP_EU1_LOCATION
|
||||
# When name is None, the 'or' pattern makes it use "unknown"
|
||||
assert "unknown" in result[0].status_extended
|
||||
|
||||
def test_log_metric_filters_with_missing_name_attribute(self):
|
||||
"""Test that metric without name attribute uses fallback 'Log Metric Filter'"""
|
||||
logging_client = MagicMock()
|
||||
monitoring_client = MagicMock()
|
||||
|
||||
with (
|
||||
patch(
|
||||
"prowler.providers.common.provider.Provider.get_global_provider",
|
||||
return_value=set_mocked_gcp_provider(),
|
||||
),
|
||||
patch(
|
||||
"prowler.providers.gcp.services.logging.logging_log_metric_filter_and_alert_for_bucket_permission_changes_enabled.logging_log_metric_filter_and_alert_for_bucket_permission_changes_enabled.logging_client",
|
||||
new=logging_client,
|
||||
),
|
||||
patch(
|
||||
"prowler.providers.gcp.services.logging.logging_log_metric_filter_and_alert_for_bucket_permission_changes_enabled.logging_log_metric_filter_and_alert_for_bucket_permission_changes_enabled.monitoring_client",
|
||||
new=monitoring_client,
|
||||
),
|
||||
):
|
||||
from prowler.providers.gcp.services.logging.logging_log_metric_filter_and_alert_for_bucket_permission_changes_enabled.logging_log_metric_filter_and_alert_for_bucket_permission_changes_enabled import (
|
||||
logging_log_metric_filter_and_alert_for_bucket_permission_changes_enabled,
|
||||
)
|
||||
|
||||
# Create a MagicMock metric object without name attribute
|
||||
metric = MagicMock(spec=["filter", "project_id"])
|
||||
metric.filter = 'resource.type="gcs_bucket" AND protoPayload.methodName="storage.setIamPermissions"'
|
||||
metric.project_id = GCP_PROJECT_ID
|
||||
|
||||
logging_client.metrics = [metric]
|
||||
logging_client.project_ids = [GCP_PROJECT_ID]
|
||||
logging_client.region = GCP_EU1_LOCATION
|
||||
|
||||
monitoring_client.alert_policies = []
|
||||
|
||||
check = (
|
||||
logging_log_metric_filter_and_alert_for_bucket_permission_changes_enabled()
|
||||
)
|
||||
result = check.execute()
|
||||
assert len(result) == 1
|
||||
assert result[0].status == "FAIL"
|
||||
assert result[0].resource_name == "Log Metric Filter"
|
||||
assert (
|
||||
result[0].resource_id == "unknown"
|
||||
) # resource_id should never be None
|
||||
assert result[0].project_id == GCP_PROJECT_ID
|
||||
assert result[0].location == GCP_EU1_LOCATION
|
||||
|
||||
def test_project_not_in_projects_dict(self):
|
||||
"""Test that project not in projects dict uses None and fallback name"""
|
||||
logging_client = MagicMock()
|
||||
monitoring_client = MagicMock()
|
||||
|
||||
with (
|
||||
patch(
|
||||
"prowler.providers.common.provider.Provider.get_global_provider",
|
||||
return_value=set_mocked_gcp_provider(),
|
||||
),
|
||||
patch(
|
||||
"prowler.providers.gcp.services.logging.logging_log_metric_filter_and_alert_for_bucket_permission_changes_enabled.logging_log_metric_filter_and_alert_for_bucket_permission_changes_enabled.logging_client",
|
||||
new=logging_client,
|
||||
),
|
||||
patch(
|
||||
"prowler.providers.gcp.services.logging.logging_log_metric_filter_and_alert_for_bucket_permission_changes_enabled.logging_log_metric_filter_and_alert_for_bucket_permission_changes_enabled.monitoring_client",
|
||||
new=monitoring_client,
|
||||
),
|
||||
):
|
||||
from prowler.providers.gcp.services.logging.logging_log_metric_filter_and_alert_for_bucket_permission_changes_enabled.logging_log_metric_filter_and_alert_for_bucket_permission_changes_enabled import (
|
||||
logging_log_metric_filter_and_alert_for_bucket_permission_changes_enabled,
|
||||
)
|
||||
|
||||
logging_client.metrics = []
|
||||
logging_client.project_ids = [GCP_PROJECT_ID]
|
||||
logging_client.region = GCP_EU1_LOCATION
|
||||
# Project is in project_ids but NOT in projects dict
|
||||
logging_client.projects = {}
|
||||
|
||||
monitoring_client.alert_policies = []
|
||||
|
||||
check = (
|
||||
logging_log_metric_filter_and_alert_for_bucket_permission_changes_enabled()
|
||||
)
|
||||
result = check.execute()
|
||||
assert len(result) == 1
|
||||
assert result[0].status == "FAIL"
|
||||
assert result[0].resource_name == "GCP Project"
|
||||
assert result[0].project_id == GCP_PROJECT_ID
|
||||
assert result[0].location == GCP_EU1_LOCATION
|
||||
|
||||
+133
@@ -259,3 +259,136 @@ class Test_logging_log_metric_filter_and_alert_for_project_ownership_changes_ena
|
||||
assert result[0].resource_name == "metric_name"
|
||||
assert result[0].project_id == GCP_PROJECT_ID
|
||||
assert result[0].location == GCP_EU1_LOCATION
|
||||
|
||||
def test_log_metric_filters_with_none_name(self):
|
||||
"""Test that metric with None name uses fallback 'Log Metric Filter'"""
|
||||
logging_client = MagicMock()
|
||||
monitoring_client = MagicMock()
|
||||
|
||||
with (
|
||||
patch(
|
||||
"prowler.providers.common.provider.Provider.get_global_provider",
|
||||
return_value=set_mocked_gcp_provider(),
|
||||
),
|
||||
patch(
|
||||
"prowler.providers.gcp.services.logging.logging_log_metric_filter_and_alert_for_project_ownership_changes_enabled.logging_log_metric_filter_and_alert_for_project_ownership_changes_enabled.logging_client",
|
||||
new=logging_client,
|
||||
),
|
||||
patch(
|
||||
"prowler.providers.gcp.services.logging.logging_log_metric_filter_and_alert_for_project_ownership_changes_enabled.logging_log_metric_filter_and_alert_for_project_ownership_changes_enabled.monitoring_client",
|
||||
new=monitoring_client,
|
||||
),
|
||||
):
|
||||
from prowler.providers.gcp.services.logging.logging_log_metric_filter_and_alert_for_project_ownership_changes_enabled.logging_log_metric_filter_and_alert_for_project_ownership_changes_enabled import (
|
||||
logging_log_metric_filter_and_alert_for_project_ownership_changes_enabled,
|
||||
)
|
||||
|
||||
# Create a MagicMock metric object with name=None
|
||||
metric = MagicMock()
|
||||
metric.name = None
|
||||
metric.filter = '(protoPayload.serviceName="cloudresourcemanager.googleapis.com") AND (ProjectOwnership OR projectOwnerInvitee) OR (protoPayload.serviceData.policyDelta.bindingDeltas.action="REMOVE" AND protoPayload.serviceData.policyDelta.bindingDeltas.role="roles/owner") OR (protoPayload.serviceData.policyDelta.bindingDeltas.action="ADD" AND protoPayload.serviceData.policyDelta.bindingDeltas.role="roles/owner")'
|
||||
metric.project_id = GCP_PROJECT_ID
|
||||
|
||||
logging_client.metrics = [metric]
|
||||
logging_client.project_ids = [GCP_PROJECT_ID]
|
||||
logging_client.region = GCP_EU1_LOCATION
|
||||
|
||||
monitoring_client.alert_policies = []
|
||||
|
||||
check = (
|
||||
logging_log_metric_filter_and_alert_for_project_ownership_changes_enabled()
|
||||
)
|
||||
result = check.execute()
|
||||
assert len(result) == 1
|
||||
assert result[0].status == "FAIL"
|
||||
assert result[0].resource_name == "Log Metric Filter"
|
||||
assert result[0].resource_id == "unknown"
|
||||
assert result[0].project_id == GCP_PROJECT_ID
|
||||
assert result[0].location == GCP_EU1_LOCATION
|
||||
assert "unknown" in result[0].status_extended
|
||||
|
||||
def test_log_metric_filters_with_missing_name_attribute(self):
|
||||
"""Test that metric without name attribute uses fallback 'Log Metric Filter'"""
|
||||
logging_client = MagicMock()
|
||||
monitoring_client = MagicMock()
|
||||
|
||||
with (
|
||||
patch(
|
||||
"prowler.providers.common.provider.Provider.get_global_provider",
|
||||
return_value=set_mocked_gcp_provider(),
|
||||
),
|
||||
patch(
|
||||
"prowler.providers.gcp.services.logging.logging_log_metric_filter_and_alert_for_project_ownership_changes_enabled.logging_log_metric_filter_and_alert_for_project_ownership_changes_enabled.logging_client",
|
||||
new=logging_client,
|
||||
),
|
||||
patch(
|
||||
"prowler.providers.gcp.services.logging.logging_log_metric_filter_and_alert_for_project_ownership_changes_enabled.logging_log_metric_filter_and_alert_for_project_ownership_changes_enabled.monitoring_client",
|
||||
new=monitoring_client,
|
||||
),
|
||||
):
|
||||
from prowler.providers.gcp.services.logging.logging_log_metric_filter_and_alert_for_project_ownership_changes_enabled.logging_log_metric_filter_and_alert_for_project_ownership_changes_enabled import (
|
||||
logging_log_metric_filter_and_alert_for_project_ownership_changes_enabled,
|
||||
)
|
||||
|
||||
# Create a MagicMock metric object without name attribute
|
||||
metric = MagicMock(spec=["filter", "project_id"])
|
||||
metric.filter = '(protoPayload.serviceName="cloudresourcemanager.googleapis.com") AND (ProjectOwnership OR projectOwnerInvitee) OR (protoPayload.serviceData.policyDelta.bindingDeltas.action="REMOVE" AND protoPayload.serviceData.policyDelta.bindingDeltas.role="roles/owner") OR (protoPayload.serviceData.policyDelta.bindingDeltas.action="ADD" AND protoPayload.serviceData.policyDelta.bindingDeltas.role="roles/owner")'
|
||||
metric.project_id = GCP_PROJECT_ID
|
||||
|
||||
logging_client.metrics = [metric]
|
||||
logging_client.project_ids = [GCP_PROJECT_ID]
|
||||
logging_client.region = GCP_EU1_LOCATION
|
||||
|
||||
monitoring_client.alert_policies = []
|
||||
|
||||
check = (
|
||||
logging_log_metric_filter_and_alert_for_project_ownership_changes_enabled()
|
||||
)
|
||||
result = check.execute()
|
||||
assert len(result) == 1
|
||||
assert result[0].status == "FAIL"
|
||||
assert result[0].resource_name == "Log Metric Filter"
|
||||
assert result[0].resource_id == "unknown"
|
||||
assert result[0].project_id == GCP_PROJECT_ID
|
||||
assert result[0].location == GCP_EU1_LOCATION
|
||||
|
||||
def test_project_not_in_projects_dict(self):
|
||||
"""Test that project not in projects dict uses None and fallback name"""
|
||||
logging_client = MagicMock()
|
||||
monitoring_client = MagicMock()
|
||||
|
||||
with (
|
||||
patch(
|
||||
"prowler.providers.common.provider.Provider.get_global_provider",
|
||||
return_value=set_mocked_gcp_provider(),
|
||||
),
|
||||
patch(
|
||||
"prowler.providers.gcp.services.logging.logging_log_metric_filter_and_alert_for_project_ownership_changes_enabled.logging_log_metric_filter_and_alert_for_project_ownership_changes_enabled.logging_client",
|
||||
new=logging_client,
|
||||
),
|
||||
patch(
|
||||
"prowler.providers.gcp.services.logging.logging_log_metric_filter_and_alert_for_project_ownership_changes_enabled.logging_log_metric_filter_and_alert_for_project_ownership_changes_enabled.monitoring_client",
|
||||
new=monitoring_client,
|
||||
),
|
||||
):
|
||||
from prowler.providers.gcp.services.logging.logging_log_metric_filter_and_alert_for_project_ownership_changes_enabled.logging_log_metric_filter_and_alert_for_project_ownership_changes_enabled import (
|
||||
logging_log_metric_filter_and_alert_for_project_ownership_changes_enabled,
|
||||
)
|
||||
|
||||
logging_client.metrics = []
|
||||
logging_client.project_ids = [GCP_PROJECT_ID]
|
||||
logging_client.region = GCP_EU1_LOCATION
|
||||
# Project is in project_ids but NOT in projects dict
|
||||
logging_client.projects = {}
|
||||
|
||||
monitoring_client.alert_policies = []
|
||||
|
||||
check = (
|
||||
logging_log_metric_filter_and_alert_for_project_ownership_changes_enabled()
|
||||
)
|
||||
result = check.execute()
|
||||
assert len(result) == 1
|
||||
assert result[0].status == "FAIL"
|
||||
assert result[0].resource_name == "GCP Project"
|
||||
assert result[0].project_id == GCP_PROJECT_ID
|
||||
assert result[0].location == GCP_EU1_LOCATION
|
||||
|
||||
+125
@@ -211,3 +211,128 @@ class Test_logging_sink_created:
|
||||
result[0].status_extended
|
||||
== f"There are no logging sinks to export copies of all the log entries in project {GCP_PROJECT_ID}."
|
||||
)
|
||||
|
||||
def test_project_not_in_projects_dict(self):
|
||||
"""Test that project not in projects dict uses None and fallback name"""
|
||||
logging_client = MagicMock()
|
||||
|
||||
with (
|
||||
patch(
|
||||
"prowler.providers.common.provider.Provider.get_global_provider",
|
||||
return_value=set_mocked_gcp_provider(),
|
||||
),
|
||||
patch(
|
||||
"prowler.providers.gcp.services.logging.logging_sink_created.logging_sink_created.logging_client",
|
||||
new=logging_client,
|
||||
),
|
||||
):
|
||||
from prowler.providers.gcp.services.logging.logging_sink_created.logging_sink_created import (
|
||||
logging_sink_created,
|
||||
)
|
||||
|
||||
logging_client.project_ids = [GCP_PROJECT_ID]
|
||||
logging_client.region = GCP_EU1_LOCATION
|
||||
logging_client.sinks = []
|
||||
# Project is in project_ids but NOT in projects dict
|
||||
logging_client.projects = {}
|
||||
|
||||
check = logging_sink_created()
|
||||
result = check.execute()
|
||||
assert len(result) == 1
|
||||
assert result[0].status == "FAIL"
|
||||
assert result[0].resource_name == "GCP Project"
|
||||
assert result[0].resource_id == GCP_PROJECT_ID
|
||||
assert result[0].project_id == GCP_PROJECT_ID
|
||||
assert result[0].location == GCP_EU1_LOCATION
|
||||
|
||||
def test_sink_with_none_name(self):
|
||||
"""Test that sink with None name uses fallback 'Logging Sink'"""
|
||||
logging_client = MagicMock()
|
||||
|
||||
with (
|
||||
patch(
|
||||
"prowler.providers.common.provider.Provider.get_global_provider",
|
||||
return_value=set_mocked_gcp_provider(),
|
||||
),
|
||||
patch(
|
||||
"prowler.providers.gcp.services.logging.logging_sink_created.logging_sink_created.logging_client",
|
||||
new=logging_client,
|
||||
),
|
||||
):
|
||||
from prowler.providers.gcp.services.logging.logging_sink_created.logging_sink_created import (
|
||||
logging_sink_created,
|
||||
)
|
||||
|
||||
# Create a MagicMock sink object with name=None
|
||||
sink = MagicMock()
|
||||
sink.name = None
|
||||
sink.filter = "all"
|
||||
sink.project_id = GCP_PROJECT_ID
|
||||
|
||||
logging_client.project_ids = [GCP_PROJECT_ID]
|
||||
logging_client.region = GCP_EU1_LOCATION
|
||||
logging_client.sinks = [sink]
|
||||
logging_client.projects = {
|
||||
GCP_PROJECT_ID: GCPProject(
|
||||
id=GCP_PROJECT_ID,
|
||||
number="123456789012",
|
||||
name="test",
|
||||
labels={},
|
||||
lifecycle_state="ACTIVE",
|
||||
)
|
||||
}
|
||||
|
||||
check = logging_sink_created()
|
||||
result = check.execute()
|
||||
assert len(result) == 1
|
||||
assert result[0].status == "PASS"
|
||||
assert result[0].resource_name == "Logging Sink"
|
||||
assert result[0].resource_id == "unknown"
|
||||
assert result[0].project_id == GCP_PROJECT_ID
|
||||
assert result[0].location == GCP_EU1_LOCATION
|
||||
assert "unknown" in result[0].status_extended
|
||||
|
||||
def test_sink_with_missing_name_attribute(self):
|
||||
"""Test that sink without name attribute uses fallback 'Logging Sink'"""
|
||||
logging_client = MagicMock()
|
||||
|
||||
with (
|
||||
patch(
|
||||
"prowler.providers.common.provider.Provider.get_global_provider",
|
||||
return_value=set_mocked_gcp_provider(),
|
||||
),
|
||||
patch(
|
||||
"prowler.providers.gcp.services.logging.logging_sink_created.logging_sink_created.logging_client",
|
||||
new=logging_client,
|
||||
),
|
||||
):
|
||||
from prowler.providers.gcp.services.logging.logging_sink_created.logging_sink_created import (
|
||||
logging_sink_created,
|
||||
)
|
||||
|
||||
# Create a MagicMock sink object without name attribute
|
||||
sink = MagicMock(spec=["filter", "project_id"])
|
||||
sink.filter = "all"
|
||||
sink.project_id = GCP_PROJECT_ID
|
||||
|
||||
logging_client.project_ids = [GCP_PROJECT_ID]
|
||||
logging_client.region = GCP_EU1_LOCATION
|
||||
logging_client.sinks = [sink]
|
||||
logging_client.projects = {
|
||||
GCP_PROJECT_ID: GCPProject(
|
||||
id=GCP_PROJECT_ID,
|
||||
number="123456789012",
|
||||
name="test",
|
||||
labels={},
|
||||
lifecycle_state="ACTIVE",
|
||||
)
|
||||
}
|
||||
|
||||
check = logging_sink_created()
|
||||
result = check.execute()
|
||||
assert len(result) == 1
|
||||
assert result[0].status == "PASS"
|
||||
assert result[0].resource_name == "Logging Sink"
|
||||
assert result[0].resource_id == "unknown"
|
||||
assert result[0].project_id == GCP_PROJECT_ID
|
||||
assert result[0].location == GCP_EU1_LOCATION
|
||||
|
||||
+201
@@ -0,0 +1,201 @@
|
||||
from unittest import mock
|
||||
|
||||
from prowler.providers.github.services.organization.organization_service import Org
|
||||
from tests.providers.github.github_fixtures import set_mocked_github_provider
|
||||
|
||||
|
||||
class Test_organization_default_repository_permission_strict:
|
||||
def test_no_organizations(self):
|
||||
organization_client = mock.MagicMock
|
||||
organization_client.organizations = {}
|
||||
|
||||
with (
|
||||
mock.patch(
|
||||
"prowler.providers.common.provider.Provider.get_global_provider",
|
||||
return_value=set_mocked_github_provider(),
|
||||
),
|
||||
mock.patch(
|
||||
"prowler.providers.github.services.organization.organization_default_repository_permission_strict.organization_default_repository_permission_strict.organization_client",
|
||||
new=organization_client,
|
||||
),
|
||||
):
|
||||
from prowler.providers.github.services.organization.organization_default_repository_permission_strict.organization_default_repository_permission_strict import (
|
||||
organization_default_repository_permission_strict,
|
||||
)
|
||||
|
||||
check = organization_default_repository_permission_strict()
|
||||
result = check.execute()
|
||||
assert len(result) == 0
|
||||
|
||||
def test_permission_read(self):
|
||||
organization_client = mock.MagicMock
|
||||
org_name = "test-organization"
|
||||
organization_client.organizations = {
|
||||
1: Org(
|
||||
id=1,
|
||||
name=org_name,
|
||||
base_permission="read",
|
||||
),
|
||||
}
|
||||
|
||||
with (
|
||||
mock.patch(
|
||||
"prowler.providers.common.provider.Provider.get_global_provider",
|
||||
return_value=set_mocked_github_provider(),
|
||||
),
|
||||
mock.patch(
|
||||
"prowler.providers.github.services.organization.organization_default_repository_permission_strict.organization_default_repository_permission_strict.organization_client",
|
||||
new=organization_client,
|
||||
),
|
||||
):
|
||||
from prowler.providers.github.services.organization.organization_default_repository_permission_strict.organization_default_repository_permission_strict import (
|
||||
organization_default_repository_permission_strict,
|
||||
)
|
||||
|
||||
check = organization_default_repository_permission_strict()
|
||||
result = check.execute()
|
||||
assert len(result) == 1
|
||||
assert result[0].resource_id == 1
|
||||
assert result[0].resource_name == org_name
|
||||
assert result[0].status == "PASS"
|
||||
assert (
|
||||
result[0].status_extended
|
||||
== f"Organization {org_name} base repository permission is 'read', which is strict."
|
||||
)
|
||||
|
||||
def test_permission_none(self):
|
||||
organization_client = mock.MagicMock
|
||||
org_name = "test-organization"
|
||||
organization_client.organizations = {
|
||||
1: Org(
|
||||
id=1,
|
||||
name=org_name,
|
||||
base_permission="none",
|
||||
),
|
||||
}
|
||||
|
||||
with (
|
||||
mock.patch(
|
||||
"prowler.providers.common.provider.Provider.get_global_provider",
|
||||
return_value=set_mocked_github_provider(),
|
||||
),
|
||||
mock.patch(
|
||||
"prowler.providers.github.services.organization.organization_default_repository_permission_strict.organization_default_repository_permission_strict.organization_client",
|
||||
new=organization_client,
|
||||
),
|
||||
):
|
||||
from prowler.providers.github.services.organization.organization_default_repository_permission_strict.organization_default_repository_permission_strict import (
|
||||
organization_default_repository_permission_strict,
|
||||
)
|
||||
|
||||
check = organization_default_repository_permission_strict()
|
||||
result = check.execute()
|
||||
assert len(result) == 1
|
||||
assert result[0].resource_id == 1
|
||||
assert result[0].resource_name == org_name
|
||||
assert result[0].status == "PASS"
|
||||
assert (
|
||||
result[0].status_extended
|
||||
== f"Organization {org_name} base repository permission is 'none', which is strict."
|
||||
)
|
||||
|
||||
def test_permission_write(self):
|
||||
organization_client = mock.MagicMock
|
||||
org_name = "test-organization"
|
||||
organization_client.organizations = {
|
||||
1: Org(
|
||||
id=1,
|
||||
name=org_name,
|
||||
base_permission="write",
|
||||
),
|
||||
}
|
||||
|
||||
with (
|
||||
mock.patch(
|
||||
"prowler.providers.common.provider.Provider.get_global_provider",
|
||||
return_value=set_mocked_github_provider(),
|
||||
),
|
||||
mock.patch(
|
||||
"prowler.providers.github.services.organization.organization_default_repository_permission_strict.organization_default_repository_permission_strict.organization_client",
|
||||
new=organization_client,
|
||||
),
|
||||
):
|
||||
from prowler.providers.github.services.organization.organization_default_repository_permission_strict.organization_default_repository_permission_strict import (
|
||||
organization_default_repository_permission_strict,
|
||||
)
|
||||
|
||||
check = organization_default_repository_permission_strict()
|
||||
result = check.execute()
|
||||
assert len(result) == 1
|
||||
assert result[0].resource_id == 1
|
||||
assert result[0].resource_name == org_name
|
||||
assert result[0].status == "FAIL"
|
||||
assert (
|
||||
result[0].status_extended
|
||||
== f"Organization {org_name} base repository permission is 'write', which is not strict."
|
||||
)
|
||||
|
||||
def test_permission_admin(self):
|
||||
organization_client = mock.MagicMock
|
||||
org_name = "test-organization"
|
||||
organization_client.organizations = {
|
||||
1: Org(
|
||||
id=1,
|
||||
name=org_name,
|
||||
base_permission="admin",
|
||||
),
|
||||
}
|
||||
|
||||
with (
|
||||
mock.patch(
|
||||
"prowler.providers.common.provider.Provider.get_global_provider",
|
||||
return_value=set_mocked_github_provider(),
|
||||
),
|
||||
mock.patch(
|
||||
"prowler.providers.github.services.organization.organization_default_repository_permission_strict.organization_default_repository_permission_strict.organization_client",
|
||||
new=organization_client,
|
||||
),
|
||||
):
|
||||
from prowler.providers.github.services.organization.organization_default_repository_permission_strict.organization_default_repository_permission_strict import (
|
||||
organization_default_repository_permission_strict,
|
||||
)
|
||||
|
||||
check = organization_default_repository_permission_strict()
|
||||
result = check.execute()
|
||||
assert len(result) == 1
|
||||
assert result[0].resource_id == 1
|
||||
assert result[0].resource_name == org_name
|
||||
assert result[0].status == "FAIL"
|
||||
assert (
|
||||
result[0].status_extended
|
||||
== f"Organization {org_name} base repository permission is 'admin', which is not strict."
|
||||
)
|
||||
|
||||
def test_permission_unknown_none_skipped(self):
|
||||
organization_client = mock.MagicMock
|
||||
org_name = "test-organization"
|
||||
organization_client.organizations = {
|
||||
1: Org(
|
||||
id=1,
|
||||
name=org_name,
|
||||
base_permission=None,
|
||||
),
|
||||
}
|
||||
|
||||
with (
|
||||
mock.patch(
|
||||
"prowler.providers.common.provider.Provider.get_global_provider",
|
||||
return_value=set_mocked_github_provider(),
|
||||
),
|
||||
mock.patch(
|
||||
"prowler.providers.github.services.organization.organization_default_repository_permission_strict.organization_default_repository_permission_strict.organization_client",
|
||||
new=organization_client,
|
||||
),
|
||||
):
|
||||
from prowler.providers.github.services.organization.organization_default_repository_permission_strict.organization_default_repository_permission_strict import (
|
||||
organization_default_repository_permission_strict,
|
||||
)
|
||||
|
||||
check = organization_default_repository_permission_strict()
|
||||
result = check.execute()
|
||||
assert len(result) == 0
|
||||
@@ -45,11 +45,13 @@ class Test_Organization_Scoping:
|
||||
self.mock_org1.id = 1
|
||||
self.mock_org1.login = "test-org1"
|
||||
self.mock_org1.two_factor_requirement_enabled = True
|
||||
self.mock_org1.default_repository_permission = None
|
||||
|
||||
self.mock_org2 = MagicMock()
|
||||
self.mock_org2.id = 2
|
||||
self.mock_org2.login = "test-org2"
|
||||
self.mock_org2.two_factor_requirement_enabled = False
|
||||
self.mock_org2.default_repository_permission = None
|
||||
|
||||
self.mock_user = MagicMock()
|
||||
self.mock_user.id = 100
|
||||
@@ -175,6 +177,35 @@ class Test_Organization_Scoping:
|
||||
|
||||
assert len(orgs) == 0
|
||||
|
||||
def test_base_permission_extraction(self):
|
||||
"""Test that base_permission is populated from organization's default_repository_permission"""
|
||||
provider = set_mocked_github_provider()
|
||||
provider.repositories = []
|
||||
provider.organizations = ["test-org1"]
|
||||
|
||||
mock_client = MagicMock()
|
||||
# Organization with default_repository_permission set to "read"
|
||||
org_with_perm = MagicMock()
|
||||
org_with_perm.id = 1
|
||||
org_with_perm.login = "test-org1"
|
||||
org_with_perm.two_factor_requirement_enabled = True
|
||||
org_with_perm.default_repository_permission = "read"
|
||||
mock_client.get_organization.return_value = org_with_perm
|
||||
|
||||
with patch(
|
||||
"prowler.providers.github.services.organization.organization_service.GithubService.__init__"
|
||||
):
|
||||
organization_service = Organization(provider)
|
||||
organization_service.clients = [mock_client]
|
||||
organization_service.provider = provider
|
||||
|
||||
orgs = organization_service._list_organizations()
|
||||
|
||||
assert len(orgs) == 1
|
||||
assert 1 in orgs
|
||||
assert orgs[1].name == "test-org1"
|
||||
assert orgs[1].base_permission == "read"
|
||||
|
||||
def test_specific_organization_scoping(self):
|
||||
"""Test that only specified organizations are returned"""
|
||||
provider = set_mocked_github_provider()
|
||||
@@ -287,11 +318,13 @@ class Test_Organization_Scoping:
|
||||
mock_owner_org.id = 1
|
||||
mock_owner_org.login = "owner1"
|
||||
mock_owner_org.two_factor_requirement_enabled = True
|
||||
mock_owner_org.default_repository_permission = None
|
||||
|
||||
mock_specific_org = MagicMock()
|
||||
mock_specific_org.id = 2
|
||||
mock_specific_org.login = "specific-org"
|
||||
mock_specific_org.two_factor_requirement_enabled = False
|
||||
mock_specific_org.default_repository_permission = None
|
||||
|
||||
mock_client.get_organization.side_effect = [
|
||||
mock_owner_org,
|
||||
@@ -393,6 +426,7 @@ class Test_Organization_ErrorHandling:
|
||||
self.mock_org1.id = 1
|
||||
self.mock_org1.login = "test-org1"
|
||||
self.mock_org1.two_factor_requirement_enabled = True
|
||||
self.mock_org1.default_repository_permission = None
|
||||
|
||||
def test_github_api_error_handling(self):
|
||||
"""Test that GitHub API errors are handled properly"""
|
||||
|
||||
+3
-4
@@ -3,7 +3,6 @@ from uuid import uuid4
|
||||
|
||||
from prowler.providers.m365.services.entra.entra_service import (
|
||||
ApplicationsConditions,
|
||||
AuthenticationStrength,
|
||||
ConditionalAccessGrantControl,
|
||||
ConditionalAccessPolicyState,
|
||||
Conditions,
|
||||
@@ -114,7 +113,7 @@ class Test_entra_admin_users_phishing_resistant_mfa_enabled:
|
||||
grant_controls=GrantControls(
|
||||
built_in_controls=[ConditionalAccessGrantControl.BLOCK],
|
||||
operator=GrantControlOperator.AND,
|
||||
authentication_strength=AuthenticationStrength.PHISHING_RESISTANT_MFA,
|
||||
authentication_strength="Phishing-resistant MFA",
|
||||
),
|
||||
session_controls=SessionControls(
|
||||
persistent_browser=PersistentBrowser(
|
||||
@@ -206,7 +205,7 @@ class Test_entra_admin_users_phishing_resistant_mfa_enabled:
|
||||
grant_controls=GrantControls(
|
||||
built_in_controls=[ConditionalAccessGrantControl.BLOCK],
|
||||
operator=GrantControlOperator.AND,
|
||||
authentication_strength=AuthenticationStrength.PHISHING_RESISTANT_MFA,
|
||||
authentication_strength="Phishing-resistant MFA",
|
||||
),
|
||||
session_controls=SessionControls(
|
||||
persistent_browser=PersistentBrowser(
|
||||
@@ -301,7 +300,7 @@ class Test_entra_admin_users_phishing_resistant_mfa_enabled:
|
||||
grant_controls=GrantControls(
|
||||
built_in_controls=[ConditionalAccessGrantControl.BLOCK],
|
||||
operator=GrantControlOperator.AND,
|
||||
authentication_strength=AuthenticationStrength.PHISHING_RESISTANT_MFA,
|
||||
authentication_strength="Phishing-resistant MFA",
|
||||
),
|
||||
session_controls=SessionControls(
|
||||
persistent_browser=PersistentBrowser(
|
||||
|
||||
@@ -7,7 +7,6 @@ from prowler.providers.m365.services.entra.entra_service import (
|
||||
AdminConsentPolicy,
|
||||
AdminRoles,
|
||||
ApplicationsConditions,
|
||||
AuthenticationStrength,
|
||||
AuthorizationPolicy,
|
||||
AuthPolicyRoles,
|
||||
ConditionalAccessGrantControl,
|
||||
@@ -75,7 +74,7 @@ async def mock_entra_get_conditional_access_policies(_):
|
||||
ConditionalAccessGrantControl.COMPLIANT_DEVICE,
|
||||
],
|
||||
operator=GrantControlOperator.OR,
|
||||
authentication_strength=AuthenticationStrength.PHISHING_RESISTANT_MFA,
|
||||
authentication_strength="Phishing-resistant MFA",
|
||||
),
|
||||
session_controls=SessionControls(
|
||||
persistent_browser=PersistentBrowser(
|
||||
@@ -226,7 +225,7 @@ class Test_Entra_Service:
|
||||
ConditionalAccessGrantControl.COMPLIANT_DEVICE,
|
||||
],
|
||||
operator=GrantControlOperator.OR,
|
||||
authentication_strength=AuthenticationStrength.PHISHING_RESISTANT_MFA,
|
||||
authentication_strength="Phishing-resistant MFA",
|
||||
),
|
||||
session_controls=SessionControls(
|
||||
persistent_browser=PersistentBrowser(
|
||||
|
||||
+412
-1
@@ -390,6 +390,7 @@ ui/
|
||||
├── types/ # TypeScript type definitions
|
||||
├── hooks/ # Custom React hooks
|
||||
├── store/ # Zustand state management
|
||||
├── tests/ # Playwright E2E tests
|
||||
└── styles/ # Global CSS & Tailwind config
|
||||
```
|
||||
|
||||
@@ -683,13 +684,423 @@ const text = message.parts
|
||||
|
||||
### Playwright E2E Tests
|
||||
|
||||
**⚠️ MANDATORY: If you have access to Playwright MCP tools, ALWAYS use them to understand the actual application flow before creating any E2E test.**
|
||||
|
||||
- **IF Playwright MCP is available**: Use browser tools to navigate, interact, and understand the real UI behavior FIRST, then create tests
|
||||
- **IF Playwright MCP is NOT available**: Proceed with test creation based on available documentation and code analysis
|
||||
- Add/update E2E tests for critical flows you modify
|
||||
- Scope: run only affected specs when iterating
|
||||
- Commit snapshot updates only with real UI changes
|
||||
- Determinism: avoid relying on real external services; mock or stub where possible
|
||||
- **Organization**: Create a folder under `tests/` for each page (e.g., `tests/sign-in/`, `tests/sign-up/`, etc.)
|
||||
- **File Structure**: Each page folder should contain 3 files:
|
||||
- `{page-name}-page.ts` - Page Object Model
|
||||
- `{page-name}.spec.ts` - Test specifications
|
||||
- `{page-name}.md` - Test documentation
|
||||
- **Base Class**: `tests/base-page.ts` - Parent class that all `{page-name}-page.ts` files should extend
|
||||
- **Helpers**: `tests/helpers.ts` - Utility functions and helper methods for tests
|
||||
|
||||
#### Playwright MCP Integration
|
||||
|
||||
**⚠️ CRITICAL WORKFLOW (When Available): If you have access to Playwright MCP browser tools, use them to explore the application BEFORE writing any test code.**
|
||||
|
||||
**Recommended Steps Before Creating Tests (Only if MCP Tools are Available):**
|
||||
|
||||
1. **Navigate to the application** to reach the target page
|
||||
2. **Take a snapshot** to see the page structure and available elements
|
||||
3. **Interact with forms and elements** to verify the exact user flow
|
||||
4. **Take screenshots** to document expected states at each step
|
||||
5. **Verify page transitions** by navigating through the complete flow to understand all states (loading, success, error)
|
||||
6. **Document actual selectors** from the snapshots - use the real element references (ref) and labels you observe
|
||||
7. **Only after exploring** the complete flow manually, create the test code with the exact selectors and steps you verified
|
||||
|
||||
**Why This Matters (When MCP Tools are Available):**
|
||||
|
||||
- ✅ **Precise test creation** - Only include the exact steps needed, no assumptions or guessing
|
||||
- ✅ **Accurate selectors** - Use the actual DOM structure from real snapshots, not imagined selectors
|
||||
- ✅ **Real flow validation** - Verify the complete user journey actually works as expected
|
||||
- ✅ **Avoid over-engineering** - Create minimal tests that focus on what actually exists
|
||||
- ✅ **Prevent flaky tests** - Tests based on real exploration are more stable and reliable
|
||||
- ❌ **Never assume** - Don't create tests based on assumptions about how the UI "should" work
|
||||
|
||||
**Benefits:**
|
||||
- **Precise test creation** - Only include the exact steps needed for the test requirement
|
||||
- **Accurate selectors** - Use the actual DOM structure to create reliable locators
|
||||
- **Real flow validation** - Verify the complete user journey works as expected
|
||||
- **Avoid over-engineering** - Create minimal tests that focus on the specific requirement
|
||||
|
||||
#### Test Creation Guidelines
|
||||
|
||||
**IMPORTANT: Always ask for clarification if the request is ambiguous about scope.**
|
||||
|
||||
**When creating a specific test:**
|
||||
|
||||
- Create only a single `test()` entry implementing the specific functionality described
|
||||
- Do NOT create the full test suite for this page
|
||||
- **ALWAYS add the test to the page's main spec file** (e.g., `sign-up.spec.ts`), NOT in a separate file
|
||||
- **REUSE existing page objects** from other pages when possible (e.g., use existing SignInPage, HomePage, etc.)
|
||||
- If the page's spec file doesn't exist, create minimal structure:
|
||||
- `{page-name}-page.ts` - Page Object Model
|
||||
- `{page-name}.spec.ts` - Test specifications (add your specific test here)
|
||||
- Focus on the exact requirement without additional test cases
|
||||
- Do NOT create separate files like `{page-name}-critical-path.spec.ts` or `{page-name}-specific-test.spec.ts`
|
||||
|
||||
**When creating comprehensive page tests:**
|
||||
|
||||
- Create the full test suite with all files (page object, spec, documentation)
|
||||
- Include multiple test cases covering various scenarios in `{page-name}.spec.ts`
|
||||
- Follow the complete structure with validation, error handling, accessibility tests
|
||||
- Create comprehensive documentation for all test cases in `{page-name}.md`
|
||||
|
||||
**File Naming Convention:**
|
||||
|
||||
- ✅ **CORRECT**: `sign-up.spec.ts` (contains all sign-up tests)
|
||||
- ✅ **CORRECT**: `sign-up-page.ts` (page object)
|
||||
- ✅ **CORRECT**: `sign-up.md` (documentation for all tests)
|
||||
- ❌ **WRONG**: `sign-up-critical-path.spec.ts` (separate file for specific test)
|
||||
- ❌ **WRONG**: `sign-up-validation.spec.ts` (separate file for specific test)
|
||||
|
||||
**Examples:**
|
||||
|
||||
```typescript
|
||||
// ✅ Specific test request - create only this test
|
||||
test("User can create account and login successfully",{
|
||||
tag: ['@critical', '@e2e', '@signup', '@SIGNUP-E2E-001']
|
||||
} async ({ page }) => {
|
||||
// Implementation for this specific test only
|
||||
});
|
||||
|
||||
// ❌ Don't create full suite when only one test is requested
|
||||
```
|
||||
|
||||
**Request Examples:**
|
||||
|
||||
- **"Create a test for user sign-up"** → Create only the sign-up test, not the full suite
|
||||
- **"Generate E2E tests for the login page"** → Create comprehensive test suite with all scenarios
|
||||
- **"Add a test to verify form validation"** → Add only the validation test to existing spec
|
||||
- **"Create tests for the home page"** → Create full test suite for home functionality
|
||||
- **"Create a new test e2e for sign-up"** → Create only the specific test mentioned
|
||||
- **"Generate comprehensive E2E tests for sign-up"** → Create full test suite
|
||||
|
||||
**Key Phrases to Identify Scope:**
|
||||
|
||||
- **Single Test**: "a test", "one test", "new test", "add test"
|
||||
- **Full Suite**: "comprehensive tests", "all tests", "test suite", "complete tests", "generate tests"
|
||||
|
||||
#### Page Object Model Pattern
|
||||
|
||||
- **Extend BasePage**: All page objects should extend `BasePage` for common functionality
|
||||
- **REUSE Existing Page Objects**: Always check for existing page objects before creating new ones
|
||||
- **Interface Definitions**: Define clear interfaces for form data and credentials
|
||||
- **Method Organization**: Group methods by functionality (navigation, form interaction, validation, etc.)
|
||||
- **Locator Strategy**: Use stable selectors (name attributes, labels) over fragile CSS selectors
|
||||
- **Avoid Code Duplication**: When creating a new page object, verify if there are repeated methods across page objects that should be moved to `BasePage`
|
||||
- **Shared Utilities**: If utility functions are repeated across tests, create or update `tests/helpers.ts` to centralize them
|
||||
- **Refactor to BasePage**: Common patterns like form validation, notification checks, or navigation should be extracted to `BasePage`
|
||||
- **Refactor to Helpers**: Data generation, test setup utilities, or common assertions should be extracted to `tests/helpers.ts`
|
||||
|
||||
#### Page Object Reuse Guidelines
|
||||
|
||||
- **Check existing page objects first**: Look in `tests/` directory for existing page objects
|
||||
- **Import and reuse**: Use existing page objects like `SignInPage`, `HomePage`, etc.
|
||||
- **Create page objects when needed**: If a test requires interaction with a page that doesn't have a page object yet, create it following the Page Object Model pattern
|
||||
- **Only create new page objects** when the page doesn't exist or has unique functionality
|
||||
- **Example**: For a sign-up test that needs to verify login after signup, reuse `SignInPage` and `HomePage` if they exist, or create them if needed
|
||||
- **Avoid duplication**: Don't recreate functionality that already exists in other page objects
|
||||
- **Complete dependencies**: When creating a test that requires multiple page interactions, ensure all necessary page objects exist (create them if they don't)
|
||||
|
||||
#### Code Refactoring Guidelines
|
||||
|
||||
**When to move code to `BasePage`:**
|
||||
|
||||
- ✅ **Navigation helpers** used by multiple pages (e.g., `waitForPageLoad()`, `getCurrentUrl()`)
|
||||
- ✅ **Common UI interactions** (e.g., clicking notifications, handling modals, theme toggles)
|
||||
- ✅ **Verification patterns** repeated across pages (e.g., `isVisible()`, `waitForVisible()`)
|
||||
- ✅ **Error handling** that applies to all pages
|
||||
- ✅ **Screenshot utilities** for debugging
|
||||
|
||||
**When to move code to `tests/helpers.ts`:**
|
||||
|
||||
- ✅ **Test data generation** (e.g., `generateUniqueEmail()`, `generateTestUser()`)
|
||||
- ✅ **Setup/teardown utilities** (e.g., `createTestUser()`, `cleanupTestData()`)
|
||||
- ✅ **Custom assertions** used across tests (e.g., `expectNotificationToContain()`)
|
||||
- ✅ **API helpers** for test setup (e.g., `seedDatabase()`, `resetState()`)
|
||||
- ✅ **Time utilities** (e.g., `waitForCondition()`, `retryAction()`)
|
||||
|
||||
**Example - Before Refactoring:**
|
||||
|
||||
```typescript
|
||||
// ❌ BAD: Repeated code in multiple page objects
|
||||
export class SignUpPage extends BasePage {
|
||||
async waitForNotification(): Promise<void> {
|
||||
await this.page.waitForSelector('[role="status"]');
|
||||
}
|
||||
}
|
||||
|
||||
export class SignInPage extends BasePage {
|
||||
async waitForNotification(): Promise<void> {
|
||||
await this.page.waitForSelector('[role="status"]');
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Example - After Refactoring:**
|
||||
|
||||
```typescript
|
||||
// ✅ GOOD: Move to BasePage
|
||||
export class BasePage {
|
||||
async waitForNotification(): Promise<void> {
|
||||
await this.page.waitForSelector('[role="status"]');
|
||||
}
|
||||
|
||||
async verifyNotificationMessage(message: string): Promise<void> {
|
||||
const notification = this.page.locator('[role="status"]');
|
||||
await expect(notification).toContainText(message);
|
||||
}
|
||||
}
|
||||
|
||||
// ✅ GOOD: Move to helpers.ts for data generation
|
||||
export function generateUniqueEmail(): string {
|
||||
const timestamp = Date.now();
|
||||
return `test.user.${timestamp}@example.com`;
|
||||
}
|
||||
|
||||
export function generateTestUser() {
|
||||
return {
|
||||
name: "Test User",
|
||||
email: generateUniqueEmail(),
|
||||
password: "TestPassword123!",
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
**Page Object Reuse Example:**
|
||||
|
||||
```typescript
|
||||
// ✅ GOOD: Check for existing page objects, create if needed
|
||||
// 1. Check if SignInPage exists - if not, create it
|
||||
// 2. Check if HomePage exists - if not, create it
|
||||
import { SignInPage } from "../sign-in/sign-in-page";
|
||||
import { HomePage } from "../home/home-page";
|
||||
|
||||
test("User can sign up and login", async ({ page }) => {
|
||||
const signUpPage = new SignUpPage(page);
|
||||
const signInPage = new SignInPage(page); // REUSE existing (or create if missing)
|
||||
const homePage = new HomePage(page); // REUSE existing (or create if missing)
|
||||
|
||||
// Use existing functionality
|
||||
await signUpPage.signUp(userData);
|
||||
await homePage.verifyPageLoaded(); // REUSE existing method
|
||||
await homePage.signOut(); // REUSE existing method
|
||||
await signInPage.login(credentials); // REUSE existing method
|
||||
});
|
||||
|
||||
// ❌ BAD: Don't recreate existing functionality in SignUpPage
|
||||
export class SignUpPage extends BasePage {
|
||||
// Don't recreate logout functionality
|
||||
async logout() {
|
||||
/* ... */
|
||||
} // ❌ HomePage already has this
|
||||
|
||||
// Don't recreate login functionality
|
||||
async login() {
|
||||
/* ... */
|
||||
} // ❌ SignInPage already has this
|
||||
|
||||
// ✅ GOOD: Instead, use composition or delegation
|
||||
async loginAfterSignUp(credentials: LoginCredentials): Promise<void> {
|
||||
// Reuse SignInPage methods or delegate to it
|
||||
const emailField = this.page.getByRole("textbox", { name: "Email*" });
|
||||
const passwordField = this.page.getByRole("textbox", { name: "Password*" });
|
||||
const loginButton = this.page.getByRole("button", { name: "Log in" });
|
||||
|
||||
await emailField.fill(credentials.email);
|
||||
await passwordField.fill(credentials.password);
|
||||
await loginButton.click();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Page Object Structure:**
|
||||
|
||||
```typescript
|
||||
export interface FeatureData {
|
||||
email: string;
|
||||
password: string;
|
||||
// ... other fields
|
||||
}
|
||||
|
||||
export class FeaturePage extends BasePage {
|
||||
// Form elements
|
||||
readonly emailInput: Locator;
|
||||
readonly passwordInput: Locator;
|
||||
readonly submitButton: Locator;
|
||||
|
||||
constructor(page: Page) {
|
||||
super(page);
|
||||
// Use stable selectors
|
||||
this.emailInput = page.getByLabel("Email");
|
||||
this.passwordInput = page.locator('input[name="password"]');
|
||||
this.submitButton = page.getByRole("button", { name: "Submit" });
|
||||
}
|
||||
|
||||
async goto(): Promise<void> {
|
||||
await super.goto("/feature-path");
|
||||
}
|
||||
|
||||
async performAction(data: FeatureData): Promise<void> {
|
||||
await this.emailInput.fill(data.email);
|
||||
await this.passwordInput.fill(data.password);
|
||||
await this.submitButton.click();
|
||||
}
|
||||
|
||||
async verifyCriticalOutcome(): Promise<void> {
|
||||
await expect(this.page).toHaveURL("/expected-path");
|
||||
// ... verification logic
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Test Structure Best Practices
|
||||
|
||||
- **Page Object Usage**: Use Page Object Models for all page interactions
|
||||
- **Tag Organization**: Use Playwright tag syntax for test categorization
|
||||
- **Test IDs**: Include test case IDs in tags for traceability
|
||||
- **Verification Steps**: Include clear verification steps for each major action
|
||||
|
||||
**Key Elements:**
|
||||
|
||||
- **Page Objects**: All interactions through Page Object Models
|
||||
- **Clear Tags**: Use `{ tag: ['@priority', '@type', '@feature', '@test-id'] }` syntax
|
||||
- **Verification**: Explicit verification of critical outcomes
|
||||
|
||||
#### Playwright Selector Best Practices
|
||||
|
||||
When creating locators in Page Objects, follow this priority order for maximum reliability:
|
||||
|
||||
**✅ Primary Selectors (Recommended):**
|
||||
|
||||
- **`getByRole()`**: The best and most robust for all interactive elements (buttons, links, main sections)
|
||||
- **`getByLabel()`**: The best for form controls that have an associated label
|
||||
|
||||
**⚠️ Secondary Selectors (Use Sparingly):**
|
||||
|
||||
- **`getByText()`**: Use only when the above fail or for static text verification (headings, paragraphs, messages)
|
||||
- **Others (e.g. `getByTestId()`)**: Use only as a last resort when the above fail or are not applicable
|
||||
|
||||
**Examples:**
|
||||
|
||||
```typescript
|
||||
// ✅ GOOD - Using getByRole for interactive elements
|
||||
this.submitButton = page.getByRole("button", { name: "Submit" });
|
||||
this.navigationLink = page.getByRole("link", { name: "Dashboard" });
|
||||
|
||||
// ✅ GOOD - Using getByLabel for form controls
|
||||
this.emailInput = page.getByLabel("Email");
|
||||
this.passwordInput = page.getByLabel("Password");
|
||||
|
||||
// ⚠️ SPARINGLY - Using getByText only when necessary
|
||||
this.errorMessage = page.getByText("Invalid credentials"); // Only if no better selector exists
|
||||
this.pageTitle = page.getByText("Welcome to Prowler"); // Only for static content verification
|
||||
|
||||
// ❌ AVOID - Using fragile selectors when better options exist
|
||||
this.submitButton = page.locator(".btn-primary"); // Use getByRole instead
|
||||
this.emailInput = page.locator("#email"); // Use getByLabel instead
|
||||
```
|
||||
|
||||
**Tag Syntax Example:**
|
||||
|
||||
```typescript
|
||||
test(
|
||||
"Test description",
|
||||
{ tag: ["@critical", "@e2e", "@signup", "@SIGNUP-E2E-001"] },
|
||||
async ({ page }) => {
|
||||
// Test implementation
|
||||
},
|
||||
);
|
||||
```
|
||||
|
||||
#### E2E Test Documentation Format
|
||||
|
||||
Each test documentation file (`{page-name}.md`) should follow this structured format:
|
||||
|
||||
```markdown
|
||||
### E2E Tests: {Feature Name}
|
||||
|
||||
**Suite ID:** `{SUITE-ID}`
|
||||
**Feature:** {Feature description}
|
||||
|
||||
---
|
||||
|
||||
## Test Case: `{TEST-ID}` - {Test case title}
|
||||
|
||||
**Priority:** `{critical|high|medium|low}`
|
||||
|
||||
**Tags:**
|
||||
|
||||
- type → @e2e
|
||||
- feature → @{feature-name}
|
||||
|
||||
**Description/Objective:** {Brief description of what the test validates}
|
||||
|
||||
**Preconditions:**
|
||||
|
||||
- {List of prerequisites for the test to run}
|
||||
- {Any required data or state}
|
||||
|
||||
### Flow Steps:
|
||||
|
||||
1. {Step 1 description}
|
||||
2. {Step 2 description}
|
||||
3. {Step 3 description}
|
||||
...
|
||||
|
||||
### Expected Result:
|
||||
|
||||
- {Expected outcome 1}
|
||||
- {Expected outcome 2}
|
||||
...
|
||||
|
||||
### Key verification points:
|
||||
|
||||
- {Key assertion 1}
|
||||
- {Key assertion 2}
|
||||
- {Key assertion 3}
|
||||
|
||||
### Notes:
|
||||
|
||||
- {Any additional notes or considerations}
|
||||
- {Test data requirements or constraints}
|
||||
```
|
||||
|
||||
#### Test Documentation Best Practices
|
||||
- **Suite ID Format**: Use descriptive suite IDs (e.g., `SIGNUP-E2E`)
|
||||
- **Test ID Format**: Include feature and sequence (e.g., `SIGNUP-E2E-001`)
|
||||
- **Priority Levels**: Use `critical`, `high`, `medium`, `low` for test prioritization
|
||||
- **Tag Organization**: Use Playwright tag syntax: `{ tag: ['@priority', '@type', '@feature', '@test-id'] }`
|
||||
- **Flow Steps**: Number steps clearly and describe user actions
|
||||
- **Verification Points**: List specific assertions and expected outcomes
|
||||
- **Preconditions**: Document any required setup or data dependencies
|
||||
- **Test Data Notes**: Include information about data generation and uniqueness strategies
|
||||
|
||||
**Tag Categories:**
|
||||
- **Priority**: `@critical`, `@high`, `@medium`, `@low`
|
||||
- **Type**: `@e2e`
|
||||
- **Feature**: `@signup`, `@signin`, `@dashboard`
|
||||
- **Test ID**: `@SIGNUP-E2E-001`, `@LOGIN-E2E-002`
|
||||
|
||||
**IMPORTANT - Keep Documentation Concise:**
|
||||
- ❌ **DO NOT** include general test running instructions
|
||||
- ❌ **DO NOT** include file structure explanations
|
||||
- ❌ **DO NOT** include code examples or tutorials
|
||||
- ❌ **DO NOT** include extensive troubleshooting sections
|
||||
- ❌ **DO NOT** include command references or configuration details
|
||||
- ✅ **DO** focus only on the specific test case: flow, preconditions, expected results, and verification points
|
||||
- ✅ **DO** keep the documentation under 60 lines when possible
|
||||
- ✅ **DO** follow the exact format template provided above
|
||||
|
||||
|
||||
### Component Testing (Future)
|
||||
|
||||
- Jest + React Testing Library
|
||||
- Component unit tests
|
||||
- Integration tests for complex flows
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
|
||||
All notable changes to the **Prowler UI** are documented in this file.
|
||||
|
||||
## [1.13.0] (Prowler UNRELEASED)
|
||||
## [1.13.0] (Prowler v5.13.0)
|
||||
|
||||
### 🚀 Added
|
||||
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
"use client";
|
||||
|
||||
import { Bell, BellOff, ShieldCheck, TriangleAlert } from "lucide-react";
|
||||
|
||||
import { DonutChart } from "@/components/graphs/donut-chart";
|
||||
import { DonutDataPoint } from "@/components/graphs/types";
|
||||
import {
|
||||
BaseCard,
|
||||
CardContent,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
ResourceStatsCard,
|
||||
StatsContainer,
|
||||
} from "@/components/shadcn";
|
||||
import { CardVariant } from "@/components/shadcn/card/resource-stats-card/resource-stats-card-content";
|
||||
|
||||
interface CheckFindingsProps {
|
||||
failFindingsData: {
|
||||
total: number;
|
||||
new: number;
|
||||
muted: number;
|
||||
};
|
||||
passFindingsData: {
|
||||
total: number;
|
||||
new: number;
|
||||
muted: number;
|
||||
};
|
||||
}
|
||||
|
||||
export const CheckFindings = ({
|
||||
failFindingsData,
|
||||
passFindingsData,
|
||||
}: CheckFindingsProps) => {
|
||||
// Calculate total findings
|
||||
const totalFindings = failFindingsData.total + passFindingsData.total;
|
||||
|
||||
// Calculate percentages
|
||||
const failPercentage = Math.round(
|
||||
(failFindingsData.total / totalFindings) * 100,
|
||||
);
|
||||
const passPercentage = Math.round(
|
||||
(passFindingsData.total / totalFindings) * 100,
|
||||
);
|
||||
|
||||
// Calculate change percentages (new findings as percentage change)
|
||||
const failChange =
|
||||
failFindingsData.total > 0
|
||||
? Math.round((failFindingsData.new / failFindingsData.total) * 100)
|
||||
: 0;
|
||||
const passChange =
|
||||
passFindingsData.total > 0
|
||||
? Math.round((passFindingsData.new / passFindingsData.total) * 100)
|
||||
: 0;
|
||||
|
||||
// Mock data for DonutChart
|
||||
const donutData: DonutDataPoint[] = [
|
||||
{
|
||||
name: "Fail Findings",
|
||||
value: failFindingsData.total,
|
||||
color: "#f43f5e", // Rose-500
|
||||
percentage: Number(failPercentage),
|
||||
change: Number(failChange),
|
||||
},
|
||||
{
|
||||
name: "Pass Findings",
|
||||
value: passFindingsData.total,
|
||||
color: "#4ade80", // Green-400
|
||||
percentage: Number(passPercentage),
|
||||
change: Number(passChange),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<BaseCard>
|
||||
{/* Header */}
|
||||
<CardHeader>
|
||||
<CardTitle>Check Findings</CardTitle>
|
||||
</CardHeader>
|
||||
|
||||
{/* DonutChart Content */}
|
||||
<CardContent className="space-y-4">
|
||||
<div className="mx-auto max-h-[200px] max-w-[200px]">
|
||||
<DonutChart
|
||||
data={donutData}
|
||||
showLegend={false}
|
||||
innerRadius={66}
|
||||
outerRadius={86}
|
||||
centerLabel={{
|
||||
value: totalFindings.toLocaleString(),
|
||||
label: "Total Findings",
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Footer with ResourceStatsCards */}
|
||||
<StatsContainer>
|
||||
<ResourceStatsCard
|
||||
containerless
|
||||
badge={{
|
||||
icon: TriangleAlert,
|
||||
count: failFindingsData.total,
|
||||
variant: CardVariant.fail,
|
||||
}}
|
||||
label="Fail Findings"
|
||||
stats={[
|
||||
{ icon: Bell, label: `${failFindingsData.new} New` },
|
||||
{ icon: BellOff, label: `${failFindingsData.muted} Muted` },
|
||||
]}
|
||||
className="flex-1"
|
||||
/>
|
||||
|
||||
<div className="flex items-center justify-center px-[46px]">
|
||||
<div className="h-full w-px bg-slate-300 dark:bg-[rgba(39,39,42,1)]" />
|
||||
</div>
|
||||
|
||||
<ResourceStatsCard
|
||||
containerless
|
||||
badge={{
|
||||
icon: ShieldCheck,
|
||||
count: passFindingsData.total,
|
||||
variant: CardVariant.pass,
|
||||
}}
|
||||
label="Pass Findings"
|
||||
stats={[
|
||||
{ icon: Bell, label: `${passFindingsData.new} New` },
|
||||
{ icon: BellOff, label: `${passFindingsData.muted} Muted` },
|
||||
]}
|
||||
className="flex-1"
|
||||
/>
|
||||
</StatsContainer>
|
||||
</CardContent>
|
||||
</BaseCard>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,87 @@
|
||||
import { Suspense } from "react";
|
||||
|
||||
import { getFindingsByStatus } from "@/actions/overview/overview";
|
||||
import { ContentLayout } from "@/components/ui";
|
||||
import { SearchParamsProps } from "@/types";
|
||||
|
||||
import { CheckFindings } from "./components/check-findings";
|
||||
|
||||
const FILTER_PREFIX = "filter[";
|
||||
|
||||
// Extract only query params that start with "filter[" for API calls
|
||||
function pickFilterParams(
|
||||
params: SearchParamsProps | undefined | null,
|
||||
): Record<string, string | string[] | undefined> {
|
||||
if (!params) return {};
|
||||
return Object.fromEntries(
|
||||
Object.entries(params).filter(([key]) => key.startsWith(FILTER_PREFIX)),
|
||||
);
|
||||
}
|
||||
|
||||
export default async function NewOverviewPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<SearchParamsProps>;
|
||||
}) {
|
||||
const resolvedSearchParams = await searchParams;
|
||||
|
||||
return (
|
||||
<ContentLayout title="New Overview" icon="lucide:square-chart-gantt">
|
||||
<div className="flex min-h-[60vh] items-center justify-center p-6">
|
||||
<Suspense
|
||||
fallback={
|
||||
<div className="flex h-[400px] w-full max-w-md items-center justify-center rounded-xl border border-zinc-900 bg-stone-950">
|
||||
<p className="text-zinc-400">Loading...</p>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<SSRCheckFindings searchParams={resolvedSearchParams} />
|
||||
</Suspense>
|
||||
</div>
|
||||
</ContentLayout>
|
||||
);
|
||||
}
|
||||
|
||||
const SSRCheckFindings = async ({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: SearchParamsProps | undefined | null;
|
||||
}) => {
|
||||
const filters = pickFilterParams(searchParams);
|
||||
|
||||
const findingsByStatus = await getFindingsByStatus({ filters });
|
||||
|
||||
if (!findingsByStatus) {
|
||||
return (
|
||||
<div className="flex h-[400px] w-full max-w-md items-center justify-center rounded-xl border border-zinc-900 bg-stone-950">
|
||||
<p className="text-zinc-400">Failed to load findings data</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const {
|
||||
fail = 0,
|
||||
pass = 0,
|
||||
muted_new = 0,
|
||||
muted_changed = 0,
|
||||
fail_new = 0,
|
||||
pass_new = 0,
|
||||
} = findingsByStatus?.data?.attributes || {};
|
||||
|
||||
const mutedTotal = muted_new + muted_changed;
|
||||
|
||||
return (
|
||||
<CheckFindings
|
||||
failFindingsData={{
|
||||
total: fail,
|
||||
new: fail_new,
|
||||
muted: mutedTotal,
|
||||
}}
|
||||
passFindingsData={{
|
||||
total: pass,
|
||||
new: pass_new,
|
||||
muted: mutedTotal,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
};
|
||||
@@ -21,44 +21,39 @@ interface DonutChartProps {
|
||||
}
|
||||
|
||||
const CustomTooltip = ({ active, payload }: any) => {
|
||||
if (active && payload && payload.length) {
|
||||
const data = payload[0].payload;
|
||||
return (
|
||||
<div
|
||||
className="rounded-lg border p-3 shadow-lg"
|
||||
style={{
|
||||
backgroundColor: "var(--chart-background)",
|
||||
borderColor: "var(--chart-border-emphasis)",
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<div
|
||||
className="h-3 w-3 rounded-sm"
|
||||
style={{ backgroundColor: data.color }}
|
||||
/>
|
||||
<span
|
||||
className="text-sm font-semibold"
|
||||
style={{ color: "var(--chart-text-primary)" }}
|
||||
>
|
||||
{data.percentage}% {data.name}
|
||||
</span>
|
||||
</div>
|
||||
{data.change !== undefined && (
|
||||
<p
|
||||
className="mt-2 text-xs"
|
||||
style={{ color: "var(--chart-text-secondary)" }}
|
||||
>
|
||||
<span className="font-bold">
|
||||
{data.change > 0 ? "+" : ""}
|
||||
{data.change}%
|
||||
</span>{" "}
|
||||
Since last scan
|
||||
</p>
|
||||
)}
|
||||
if (!active || !payload || !payload.length) return null;
|
||||
|
||||
const entry = payload[0];
|
||||
const name = entry.name;
|
||||
const percentage = entry.payload?.percentage;
|
||||
const color = entry.color || entry.payload?.color;
|
||||
const change = entry.payload?.change;
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border border-slate-200 bg-white p-3 shadow-lg dark:border-slate-600 dark:bg-slate-800">
|
||||
<div className="flex items-center gap-1">
|
||||
<div
|
||||
className="h-3 w-3 rounded-sm"
|
||||
style={{ backgroundColor: color }}
|
||||
/>
|
||||
<span className="text-sm font-semibold text-slate-600 dark:text-zinc-300">
|
||||
{percentage}%
|
||||
</span>
|
||||
<span>{name}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
<p className="mt-1 text-xs text-slate-600 dark:text-zinc-300">
|
||||
{change !== undefined && (
|
||||
<>
|
||||
<span className="font-bold">
|
||||
{change > 0 ? "+" : ""}
|
||||
{change}%
|
||||
</span>
|
||||
<span> Since Last Scan</span>
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const CustomLegend = ({ payload }: any) => {
|
||||
@@ -72,8 +67,8 @@ const CustomLegend = ({ payload }: any) => {
|
||||
|
||||
export function DonutChart({
|
||||
data,
|
||||
innerRadius = 80,
|
||||
outerRadius = 120,
|
||||
innerRadius = 68,
|
||||
outerRadius = 86,
|
||||
showLegend = true,
|
||||
centerLabel,
|
||||
}: DonutChartProps) {
|
||||
@@ -108,7 +103,7 @@ export function DonutChart({
|
||||
}));
|
||||
|
||||
return (
|
||||
<div>
|
||||
<>
|
||||
<ChartContainer
|
||||
config={chartConfig}
|
||||
className="mx-auto aspect-square max-h-[350px]"
|
||||
@@ -122,7 +117,7 @@ export function DonutChart({
|
||||
innerRadius={innerRadius}
|
||||
outerRadius={outerRadius}
|
||||
strokeWidth={0}
|
||||
paddingAngle={2}
|
||||
paddingAngle={0}
|
||||
>
|
||||
{chartData.map((entry, index) => {
|
||||
const opacity =
|
||||
@@ -157,9 +152,9 @@ export function DonutChart({
|
||||
<tspan
|
||||
x={viewBox.cx}
|
||||
y={viewBox.cy}
|
||||
className="text-3xl font-bold"
|
||||
className="text-3xl font-bold text-black dark:text-white"
|
||||
style={{
|
||||
fill: "var(--chart-text-primary)",
|
||||
fill: "currentColor",
|
||||
}}
|
||||
>
|
||||
{formattedValue}
|
||||
@@ -167,8 +162,9 @@ export function DonutChart({
|
||||
<tspan
|
||||
x={viewBox.cx}
|
||||
y={(viewBox.cy || 0) + 24}
|
||||
className="text-black dark:text-white"
|
||||
style={{
|
||||
fill: "var(--chart-text-secondary)",
|
||||
fill: "currentColor",
|
||||
}}
|
||||
>
|
||||
{centerLabel.label}
|
||||
@@ -183,6 +179,6 @@ export function DonutChart({
|
||||
</PieChart>
|
||||
</ChartContainer>
|
||||
{showLegend && <CustomLegend payload={legendPayload} />}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@ export function ChartTooltip({
|
||||
|
||||
return (
|
||||
<div
|
||||
className="min-w-[200px] rounded-lg border p-3 shadow-lg"
|
||||
className="min-w-[200px] rounded-lg border border-slate-200 bg-white p-3 shadow-lg dark:border-slate-600 dark:bg-slate-800"
|
||||
style={{
|
||||
borderColor: CHART_COLORS.tooltipBorder,
|
||||
backgroundColor: CHART_COLORS.tooltipBackground,
|
||||
@@ -45,15 +45,12 @@ export function ChartTooltip({
|
||||
style={{ backgroundColor: color }}
|
||||
/>
|
||||
)}
|
||||
<p
|
||||
className="text-sm font-semibold"
|
||||
style={{ color: CHART_COLORS.textPrimary }}
|
||||
>
|
||||
<p className="text-sm font-semibold text-slate-900 dark:text-white">
|
||||
{label || data.name}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<p className="mt-1 text-xs" style={{ color: CHART_COLORS.textPrimary }}>
|
||||
<p className="mt-1 text-xs text-slate-900 dark:text-white">
|
||||
{typeof data.value === "number"
|
||||
? data.value.toLocaleString()
|
||||
: data.value}
|
||||
@@ -62,11 +59,8 @@ export function ChartTooltip({
|
||||
|
||||
{data.newFindings !== undefined && data.newFindings > 0 && (
|
||||
<div className="mt-1 flex items-center gap-2">
|
||||
<Bell size={14} style={{ color: "var(--chart-fail)" }} />
|
||||
<span
|
||||
className="text-xs"
|
||||
style={{ color: CHART_COLORS.textSecondary }}
|
||||
>
|
||||
<Bell size={14} className="text-slate-600 dark:text-slate-400" />
|
||||
<span className="text-xs text-slate-600 dark:text-slate-400">
|
||||
{data.newFindings} New Findings
|
||||
</span>
|
||||
</div>
|
||||
@@ -74,11 +68,8 @@ export function ChartTooltip({
|
||||
|
||||
{data.new !== undefined && data.new > 0 && (
|
||||
<div className="mt-1 flex items-center gap-2">
|
||||
<Bell size={14} style={{ color: "var(--chart-fail)" }} />
|
||||
<span
|
||||
className="text-xs"
|
||||
style={{ color: CHART_COLORS.textSecondary }}
|
||||
>
|
||||
<Bell size={14} className="text-slate-600 dark:text-slate-400" />
|
||||
<span className="text-xs text-slate-600 dark:text-slate-400">
|
||||
{data.new} New
|
||||
</span>
|
||||
</div>
|
||||
@@ -86,21 +77,15 @@ export function ChartTooltip({
|
||||
|
||||
{data.muted !== undefined && data.muted > 0 && (
|
||||
<div className="mt-1 flex items-center gap-2">
|
||||
<VolumeX size={14} style={{ color: CHART_COLORS.textSecondary }} />
|
||||
<span
|
||||
className="text-xs"
|
||||
style={{ color: CHART_COLORS.textSecondary }}
|
||||
>
|
||||
<VolumeX size={14} className="text-slate-600 dark:text-slate-400" />
|
||||
<span className="text-xs text-slate-600 dark:text-slate-400">
|
||||
{data.muted} Muted
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{data.change !== undefined && (
|
||||
<p
|
||||
className="mt-1 text-xs"
|
||||
style={{ color: CHART_COLORS.textSecondary }}
|
||||
>
|
||||
<p className="mt-1 text-xs text-slate-600 dark:text-slate-400">
|
||||
<span className="font-bold">
|
||||
{data.change > 0 ? "+" : ""}
|
||||
{data.change}%
|
||||
@@ -125,17 +110,8 @@ export function MultiSeriesChartTooltip({
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className="min-w-[200px] rounded-lg border p-3 shadow-lg"
|
||||
style={{
|
||||
borderColor: CHART_COLORS.tooltipBorder,
|
||||
backgroundColor: CHART_COLORS.tooltipBackground,
|
||||
}}
|
||||
>
|
||||
<p
|
||||
className="mb-2 text-sm font-semibold"
|
||||
style={{ color: CHART_COLORS.textPrimary }}
|
||||
>
|
||||
<div className="min-w-[200px] rounded-lg border border-slate-200 bg-white p-3 shadow-lg dark:border-slate-600 dark:bg-slate-800">
|
||||
<p className="mb-2 text-sm font-semibold text-slate-900 dark:text-white">
|
||||
{label}
|
||||
</p>
|
||||
|
||||
@@ -145,20 +121,14 @@ export function MultiSeriesChartTooltip({
|
||||
className="h-2 w-2 rounded-full"
|
||||
style={{ backgroundColor: entry.color }}
|
||||
/>
|
||||
<span className="text-xs" style={{ color: CHART_COLORS.textPrimary }}>
|
||||
<span className="text-xs text-slate-900 dark:text-white">
|
||||
{entry.name}:
|
||||
</span>
|
||||
<span
|
||||
className="text-xs font-semibold"
|
||||
style={{ color: CHART_COLORS.textPrimary }}
|
||||
>
|
||||
<span className="text-xs font-semibold text-slate-900 dark:text-white">
|
||||
{entry.value}
|
||||
</span>
|
||||
{entry.payload[`${entry.dataKey}_change`] && (
|
||||
<span
|
||||
className="text-xs"
|
||||
style={{ color: CHART_COLORS.textSecondary }}
|
||||
>
|
||||
<span className="text-xs text-slate-600 dark:text-slate-400">
|
||||
({entry.payload[`${entry.dataKey}_change`] > 0 ? "+" : ""}
|
||||
{entry.payload[`${entry.dataKey}_change`]}%)
|
||||
</span>
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
import { tv } from "tailwind-variants";
|
||||
|
||||
export const title = tv({
|
||||
base: "tracking-tight inline font-semibold",
|
||||
variants: {
|
||||
color: {
|
||||
violet: "from-[#FF1CF7] to-[#b249f8]",
|
||||
yellow: "from-[#FF705B] to-[#FFB457]",
|
||||
blue: "from-[#5EA2EF] to-[#0072F5]",
|
||||
cyan: "from-[#00b7fa] to-[#01cfea]",
|
||||
green: "from-[#6FEE8D] to-[#17c964]",
|
||||
pink: "from-[#FF72E1] to-[#F54C7A]",
|
||||
foreground: "dark:from-[#FFFFFF] dark:to-[#4B4B4B]",
|
||||
},
|
||||
size: {
|
||||
sm: "text-3xl lg:text-4xl",
|
||||
md: "text-[2.3rem] lg:text-5xl leading-9",
|
||||
lg: "text-4xl lg:text-6xl",
|
||||
},
|
||||
fullWidth: {
|
||||
true: "w-full block",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
size: "md",
|
||||
},
|
||||
compoundVariants: [
|
||||
{
|
||||
color: [
|
||||
"violet",
|
||||
"yellow",
|
||||
"blue",
|
||||
"cyan",
|
||||
"green",
|
||||
"pink",
|
||||
"foreground",
|
||||
],
|
||||
class: "bg-clip-text text-transparent bg-linear-to-b",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
export const subtitle = tv({
|
||||
base: "w-full md:w-1/2 my-2 text-lg lg:text-xl text-default-600 block max-w-full",
|
||||
variants: {
|
||||
fullWidth: {
|
||||
true: "w-full!",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
fullWidth: true,
|
||||
},
|
||||
});
|
||||
@@ -4,13 +4,18 @@ This directory contains all shadcn/ui based components for the Prowler applicati
|
||||
|
||||
## Directory Structure
|
||||
|
||||
Example of a custom component:
|
||||
|
||||
```
|
||||
shadcn/
|
||||
├── card.tsx # shadcn Card component
|
||||
├── resource-stats-card/ # Custom ResourceStatsCard built on shadcn
|
||||
│ ├── resource-stats-card.tsx
|
||||
│ ├── resource-stats-card.example.tsx
|
||||
│ └── index.ts
|
||||
├── card/
|
||||
│ ├── base-card/
|
||||
│ │ ├── base-card.tsx
|
||||
│ ├── card/
|
||||
│ │ ├── card.tsx
|
||||
│ └── resource-stats-card/
|
||||
│ ├── resource-stats-card.tsx
|
||||
│ ├── resource-stats-card.example.tsx
|
||||
├── index.ts # Barrel exports
|
||||
└── README.md
|
||||
```
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
import { Card } from "../card";
|
||||
|
||||
const baseCardVariants = cva("", {
|
||||
variants: {
|
||||
variant: {
|
||||
default:
|
||||
"border-slate-200 bg-white dark:border-zinc-900 dark:bg-stone-950",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
});
|
||||
|
||||
interface BaseCardProps
|
||||
extends React.ComponentProps<typeof Card>,
|
||||
VariantProps<typeof baseCardVariants> {}
|
||||
|
||||
const BaseCard = ({ className, variant, ...props }: BaseCardProps) => {
|
||||
return (
|
||||
<Card
|
||||
className={cn(
|
||||
baseCardVariants({ variant }),
|
||||
"gap-2 px-[18px] pt-3 pb-4",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export { BaseCard };
|
||||
@@ -1,5 +1,3 @@
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
function Card({ className, ...props }: React.ComponentProps<"div">) {
|
||||
@@ -20,7 +18,7 @@ function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
<div
|
||||
data-slot="card-header"
|
||||
className={cn(
|
||||
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
|
||||
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
@@ -32,7 +30,10 @@ function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-title"
|
||||
className={cn("leading-none font-semibold", className)}
|
||||
className={cn(
|
||||
"my-2 text-[18px] leading-none text-slate-900 dark:text-white",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
+8
-8
@@ -33,11 +33,11 @@ const badgeVariants = cva(
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
[CardVariant.default]: "bg-[#535359]",
|
||||
[CardVariant.fail]: "bg-[#432232]",
|
||||
[CardVariant.pass]: "bg-[#204237]",
|
||||
[CardVariant.warning]: "bg-[#3d3520]",
|
||||
[CardVariant.info]: "bg-[#1e3a5f]",
|
||||
[CardVariant.default]: "bg-slate-100 dark:bg-[#535359]",
|
||||
[CardVariant.fail]: "bg-red-100 dark:bg-[#432232]",
|
||||
[CardVariant.pass]: "bg-green-100 dark:bg-[#204237]",
|
||||
[CardVariant.warning]: "bg-amber-100 dark:bg-[#3d3520]",
|
||||
[CardVariant.info]: "bg-blue-100 dark:bg-[#1e3a5f]",
|
||||
},
|
||||
size: {
|
||||
sm: "px-1 text-xs",
|
||||
@@ -66,7 +66,7 @@ const badgeIconVariants = cva("", {
|
||||
});
|
||||
|
||||
const labelTextVariants = cva(
|
||||
"leading-6 font-semibold text-zinc-300 dark:text-zinc-300",
|
||||
"leading-6 font-semibold text-slate-900 dark:text-zinc-300 whitespace-nowrap",
|
||||
{
|
||||
variants: {
|
||||
size: {
|
||||
@@ -81,7 +81,7 @@ const labelTextVariants = cva(
|
||||
},
|
||||
);
|
||||
|
||||
const statIconVariants = cva("text-zinc-300 dark:text-zinc-300", {
|
||||
const statIconVariants = cva("text-slate-600 dark:text-zinc-300", {
|
||||
variants: {
|
||||
size: {
|
||||
sm: "h-2.5 w-2.5",
|
||||
@@ -95,7 +95,7 @@ const statIconVariants = cva("text-zinc-300 dark:text-zinc-300", {
|
||||
});
|
||||
|
||||
const statLabelVariants = cva(
|
||||
"leading-5 font-medium text-zinc-300 dark:text-zinc-300",
|
||||
"leading-5 font-medium text-slate-700 dark:text-zinc-300",
|
||||
{
|
||||
variants: {
|
||||
size: {
|
||||
+2
-2
@@ -111,7 +111,7 @@ export const ResourceStatsCard = ({
|
||||
{header && <ResourceStatsCardHeader {...header} size={resolvedSize} />}
|
||||
{emptyState ? (
|
||||
<div className="flex h-[51px] w-full flex-col items-center justify-center">
|
||||
<p className="text-center text-sm leading-5 font-medium text-zinc-300 dark:text-zinc-300">
|
||||
<p className="text-center text-sm leading-5 font-medium text-slate-600 dark:text-zinc-300">
|
||||
{emptyState.message}
|
||||
</p>
|
||||
</div>
|
||||
@@ -141,7 +141,7 @@ export const ResourceStatsCard = ({
|
||||
{header && <ResourceStatsCardHeader {...header} size={resolvedSize} />}
|
||||
{emptyState ? (
|
||||
<div className="flex h-[51px] w-full flex-col items-center justify-center">
|
||||
<p className="text-center text-sm leading-5 font-medium text-zinc-300 dark:text-zinc-300">
|
||||
<p className="text-center text-sm leading-5 font-medium text-slate-600 dark:text-zinc-300">
|
||||
{emptyState.message}
|
||||
</p>
|
||||
</div>
|
||||
@@ -0,0 +1,25 @@
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface StatsContainerProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
const StatsContainer = ({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: StatsContainerProps) => {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex rounded-xl border border-slate-200 bg-white px-[19px] py-[9px] dark:border-[rgba(38,38,38,0.7)] dark:bg-[rgba(23,23,23,0.5)] dark:backdrop-blur-[46px]",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export { StatsContainer };
|
||||
@@ -1,21 +1,8 @@
|
||||
export {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardFooter,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "./card";
|
||||
export {
|
||||
ResourceStatsCard,
|
||||
ResourceStatsCardContainer,
|
||||
type ResourceStatsCardContainerProps,
|
||||
ResourceStatsCardContent,
|
||||
type ResourceStatsCardContentProps,
|
||||
ResourceStatsCardDivider,
|
||||
type ResourceStatsCardDividerProps,
|
||||
ResourceStatsCardHeader,
|
||||
type ResourceStatsCardHeaderProps,
|
||||
type ResourceStatsCardProps,
|
||||
type StatItem,
|
||||
} from "./resource-stats-card";
|
||||
export * from "./card/base-card/base-card";
|
||||
export * from "./card/card";
|
||||
export * from "./card/resource-stats-card/resource-stats-card";
|
||||
export * from "./card/resource-stats-card/resource-stats-card-container";
|
||||
export * from "./card/resource-stats-card/resource-stats-card-content";
|
||||
export * from "./card/resource-stats-card/resource-stats-card-divider";
|
||||
export * from "./card/resource-stats-card/resource-stats-card-header";
|
||||
export * from "./card/stats-container";
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
export type { ResourceStatsCardProps } from "./resource-stats-card";
|
||||
export { ResourceStatsCard } from "./resource-stats-card";
|
||||
export type { ResourceStatsCardContainerProps } from "./resource-stats-card-container";
|
||||
export { ResourceStatsCardContainer } from "./resource-stats-card-container";
|
||||
export type {
|
||||
ResourceStatsCardContentProps,
|
||||
StatItem,
|
||||
} from "./resource-stats-card-content";
|
||||
export { ResourceStatsCardContent } from "./resource-stats-card-content";
|
||||
export type { ResourceStatsCardDividerProps } from "./resource-stats-card-divider";
|
||||
export { ResourceStatsCardDivider } from "./resource-stats-card-divider";
|
||||
export type { ResourceStatsCardHeaderProps } from "./resource-stats-card-header";
|
||||
export { ResourceStatsCardHeader } from "./resource-stats-card-header";
|
||||
@@ -70,6 +70,7 @@ const ChartContainer = React.forwardRef<
|
||||
</ChartContext.Provider>
|
||||
);
|
||||
});
|
||||
|
||||
ChartContainer.displayName = "Chart";
|
||||
|
||||
const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {
|
||||
@@ -184,7 +185,7 @@ const ChartTooltipContent = React.forwardRef<
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"grid min-w-32 items-start gap-1.5 rounded-lg border border-slate-200 border-slate-200/50 bg-white px-2.5 py-1.5 text-xs shadow-xl dark:border-slate-800 dark:border-slate-800/50 dark:bg-slate-950",
|
||||
"grid min-w-32 items-start gap-1.5 rounded-lg border border-slate-200/50 bg-white px-2.5 py-1.5 text-xs shadow-xl dark:border-slate-800/50 dark:bg-slate-950",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user