Merge branch 'master' into PRWLR-6707-create-a-way-of-reporting-for-prowler-threatscore

This commit is contained in:
pedrooot committed 2025-07-03 18:44:17 +02:00
commit d185d7bac6
98 files changed
+4209 -2985

No files matched your search

+3 -3
View File
@@ -6,6 +6,7 @@
PROWLER_UI_VERSION="stable"
AUTH_URL=http://localhost:3000
API_BASE_URL=http://prowler-api:8080/api/v1
NEXT_PUBLIC_API_BASE_URL=${API_BASE_URL}
NEXT_PUBLIC_API_DOCS_URL=http://prowler-api:8080/api/v1/docs
AUTH_TRUST_HOST=true
UI_PORT=3000
@@ -130,7 +131,7 @@ SENTRY_ENVIRONMENT=local
SENTRY_RELEASE=local
#### Prowler release version ####
NEXT_PUBLIC_PROWLER_RELEASE_VERSION=v5.6.0
NEXT_PUBLIC_PROWLER_RELEASE_VERSION=v5.7.5
# Social login credentials
SOCIAL_GOOGLE_OAUTH_CALLBACK_URL="${AUTH_URL}/api/auth/callback/google"
@@ -142,8 +143,7 @@ SOCIAL_GITHUB_OAUTH_CLIENT_ID=""
SOCIAL_GITHUB_OAUTH_CLIENT_SECRET=""
# Single Sign-On (SSO)
SAML_PUBLIC_CERT=""
SAML_PRIVATE_KEY=""
SAML_SSO_CALLBACK_URL="${AUTH_URL}/api/auth/callback/saml"
# Lighthouse tracing
LANGSMITH_TRACING=false
@@ -76,7 +76,7 @@ jobs:
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@b5ca514318bd6ebac0fb2aedd5d36ec1b5c232a2 # v3.10.0
uses: docker/setup-buildx-action@e468171a9de216ec08956ac3ada2f0791b6bd435 # v3.11.1
- name: Build and push container image (latest)
# Comment the following line for testing
+2 -2
View File
@@ -48,12 +48,12 @@ jobs:
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@ff0a06e83cb2de871e5a09832bc6a81e7276941f # v3.28.18
uses: github/codeql-action/init@181d5eefc20863364f96762470ba6f862bdef56b # v3.29.2
with:
languages: ${{ matrix.language }}
config-file: ./.github/codeql/api-codeql-config.yml
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@ff0a06e83cb2de871e5a09832bc6a81e7276941f # v3.28.18
uses: github/codeql-action/analyze@181d5eefc20863364f96762470ba6f862bdef56b # v3.29.2
with:
category: "/language:${{matrix.language}}"
+1 -1
View File
@@ -211,7 +211,7 @@ jobs:
files_ignore: ${{ env.IGNORE_FILES }}
- name: Set up Docker Buildx
if: steps.are-non-ignored-files-changed.outputs.any_changed == 'true'
uses: docker/setup-buildx-action@b5ca514318bd6ebac0fb2aedd5d36ec1b5c232a2 # v3.10.0
uses: docker/setup-buildx-action@e468171a9de216ec08956ac3ada2f0791b6bd435 # v3.11.1
- name: Build Container
if: steps.are-non-ignored-files-changed.outputs.any_changed == 'true'
uses: docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0
+1 -1
View File
@@ -11,7 +11,7 @@ jobs:
with:
fetch-depth: 0
- name: TruffleHog OSS
uses: trufflesecurity/trufflehog@90694bf9af66e7536abc5824e7a87246dbf933cb # v3.88.35
uses: trufflesecurity/trufflehog@6641d4ba5b684fffe195b9820345de1bf19f3181 # v3.89.2
with:
path: ./
base: ${{ github.event.repository.default_branch }}
@@ -123,7 +123,7 @@ jobs:
AWS_REGION: ${{ env.AWS_REGION }}
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@b5ca514318bd6ebac0fb2aedd5d36ec1b5c232a2 # v3.10.0
uses: docker/setup-buildx-action@e468171a9de216ec08956ac3ada2f0791b6bd435 # v3.11.1
- name: Build and push container image (latest)
if: github.event_name == 'push'
+2 -2
View File
@@ -56,12 +56,12 @@ jobs:
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@ff0a06e83cb2de871e5a09832bc6a81e7276941f # v3.28.18
uses: github/codeql-action/init@181d5eefc20863364f96762470ba6f862bdef56b # v3.29.2
with:
languages: ${{ matrix.language }}
config-file: ./.github/codeql/sdk-codeql-config.yml
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@ff0a06e83cb2de871e5a09832bc6a81e7276941f # v3.28.18
uses: github/codeql-action/analyze@181d5eefc20863364f96762470ba6f862bdef56b # v3.29.2
with:
category: "/language:${{matrix.language}}"
@@ -30,6 +30,7 @@ env:
# Container Registries
PROWLERCLOUD_DOCKERHUB_REPOSITORY: prowlercloud
PROWLERCLOUD_DOCKERHUB_IMAGE: prowler-ui
NEXT_PUBLIC_API_BASE_URL: http://prowler-api:8080/api/v1
jobs:
repository-check:
@@ -76,7 +77,7 @@ jobs:
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@b5ca514318bd6ebac0fb2aedd5d36ec1b5c232a2 # v3.10.0
uses: docker/setup-buildx-action@e468171a9de216ec08956ac3ada2f0791b6bd435 # v3.11.1
- name: Build and push container image (latest)
# Comment the following line for testing
@@ -86,6 +87,7 @@ jobs:
context: ${{ env.WORKING_DIRECTORY }}
build-args: |
NEXT_PUBLIC_PROWLER_RELEASE_VERSION=${{ env.SHORT_SHA }}
NEXT_PUBLIC_API_BASE_URL=${{ env.NEXT_PUBLIC_API_BASE_URL }}
# Set push: false for testing
push: true
tags: |
@@ -101,6 +103,7 @@ jobs:
context: ${{ env.WORKING_DIRECTORY }}
build-args: |
NEXT_PUBLIC_PROWLER_RELEASE_VERSION=v${{ env.RELEASE_TAG }}
NEXT_PUBLIC_API_BASE_URL=${{ env.NEXT_PUBLIC_API_BASE_URL }}
push: true
tags: |
${{ env.PROWLERCLOUD_DOCKERHUB_REPOSITORY }}/${{ env.PROWLERCLOUD_DOCKERHUB_IMAGE }}:${{ env.RELEASE_TAG }}
+2 -2
View File
@@ -48,12 +48,12 @@ jobs:
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@ff0a06e83cb2de871e5a09832bc6a81e7276941f # v3.28.18
uses: github/codeql-action/init@181d5eefc20863364f96762470ba6f862bdef56b # v3.29.2
with:
languages: ${{ matrix.language }}
config-file: ./.github/codeql/ui-codeql-config.yml
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@ff0a06e83cb2de871e5a09832bc6a81e7276941f # v3.28.18
uses: github/codeql-action/analyze@181d5eefc20863364f96762470ba6f862bdef56b # v3.29.2
with:
category: "/language:${{matrix.language}}"
+1 -1
View File
@@ -97,7 +97,7 @@ jobs:
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@b5ca514318bd6ebac0fb2aedd5d36ec1b5c232a2 # v3.10.0
uses: docker/setup-buildx-action@e468171a9de216ec08956ac3ada2f0791b6bd435 # v3.11.1
- name: Build Container
uses: docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0
with:
+2 -5
View File
@@ -6,7 +6,8 @@ LABEL org.opencontainers.image.source="https://github.com/prowler-cloud/prowler"
ARG POWERSHELL_VERSION=7.5.0
# hadolint ignore=DL3008
RUN apt-get update && apt-get install -y --no-install-recommends wget libicu72 \
RUN apt-get update && apt-get install -y --no-install-recommends \
wget libicu72 libunwind8 libssl3 libcurl4 ca-certificates apt-transport-https gnupg \
&& rm -rf /var/lib/apt/lists/*
# Install PowerShell
@@ -46,10 +47,6 @@ ENV PATH="${HOME}/.local/bin:${PATH}"
RUN pip install --no-cache-dir --upgrade pip && \
pip install --no-cache-dir poetry
# By default poetry does not compile Python source files to bytecode during installation.
# This speeds up the installation process, but the first execution may take a little more
# time because Python then compiles source files to bytecode automatically. If you want to
# compile source files to bytecode during installation, you can use the --compile option
RUN poetry install --compile && \
rm -rf ~/.cache/pip
+6 -2
View File
@@ -2,16 +2,20 @@
All notable changes to the **Prowler API** are documented in this file.
## [v1.9.0] (Prowler UNRELEASED)
## [v1.10.0] (Prowler UNRELEASED)
---
## [v1.9.0] (Prowler v5.8.0)
### Added
- SSO with SAML support [(#7822)](https://github.com/prowler-cloud/prowler/pull/7822)
- Support GCP Service Account key [(#7824)](https://github.com/prowler-cloud/prowler/pull/7824)
- `GET /compliance-overviews` endpoints to retrieve compliance metadata and specific requirements statuses [(#7877)](https://github.com/prowler-cloud/prowler/pull/7877)
- Lighthouse configuration support [(#7848)](https://github.com/prowler-cloud/prowler/pull/7848)
### Changed
- Reworked `GET /compliance-overviews` to return proper requirement metrics [(#7877)](https://github.com/prowler-cloud/prowler/pull/7877)
- Optional `user` and `password` for M365 provider [(#7992)](https://github.com/prowler-cloud/prowler/pull/7992)
### Fixed
- Scheduled scans are no longer deleted when their daily schedule run is disabled [(#8082)](https://github.com/prowler-cloud/prowler/pull/8082)
+63 -15
View File
@@ -1,4 +1,4 @@
# This file is automatically @generated by Poetry 2.1.1 and should not be changed by hand.
# This file is automatically @generated by Poetry 2.1.3 and should not be changed by hand.
[[package]]
name = "about-time"
@@ -880,7 +880,6 @@ description = "Foreign Function Interface for Python calling C code."
optional = false
python-versions = ">=3.8"
groups = ["main", "dev"]
markers = "platform_python_implementation != \"PyPy\""
files = [
{file = "cffi-1.17.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:df8b1c11f177bc2313ec4b2d46baec87a5f3e71fc8b45dab2ee7cae86d9aba14"},
{file = "cffi-1.17.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:8f2cdc858323644ab277e9bb925ad72ae0e67f69e804f4898c070998d50b1a67"},
@@ -950,6 +949,7 @@ files = [
{file = "cffi-1.17.1-cp39-cp39-win_amd64.whl", hash = "sha256:d016c76bdd850f3c626af19b0542c9677ba156e4ee4fccfdd7848803533ef662"},
{file = "cffi-1.17.1.tar.gz", hash = "sha256:1c39c6016c32bc48dd54561950ebd6836e1670f2ae46128f67cf49e789c52824"},
]
markers = {dev = "platform_python_implementation != \"PyPy\""}
[package.dependencies]
pycparser = "*"
@@ -3854,26 +3854,26 @@ testing = ["google-api-core (>=1.31.5)"]
[[package]]
name = "protobuf"
version = "6.30.2"
version = "6.31.1"
description = ""
optional = false
python-versions = ">=3.9"
groups = ["main"]
files = [
{file = "protobuf-6.30.2-cp310-abi3-win32.whl", hash = "sha256:b12ef7df7b9329886e66404bef5e9ce6a26b54069d7f7436a0853ccdeb91c103"},
{file = "protobuf-6.30.2-cp310-abi3-win_amd64.whl", hash = "sha256:7653c99774f73fe6b9301b87da52af0e69783a2e371e8b599b3e9cb4da4b12b9"},
{file = "protobuf-6.30.2-cp39-abi3-macosx_10_9_universal2.whl", hash = "sha256:0eb523c550a66a09a0c20f86dd554afbf4d32b02af34ae53d93268c1f73bc65b"},
{file = "protobuf-6.30.2-cp39-abi3-manylinux2014_aarch64.whl", hash = "sha256:50f32cc9fd9cb09c783ebc275611b4f19dfdfb68d1ee55d2f0c7fa040df96815"},
{file = "protobuf-6.30.2-cp39-abi3-manylinux2014_x86_64.whl", hash = "sha256:4f6c687ae8efae6cf6093389a596548214467778146b7245e886f35e1485315d"},
{file = "protobuf-6.30.2-cp39-cp39-win32.whl", hash = "sha256:524afedc03b31b15586ca7f64d877a98b184f007180ce25183d1a5cb230ee72b"},
{file = "protobuf-6.30.2-cp39-cp39-win_amd64.whl", hash = "sha256:acec579c39c88bd8fbbacab1b8052c793efe83a0a5bd99db4a31423a25c0a0e2"},
{file = "protobuf-6.30.2-py3-none-any.whl", hash = "sha256:ae86b030e69a98e08c77beab574cbcb9fff6d031d57209f574a5aea1445f4b51"},
{file = "protobuf-6.30.2.tar.gz", hash = "sha256:35c859ae076d8c56054c25b59e5e59638d86545ed6e2b6efac6be0b6ea3ba048"},
{file = "protobuf-6.31.1-cp310-abi3-win32.whl", hash = "sha256:7fa17d5a29c2e04b7d90e5e32388b8bfd0e7107cd8e616feef7ed3fa6bdab5c9"},
{file = "protobuf-6.31.1-cp310-abi3-win_amd64.whl", hash = "sha256:426f59d2964864a1a366254fa703b8632dcec0790d8862d30034d8245e1cd447"},
{file = "protobuf-6.31.1-cp39-abi3-macosx_10_9_universal2.whl", hash = "sha256:6f1227473dc43d44ed644425268eb7c2e488ae245d51c6866d19fe158e207402"},
{file = "protobuf-6.31.1-cp39-abi3-manylinux2014_aarch64.whl", hash = "sha256:a40fc12b84c154884d7d4c4ebd675d5b3b5283e155f324049ae396b95ddebc39"},
{file = "protobuf-6.31.1-cp39-abi3-manylinux2014_x86_64.whl", hash = "sha256:4ee898bf66f7a8b0bd21bce523814e6fbd8c6add948045ce958b73af7e8878c6"},
{file = "protobuf-6.31.1-cp39-cp39-win32.whl", hash = "sha256:0414e3aa5a5f3ff423828e1e6a6e907d6c65c1d5b7e6e975793d5590bdeecc16"},
{file = "protobuf-6.31.1-cp39-cp39-win_amd64.whl", hash = "sha256:8764cf4587791e7564051b35524b72844f845ad0bb011704c3736cce762d8fe9"},
{file = "protobuf-6.31.1-py3-none-any.whl", hash = "sha256:720a6c7e6b77288b85063569baae8536671b39f15cc22037ec7045658d80489e"},
{file = "protobuf-6.31.1.tar.gz", hash = "sha256:d8cac4c982f0b957a4dc73a80e2ea24fab08e679c0de9deb835f4a12d69aca9a"},
]
[[package]]
name = "prowler"
version = "5.6.0"
version = "5.8.0"
description = "Prowler is an Open Source security tool to perform AWS, GCP and Azure security best practices assessments, audits, incident response, continuous monitoring, hardening and forensics readiness. It contains hundreds of controls covering CIS, NIST 800, NIST CSF, CISA, RBI, FedRAMP, PCI-DSS, GDPR, HIPAA, FFIEC, SOC2, GXP, AWS Well-Architected Framework Security Pillar, AWS Foundational Technical Review (FTR), ENS (Spanish National Security Scheme) and your custom security frameworks."
optional = false
python-versions = ">3.9.1,<3.13"
@@ -3921,6 +3921,7 @@ numpy = "2.0.2"
pandas = "2.2.3"
py-ocsf-models = "0.3.1"
pydantic = "1.10.21"
pygithub = "2.5.0"
python-dateutil = ">=2.9.0.post0,<3.0.0"
pytz = "2025.1"
schema = "0.7.7"
@@ -3933,7 +3934,7 @@ tzlocal = "5.3.1"
type = "git"
url = "https://github.com/prowler-cloud/prowler.git"
reference = "master"
resolved_reference = "9828824b737b8deda61f4a6646b54e0ad45033b9"
resolved_reference = "ea97de7f43a2063476b49f7697bb6c7b51137c11"
[[package]]
name = "psutil"
@@ -4110,11 +4111,11 @@ description = "C parser in Python"
optional = false
python-versions = ">=3.8"
groups = ["main", "dev"]
markers = "platform_python_implementation != \"PyPy\""
files = [
{file = "pycparser-2.22-py3-none-any.whl", hash = "sha256:c3702b6d3dd8c7abc1afa565d7e63d53a1d0bd86cdc24edd75470f4de499cfcc"},
{file = "pycparser-2.22.tar.gz", hash = "sha256:491c8be9c040f5390f5bf44a5b07752bd07f56edf992381b05c701439eec10f6"},
]
markers = {dev = "platform_python_implementation != \"PyPy\""}
[[package]]
name = "pycurl"
@@ -4225,6 +4226,26 @@ typing-extensions = ">=4.2.0"
dotenv = ["python-dotenv (>=0.10.4)"]
email = ["email-validator (>=1.0.3)"]
[[package]]
name = "pygithub"
version = "2.5.0"
description = "Use the full Github API v3"
optional = false
python-versions = ">=3.8"
groups = ["main"]
files = [
{file = "PyGithub-2.5.0-py3-none-any.whl", hash = "sha256:b0b635999a658ab8e08720bdd3318893ff20e2275f6446fcf35bf3f44f2c0fd2"},
{file = "pygithub-2.5.0.tar.gz", hash = "sha256:e1613ac508a9be710920d26eb18b1905ebd9926aa49398e88151c1b526aad3cf"},
]
[package.dependencies]
Deprecated = "*"
pyjwt = {version = ">=2.4.0", extras = ["crypto"]}
pynacl = ">=1.4.0"
requests = ">=2.14.0"
typing-extensions = ">=4.0.0"
urllib3 = ">=1.26.0"
[[package]]
name = "pygments"
version = "2.19.1"
@@ -4289,6 +4310,33 @@ tomlkit = ">=0.10.1"
spelling = ["pyenchant (>=3.2,<4.0)"]
testutils = ["gitpython (>3)"]
[[package]]
name = "pynacl"
version = "1.5.0"
description = "Python binding to the Networking and Cryptography (NaCl) library"
optional = false
python-versions = ">=3.6"
groups = ["main"]
files = [
{file = "PyNaCl-1.5.0-cp36-abi3-macosx_10_10_universal2.whl", hash = "sha256:401002a4aaa07c9414132aaed7f6836ff98f59277a234704ff66878c2ee4a0d1"},
{file = "PyNaCl-1.5.0-cp36-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_24_aarch64.whl", hash = "sha256:52cb72a79269189d4e0dc537556f4740f7f0a9ec41c1322598799b0bdad4ef92"},
{file = "PyNaCl-1.5.0-cp36-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a36d4a9dda1f19ce6e03c9a784a2921a4b726b02e1c736600ca9c22029474394"},
{file = "PyNaCl-1.5.0-cp36-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl", hash = "sha256:0c84947a22519e013607c9be43706dd42513f9e6ae5d39d3613ca1e142fba44d"},
{file = "PyNaCl-1.5.0-cp36-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:06b8f6fa7f5de8d5d2f7573fe8c863c051225a27b61e6860fd047b1775807858"},
{file = "PyNaCl-1.5.0-cp36-abi3-musllinux_1_1_aarch64.whl", hash = "sha256:a422368fc821589c228f4c49438a368831cb5bbc0eab5ebe1d7fac9dded6567b"},
{file = "PyNaCl-1.5.0-cp36-abi3-musllinux_1_1_x86_64.whl", hash = "sha256:61f642bf2378713e2c2e1de73444a3778e5f0a38be6fee0fe532fe30060282ff"},
{file = "PyNaCl-1.5.0-cp36-abi3-win32.whl", hash = "sha256:e46dae94e34b085175f8abb3b0aaa7da40767865ac82c928eeb9e57e1ea8a543"},
{file = "PyNaCl-1.5.0-cp36-abi3-win_amd64.whl", hash = "sha256:20f42270d27e1b6a29f54032090b972d97f0a1b0948cc52392041ef7831fee93"},
{file = "PyNaCl-1.5.0.tar.gz", hash = "sha256:8ac7448f09ab85811607bdd21ec2464495ac8b7c66d146bf545b0f08fb9220ba"},
]
[package.dependencies]
cffi = ">=1.4.1"
[package.extras]
docs = ["sphinx (>=1.6.5)", "sphinx-rtd-theme"]
tests = ["hypothesis (>=3.27.0)", "pytest (>=3.2.1,!=3.3.0)"]
[[package]]
name = "pyparsing"
version = "3.2.3"
+90 -99
View File
@@ -3,14 +3,7 @@ from django.db import transaction
from api.db_router import MainRouter
from api.db_utils import rls_transaction
from api.models import (
Membership,
Role,
SAMLConfiguration,
Tenant,
User,
UserRoleRelationship,
)
from api.models import Membership, Role, Tenant, User, UserRoleRelationship
class ProwlerSocialAccountAdapter(DefaultSocialAccountAdapter):
@@ -24,8 +17,8 @@ class ProwlerSocialAccountAdapter(DefaultSocialAccountAdapter):
def pre_social_login(self, request, sociallogin):
# Link existing accounts with the same email address
email = sociallogin.account.extra_data.get("email")
if sociallogin.account.provider == "saml":
email = sociallogin.user.email
# if sociallogin.account.provider == "saml":
# email = sociallogin.user.email
if email:
existing_user = self.get_user_by_email(email)
if existing_user:
@@ -38,100 +31,98 @@ class ProwlerSocialAccountAdapter(DefaultSocialAccountAdapter):
"""
with transaction.atomic(using=MainRouter.admin_db):
user = super().save_user(request, sociallogin, form)
provider = sociallogin.account.provider
extra = sociallogin.account.extra_data
if provider == "saml":
# Handle SAML-specific logic
user.first_name = (
extra.get("firstName", [""])[0] if extra.get("firstName") else ""
)
user.last_name = (
extra.get("lastName", [""])[0] if extra.get("lastName") else ""
)
user.company_name = (
extra.get("organization", [""])[0]
if extra.get("organization")
else ""
)
user.name = f"{user.first_name} {user.last_name}".strip()
if user.name == "":
user.name = "N/A"
# if provider == "saml":
# # Handle SAML-specific logic
# user.first_name = (
# extra.get("firstName", [""])[0] if extra.get("firstName") else ""
# )
# user.last_name = (
# extra.get("lastName", [""])[0] if extra.get("lastName") else ""
# )
# user.company_name = (
# extra.get("organization", [""])[0]
# if extra.get("organization")
# else ""
# )
# user.name = f"{user.first_name} {user.last_name}".strip()
# if user.name == "":
# user.name = "N/A"
# user.save(using=MainRouter.admin_db)
# email_domain = user.email.split("@")[-1]
# tenant = (
# SAMLConfiguration.objects.using(MainRouter.admin_db)
# .get(email_domain=email_domain)
# .tenant
# )
# with rls_transaction(str(tenant.id)):
# role_name = (
# extra.get("userType", ["saml_default_role"])[0].strip()
# if extra.get("userType")
# else "saml_default_role"
# )
# try:
# role = Role.objects.using(MainRouter.admin_db).get(
# name=role_name, tenant_id=tenant.id
# )
# except Role.DoesNotExist:
# role = Role.objects.using(MainRouter.admin_db).create(
# name=role_name,
# tenant_id=tenant.id,
# manage_users=False,
# manage_account=False,
# manage_billing=False,
# manage_providers=False,
# manage_integrations=False,
# manage_scans=False,
# unlimited_visibility=False,
# )
# Membership.objects.using(MainRouter.admin_db).create(
# user=user,
# tenant=tenant,
# role=Membership.RoleChoices.MEMBER,
# )
# UserRoleRelationship.objects.using(MainRouter.admin_db).create(
# user=user,
# role=role,
# tenant_id=tenant.id,
# )
# Handle other providers (e.g., GitHub, Google)
user.save(using=MainRouter.admin_db)
social_account_name = extra.get("name")
if social_account_name:
user.name = social_account_name
user.save(using=MainRouter.admin_db)
email_domain = user.email.split("@")[-1]
tenant = (
SAMLConfiguration.objects.using(MainRouter.admin_db)
.get(email_domain=email_domain)
.tenant
tenant = Tenant.objects.using(MainRouter.admin_db).create(
name=f"{user.email.split('@')[0]} default tenant"
)
with rls_transaction(str(tenant.id)):
Membership.objects.using(MainRouter.admin_db).create(
user=user, tenant=tenant, role=Membership.RoleChoices.OWNER
)
with rls_transaction(str(tenant.id)):
role_name = (
extra.get("userType", ["saml_default_role"])[0].strip()
if extra.get("userType")
else "saml_default_role"
)
try:
role = Role.objects.using(MainRouter.admin_db).get(
name=role_name, tenant_id=tenant.id
)
except Role.DoesNotExist:
role = Role.objects.using(MainRouter.admin_db).create(
name=role_name,
tenant_id=tenant.id,
manage_users=False,
manage_account=False,
manage_billing=False,
manage_providers=False,
manage_integrations=False,
manage_scans=False,
unlimited_visibility=False,
)
Membership.objects.using(MainRouter.admin_db).create(
user=user,
tenant=tenant,
role=Membership.RoleChoices.MEMBER,
)
UserRoleRelationship.objects.using(MainRouter.admin_db).create(
user=user,
role=role,
tenant_id=tenant.id,
)
else:
# Handle other providers (e.g., GitHub, Google)
user.save(using=MainRouter.admin_db)
social_account_name = extra.get("name")
if social_account_name:
user.name = social_account_name
user.save(using=MainRouter.admin_db)
tenant = Tenant.objects.using(MainRouter.admin_db).create(
name=f"{user.email.split('@')[0]} default tenant"
role = Role.objects.using(MainRouter.admin_db).create(
name="admin",
tenant_id=tenant.id,
manage_users=True,
manage_account=True,
manage_billing=True,
manage_providers=True,
manage_integrations=True,
manage_scans=True,
unlimited_visibility=True,
)
UserRoleRelationship.objects.using(MainRouter.admin_db).create(
user=user,
role=role,
tenant_id=tenant.id,
)
with rls_transaction(str(tenant.id)):
Membership.objects.using(MainRouter.admin_db).create(
user=user, tenant=tenant, role=Membership.RoleChoices.OWNER
)
role = Role.objects.using(MainRouter.admin_db).create(
name="admin",
tenant_id=tenant.id,
manage_users=True,
manage_account=True,
manage_billing=True,
manage_providers=True,
manage_integrations=True,
manage_scans=True,
unlimited_visibility=True,
)
UserRoleRelationship.objects.using(MainRouter.admin_db).create(
user=user,
role=role,
tenant_id=tenant.id,
)
return user
@@ -11,7 +11,7 @@ import api.rls
class Migration(migrations.Migration):
dependencies = [
("api", "0030_samlconfigurations"),
("api", "0029_findings_check_index_parent"),
]
operations = [
@@ -1,120 +0,0 @@
# Generated by Django 5.1.8 on 2025-05-15 09:54
import uuid
import django.db.models.deletion
from django.db import migrations, models
import api.rls
class Migration(migrations.Migration):
dependencies = [
("api", "0029_findings_check_index_parent"),
]
operations = [
migrations.CreateModel(
name="SAMLDomainIndex",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("email_domain", models.CharField(max_length=254, unique=True)),
(
"tenant",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE, to="api.tenant"
),
),
],
options={
"db_table": "saml_domain_index",
},
),
migrations.AddConstraint(
model_name="samldomainindex",
constraint=models.UniqueConstraint(
fields=("email_domain", "tenant"),
name="unique_resources_by_email_domain",
),
),
migrations.AddConstraint(
model_name="samldomainindex",
constraint=api.rls.BaseSecurityConstraint(
name="statements_on_samldomainindex",
statements=["SELECT", "INSERT", "UPDATE", "DELETE"],
),
),
migrations.CreateModel(
name="SAMLConfiguration",
fields=[
(
"id",
models.UUIDField(
default=uuid.uuid4,
editable=False,
primary_key=True,
serialize=False,
),
),
(
"email_domain",
models.CharField(
help_text="Email domain used to identify the tenant, e.g. prowlerdemo.com",
max_length=254,
unique=True,
),
),
(
"metadata_xml",
models.TextField(
help_text="Raw IdP metadata XML to configure SingleSignOnService, certificates, etc."
),
),
("created_at", models.DateTimeField(auto_now_add=True)),
("updated_at", models.DateTimeField(auto_now=True)),
(
"tenant",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE, to="api.tenant"
),
),
],
options={
"db_table": "saml_configurations",
},
),
migrations.AddConstraint(
model_name="samlconfiguration",
constraint=api.rls.RowLevelSecurityConstraint(
"tenant_id",
name="rls_on_samlconfiguration",
statements=["SELECT", "INSERT", "UPDATE", "DELETE"],
),
),
migrations.AddConstraint(
model_name="samlconfiguration",
constraint=models.UniqueConstraint(
fields=("tenant",), name="unique_samlconfig_per_tenant"
),
),
migrations.AlterField(
model_name="integration",
name="integration_type",
field=api.db_utils.IntegrationTypeEnumField(
choices=[
("amazon_s3", "Amazon S3"),
("aws_security_hub", "AWS Security Hub"),
("jira", "JIRA"),
("slack", "Slack"),
]
),
),
]
@@ -6,7 +6,7 @@ from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("api", "0031_lighthouseconfiguration"),
("api", "0030_lighthouseconfiguration"),
("django_celery_beat", "0019_alter_periodictasks_options"),
]
+204 -187
View File
@@ -1,20 +1,15 @@
import json
import logging
import re
import xml.etree.ElementTree as ET
from uuid import UUID, uuid4
from allauth.socialaccount.models import SocialApp
from config.custom_logging import BackendLogger
from config.settings.social_login import SOCIALACCOUNT_PROVIDERS
from cryptography.fernet import Fernet, InvalidToken
from django.conf import settings
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.postgres.fields import ArrayField
from django.contrib.postgres.indexes import GinIndex
from django.contrib.postgres.search import SearchVector, SearchVectorField
from django.contrib.sites.models import Site
from django.core.exceptions import ValidationError
from django.core.validators import MinLengthValidator
from django.db import models
from django.db.models import Q
@@ -26,7 +21,6 @@ from psqlextra.models import PostgresPartitionedModel
from psqlextra.types import PostgresPartitioningMethod
from uuid6 import uuid7
from api.db_router import MainRouter
from api.db_utils import (
CustomUserManager,
FindingDeltaEnumField,
@@ -1370,219 +1364,242 @@ class IntegrationProviderRelationship(RowLevelSecurityProtectedModel):
]
class SAMLDomainIndex(models.Model):
"""
Public index of SAML domains. No RLS. Used for fast lookup in SAML login flow.
"""
# class SAMLToken(models.Model):
# 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)
# expires_at = models.DateTimeField(editable=False)
# token = models.JSONField(unique=True)
# user = models.ForeignKey(User, on_delete=models.CASCADE)
email_domain = models.CharField(max_length=254, unique=True)
tenant = models.ForeignKey("Tenant", on_delete=models.CASCADE)
# class Meta:
# db_table = "saml_tokens"
class Meta:
db_table = "saml_domain_index"
# def save(self, *args, **kwargs):
# if not self.expires_at:
# self.expires_at = datetime.now(timezone.utc) + timedelta(seconds=15)
# super().save(*args, **kwargs)
constraints = [
models.UniqueConstraint(
fields=("email_domain", "tenant"),
name="unique_resources_by_email_domain",
),
BaseSecurityConstraint(
name="statements_on_%(class)s",
statements=["SELECT", "INSERT", "UPDATE", "DELETE"],
),
]
# def is_expired(self) -> bool:
# return datetime.now(timezone.utc) >= self.expires_at
class SAMLConfiguration(RowLevelSecurityProtectedModel):
"""
Stores per-tenant SAML settings, including email domain and IdP metadata.
Automatically syncs to a SocialApp instance on save.
# class SAMLDomainIndex(models.Model):
# """
# Public index of SAML domains. No RLS. Used for fast lookup in SAML login flow.
# """
Note:
This model exists to provide a tenant-aware abstraction over SAML configuration.
It supports row-level security, custom validation, and metadata parsing, enabling
Prowler to expose a clean API and admin interface for managing SAML integrations.
# email_domain = models.CharField(max_length=254, unique=True)
# tenant = models.ForeignKey("Tenant", on_delete=models.CASCADE)
Although Django Allauth uses the SocialApp model to store provider configuration,
it is not designed for multi-tenant use. SocialApp lacks support for tenant scoping,
email domain mapping, and structured metadata handling.
# class Meta:
# db_table = "saml_domain_index"
By managing SAMLConfiguration separately, we ensure:
- Strong isolation between tenants via RLS.
- Ownership of raw IdP metadata and its validation.
- An explicit link between SAML config and business-level identifiers (e.g. email domain).
- Programmatic transformation into the SocialApp format used by Allauth.
# constraints = [
# models.UniqueConstraint(
# fields=("email_domain", "tenant"),
# name="unique_resources_by_email_domain",
# ),
# BaseSecurityConstraint(
# name="statements_on_%(class)s",
# statements=["SELECT", "INSERT", "UPDATE", "DELETE"],
# ),
# ]
In short, this model acts as a secure and user-friendly layer over Allauth's lower-level primitives.
"""
id = models.UUIDField(primary_key=True, default=uuid4, editable=False)
email_domain = models.CharField(
max_length=254,
unique=True,
help_text="Email domain used to identify the tenant, e.g. prowlerdemo.com",
)
metadata_xml = models.TextField(
help_text="Raw IdP metadata XML to configure SingleSignOnService, certificates, etc."
)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
# class SAMLConfiguration(RowLevelSecurityProtectedModel):
# """
# Stores per-tenant SAML settings, including email domain and IdP metadata.
# Automatically syncs to a SocialApp instance on save.
class JSONAPIMeta:
resource_name = "saml-configurations"
# Note:
# This model exists to provide a tenant-aware abstraction over SAML configuration.
# It supports row-level security, custom validation, and metadata parsing, enabling
# Prowler to expose a clean API and admin interface for managing SAML integrations.
class Meta:
db_table = "saml_configurations"
# Although Django Allauth uses the SocialApp model to store provider configuration,
# it is not designed for multi-tenant use. SocialApp lacks support for tenant scoping,
# email domain mapping, and structured metadata handling.
constraints = [
RowLevelSecurityConstraint(
field="tenant_id",
name="rls_on_%(class)s",
statements=["SELECT", "INSERT", "UPDATE", "DELETE"],
),
# 1 config per tenant
models.UniqueConstraint(
fields=["tenant"],
name="unique_samlconfig_per_tenant",
),
]
# By managing SAMLConfiguration separately, we ensure:
# - Strong isolation between tenants via RLS.
# - Ownership of raw IdP metadata and its validation.
# - An explicit link between SAML config and business-level identifiers (e.g. email domain).
# - Programmatic transformation into the SocialApp format used by Allauth.
def clean(self, old_email_domain=None):
# Domain must not contain @
if "@" in self.email_domain:
raise ValidationError({"email_domain": "Domain must not contain @"})
# In short, this model acts as a secure and user-friendly layer over Allauth's lower-level primitives.
# """
# Enforce at most one config per tenant
qs = SAMLConfiguration.objects.filter(tenant=self.tenant)
# Exclude ourselves in case of update
if self.pk:
qs = qs.exclude(pk=self.pk)
if qs.exists():
raise ValidationError(
{"tenant": "A SAML configuration already exists for this tenant."}
)
# id = models.UUIDField(primary_key=True, default=uuid4, editable=False)
# email_domain = models.CharField(
# max_length=254,
# unique=True,
# help_text="Email domain used to identify the tenant, e.g. prowlerdemo.com",
# )
# metadata_xml = models.TextField(
# help_text="Raw IdP metadata XML to configure SingleSignOnService, certificates, etc."
# )
# created_at = models.DateTimeField(auto_now_add=True)
# updated_at = models.DateTimeField(auto_now=True)
# The email domain must be unique in the entire system
qs = SAMLConfiguration.objects.using(MainRouter.admin_db).filter(
email_domain__iexact=self.email_domain
)
if qs.exists() and old_email_domain != self.email_domain:
raise ValidationError(
{"tenant": "There is a problem with your email domain."}
)
# class JSONAPIMeta:
# resource_name = "saml-configurations"
def save(self, *args, **kwargs):
self.email_domain = self.email_domain.strip().lower()
is_create = not SAMLConfiguration.objects.filter(pk=self.pk).exists()
# class Meta:
# db_table = "saml_configurations"
if not is_create:
old = SAMLConfiguration.objects.get(pk=self.pk)
old_email_domain = old.email_domain
old_metadata_xml = old.metadata_xml
else:
old_email_domain = None
old_metadata_xml = None
# constraints = [
# RowLevelSecurityConstraint(
# field="tenant_id",
# name="rls_on_%(class)s",
# statements=["SELECT", "INSERT", "UPDATE", "DELETE"],
# ),
# # 1 config per tenant
# models.UniqueConstraint(
# fields=["tenant"],
# name="unique_samlconfig_per_tenant",
# ),
# ]
self.clean(old_email_domain)
super().save(*args, **kwargs)
# def clean(self, old_email_domain=None):
# # Domain must not contain @
# if "@" in self.email_domain:
# raise ValidationError({"email_domain": "Domain must not contain @"})
if is_create or (
old_email_domain != self.email_domain
or old_metadata_xml != self.metadata_xml
):
self._sync_social_app(old_email_domain)
# # Enforce at most one config per tenant
# qs = SAMLConfiguration.objects.filter(tenant=self.tenant)
# # Exclude ourselves in case of update
# if self.pk:
# qs = qs.exclude(pk=self.pk)
# if qs.exists():
# raise ValidationError(
# {"tenant": "A SAML configuration already exists for this tenant."}
# )
# Sync the public index
if not is_create and old_email_domain and old_email_domain != self.email_domain:
SAMLDomainIndex.objects.filter(email_domain=old_email_domain).delete()
# # The email domain must be unique in the entire system
# qs = SAMLConfiguration.objects.using(MainRouter.admin_db).filter(
# email_domain__iexact=self.email_domain
# )
# if qs.exists() and old_email_domain != self.email_domain:
# raise ValidationError(
# {"tenant": "There is a problem with your email domain."}
# )
# Create/update the new domain index
SAMLDomainIndex.objects.update_or_create(
email_domain=self.email_domain, defaults={"tenant": self.tenant}
)
# def save(self, *args, **kwargs):
# self.email_domain = self.email_domain.strip().lower()
# is_create = not SAMLConfiguration.objects.filter(pk=self.pk).exists()
def _parse_metadata(self):
"""
Parse the raw IdP metadata XML and extract:
- entity_id
- sso_url
- slo_url (may be None)
- x509cert (required)
"""
ns = {
"md": "urn:oasis:names:tc:SAML:2.0:metadata",
"ds": "http://www.w3.org/2000/09/xmldsig#",
}
try:
root = ET.fromstring(self.metadata_xml)
except ET.ParseError as e:
raise ValidationError({"metadata_xml": f"Invalid XML: {e}"})
# if not is_create:
# old = SAMLConfiguration.objects.get(pk=self.pk)
# old_email_domain = old.email_domain
# old_metadata_xml = old.metadata_xml
# else:
# old_email_domain = None
# old_metadata_xml = None
# Entity ID
entity_id = root.attrib.get("entityID")
# self.clean(old_email_domain)
# super().save(*args, **kwargs)
# SSO endpoint (must exist)
sso = root.find(".//md:IDPSSODescriptor/md:SingleSignOnService", ns)
if sso is None or "Location" not in sso.attrib:
raise ValidationError(
{"metadata_xml": "Missing SingleSignOnService in metadata."}
)
sso_url = sso.attrib["Location"]
# if is_create or (
# old_email_domain != self.email_domain
# or old_metadata_xml != self.metadata_xml
# ):
# self._sync_social_app(old_email_domain)
# SLO endpoint (optional)
slo = root.find(".//md:IDPSSODescriptor/md:SingleLogoutService", ns)
slo_url = slo.attrib.get("Location") if slo is not None else None
# # Sync the public index
# if not is_create and old_email_domain and old_email_domain != self.email_domain:
# SAMLDomainIndex.objects.filter(email_domain=old_email_domain).delete()
# X.509 certificate (required)
cert = root.find(
'.//md:KeyDescriptor[@use="signing"]/ds:KeyInfo/ds:X509Data/ds:X509Certificate',
ns,
)
if cert is None or not cert.text or not cert.text.strip():
raise ValidationError(
{
"metadata_xml": 'Metadata must include a <ds:X509Certificate> under <KeyDescriptor use="signing">.'
}
)
x509cert = cert.text.strip()
# # Create/update the new domain index
# SAMLDomainIndex.objects.update_or_create(
# email_domain=self.email_domain, defaults={"tenant": self.tenant}
# )
return {
"entity_id": entity_id,
"sso_url": sso_url,
"slo_url": slo_url,
"x509cert": x509cert,
}
# def _parse_metadata(self):
# """
# Parse the raw IdP metadata XML and extract:
# - entity_id
# - sso_url
# - slo_url (may be None)
# - x509cert (required)
# """
# ns = {
# "md": "urn:oasis:names:tc:SAML:2.0:metadata",
# "ds": "http://www.w3.org/2000/09/xmldsig#",
# }
# try:
# root = ET.fromstring(self.metadata_xml)
# except ET.ParseError as e:
# raise ValidationError({"metadata_xml": f"Invalid XML: {e}"})
def _sync_social_app(self, previous_email_domain=None):
"""
Create or update the corresponding SocialApp based on email_domain.
If the domain changed, update the matching SocialApp.
"""
idp_settings = self._parse_metadata()
settings_dict = SOCIALACCOUNT_PROVIDERS["saml"].copy()
settings_dict["idp"] = idp_settings
# # Entity ID
# entity_id = root.attrib.get("entityID")
current_site = Site.objects.get(id=settings.SITE_ID)
# # SSO endpoint (must exist)
# sso = root.find(".//md:IDPSSODescriptor/md:SingleSignOnService", ns)
# if sso is None or "Location" not in sso.attrib:
# raise ValidationError(
# {"metadata_xml": "Missing SingleSignOnService in metadata."}
# )
# sso_url = sso.attrib["Location"]
social_app_qs = SocialApp.objects.filter(
provider="saml", client_id=previous_email_domain or self.email_domain
)
# # SLO endpoint (optional)
# slo = root.find(".//md:IDPSSODescriptor/md:SingleLogoutService", ns)
# slo_url = slo.attrib.get("Location") if slo is not None else None
if social_app_qs.exists():
social_app = social_app_qs.first()
social_app.client_id = self.email_domain
social_app.name = f"{self.tenant.name} SAML ({self.email_domain})"
social_app.settings = settings_dict
social_app.save()
social_app.sites.set([current_site])
else:
social_app = SocialApp.objects.create(
provider="saml",
client_id=self.email_domain,
name=f"{self.tenant.name} SAML ({self.email_domain})",
settings=settings_dict,
)
social_app.sites.set([current_site])
# # X.509 certificate (required)
# cert = root.find(
# './/md:KeyDescriptor[@use="signing"]/ds:KeyInfo/ds:X509Data/ds:X509Certificate',
# ns,
# )
# if cert is None or not cert.text or not cert.text.strip():
# raise ValidationError(
# {
# "metadata_xml": 'Metadata must include a <ds:X509Certificate> under <KeyDescriptor use="signing">.'
# }
# )
# x509cert = cert.text.strip()
# return {
# "entity_id": entity_id,
# "sso_url": sso_url,
# "slo_url": slo_url,
# "x509cert": x509cert,
# }
# def _sync_social_app(self, previous_email_domain=None):
# """
# Create or update the corresponding SocialApp based on email_domain.
# If the domain changed, update the matching SocialApp.
# """
# idp_settings = self._parse_metadata()
# settings_dict = SOCIALACCOUNT_PROVIDERS["saml"].copy()
# settings_dict["idp"] = idp_settings
# current_site = Site.objects.get(id=settings.SITE_ID)
# social_app_qs = SocialApp.objects.filter(
# provider="saml", client_id=previous_email_domain or self.email_domain
# )
# client_id = self.email_domain[:191]
# name = f"SAML-{self.email_domain}"[:40]
# if social_app_qs.exists():
# social_app = social_app_qs.first()
# social_app.client_id = client_id
# social_app.name = name
# social_app.settings = settings_dict
# social_app.save()
# social_app.sites.set([current_site])
# else:
# social_app = SocialApp.objects.create(
# provider="saml",
# client_id=client_id,
# name=name,
# settings=settings_dict,
# )
# social_app.sites.set([current_site])
class ResourceScanSummary(RowLevelSecurityProtectedModel):
-339
View File
@@ -5152,199 +5152,6 @@ paths:
responses:
'204':
description: Relationship deleted successfully
/api/v1/saml-config:
get:
operationId: saml_config_list
description: Returns all the SAML-based SSO configurations associated with the
current tenant.
summary: List all SSO configurations
parameters:
- in: query
name: fields[saml-configurations]
schema:
type: array
items:
type: string
enum:
- email_domain
- metadata_xml
- created_at
- updated_at
description: endpoint return only specific fields in the response on a per-type
basis by including a fields[TYPE] query parameter.
explode: false
- name: filter[search]
required: false
in: query
description: A search term.
schema:
type: string
- name: page[number]
required: false
in: query
description: A page number within the paginated result set.
schema:
type: integer
- name: page[size]
required: false
in: query
description: Number of results to return per page.
schema:
type: integer
- name: sort
required: false
in: query
description: '[list of fields to sort by](https://jsonapi.org/format/#fetching-sorting)'
schema:
type: array
items:
type: string
enum:
- id
- -id
- email_domain
- -email_domain
- metadata_xml
- -metadata_xml
- created_at
- -created_at
- updated_at
- -updated_at
explode: false
tags:
- SAML
security:
- jwtAuth: []
responses:
'200':
content:
application/vnd.api+json:
schema:
$ref: '#/components/schemas/PaginatedSAMLConfigurationList'
description: ''
post:
operationId: saml_config_create
description: Creates a new SAML SSO configuration for the current tenant, including
email domain and metadata XML.
summary: Create the SSO configuration
tags:
- SAML
requestBody:
content:
application/vnd.api+json:
schema:
$ref: '#/components/schemas/SAMLConfigurationRequest'
application/x-www-form-urlencoded:
schema:
$ref: '#/components/schemas/SAMLConfigurationRequest'
multipart/form-data:
schema:
$ref: '#/components/schemas/SAMLConfigurationRequest'
required: true
security:
- jwtAuth: []
responses:
'201':
content:
application/vnd.api+json:
schema:
$ref: '#/components/schemas/SAMLConfigurationResponse'
description: ''
/api/v1/saml-config/{id}:
get:
operationId: saml_config_retrieve
description: Returns the details of a specific SAML configuration belonging
to the current tenant.
summary: Retrieve SSO configuration details
parameters:
- in: query
name: fields[saml-configurations]
schema:
type: array
items:
type: string
enum:
- email_domain
- metadata_xml
- created_at
- updated_at
description: endpoint return only specific fields in the response on a per-type
basis by including a fields[TYPE] query parameter.
explode: false
- in: path
name: id
schema:
type: string
format: uuid
description: A UUID string identifying this saml configuration.
required: true
tags:
- SAML
security:
- jwtAuth: []
responses:
'200':
content:
application/vnd.api+json:
schema:
$ref: '#/components/schemas/SAMLConfigurationResponse'
description: ''
patch:
operationId: saml_config_partial_update
description: Partially updates an existing SAML SSO configuration. Supports
changes to email domain and metadata XML.
summary: Update the SSO configuration
parameters:
- in: path
name: id
schema:
type: string
format: uuid
description: A UUID string identifying this saml configuration.
required: true
tags:
- SAML
requestBody:
content:
application/vnd.api+json:
schema:
$ref: '#/components/schemas/PatchedSAMLConfigurationRequest'
application/x-www-form-urlencoded:
schema:
$ref: '#/components/schemas/PatchedSAMLConfigurationRequest'
multipart/form-data:
schema:
$ref: '#/components/schemas/PatchedSAMLConfigurationRequest'
required: true
security:
- jwtAuth: []
responses:
'200':
content:
application/vnd.api+json:
schema:
$ref: '#/components/schemas/SAMLConfigurationResponse'
description: ''
delete:
operationId: saml_config_destroy
description: Deletes an existing SAML SSO configuration associated with the
current tenant.
summary: Delete the SSO configuration
parameters:
- in: path
name: id
schema:
type: string
format: uuid
description: A UUID string identifying this saml configuration.
required: true
tags:
- SAML
security:
- jwtAuth: []
responses:
'204':
description: No response body
/api/v1/scans:
get:
operationId: scans_list
@@ -9351,15 +9158,6 @@ components:
$ref: '#/components/schemas/Role'
required:
- data
PaginatedSAMLConfigurationList:
type: object
properties:
data:
type: array
items:
$ref: '#/components/schemas/SAMLConfiguration'
required:
- data
PaginatedScanList:
type: object
properties:
@@ -10244,52 +10042,6 @@ components:
readOnly: true
required:
- data
PatchedSAMLConfigurationRequest:
type: object
properties:
data:
type: object
required:
- type
- id
additionalProperties: false
properties:
type:
type: string
description: The [type](https://jsonapi.org/format/#document-resource-object-identification)
member is used to describe resource objects that share common attributes
and relationships.
enum:
- saml-configurations
id:
type: string
format: uuid
attributes:
type: object
properties:
email_domain:
type: string
minLength: 1
description: Email domain used to identify the tenant, e.g. prowlerdemo.com
maxLength: 254
metadata_xml:
type: string
minLength: 1
description: Raw IdP metadata XML to configure SingleSignOnService,
certificates, etc.
created_at:
type: string
format: date-time
readOnly: true
updated_at:
type: string
format: date-time
readOnly: true
required:
- email_domain
- metadata_xml
required:
- data
PatchedScanUpdateRequest:
type: object
properties:
@@ -12403,97 +12155,6 @@ components:
$ref: '#/components/schemas/Role'
required:
- data
SAMLConfiguration:
type: object
required:
- type
- id
additionalProperties: false
properties:
type:
allOf:
- $ref: '#/components/schemas/SAMLConfigurationTypeEnum'
description: The [type](https://jsonapi.org/format/#document-resource-object-identification)
member is used to describe resource objects that share common attributes
and relationships.
id:
type: string
format: uuid
attributes:
type: object
properties:
email_domain:
type: string
description: Email domain used to identify the tenant, e.g. prowlerdemo.com
maxLength: 254
metadata_xml:
type: string
description: Raw IdP metadata XML to configure SingleSignOnService,
certificates, etc.
created_at:
type: string
format: date-time
readOnly: true
updated_at:
type: string
format: date-time
readOnly: true
required:
- email_domain
- metadata_xml
SAMLConfigurationRequest:
type: object
properties:
data:
type: object
required:
- type
additionalProperties: false
properties:
type:
type: string
description: The [type](https://jsonapi.org/format/#document-resource-object-identification)
member is used to describe resource objects that share common attributes
and relationships.
enum:
- saml-configurations
attributes:
type: object
properties:
email_domain:
type: string
minLength: 1
description: Email domain used to identify the tenant, e.g. prowlerdemo.com
maxLength: 254
metadata_xml:
type: string
minLength: 1
description: Raw IdP metadata XML to configure SingleSignOnService,
certificates, etc.
created_at:
type: string
format: date-time
readOnly: true
updated_at:
type: string
format: date-time
readOnly: true
required:
- email_domain
- metadata_xml
required:
- data
SAMLConfigurationResponse:
type: object
properties:
data:
$ref: '#/components/schemas/SAMLConfiguration'
required:
- data
SAMLConfigurationTypeEnum:
type: string
enum:
- saml-configurations
Scan:
type: object
required:
+45 -47
View File
@@ -5,8 +5,6 @@ from allauth.socialaccount.models import SocialLogin
from django.contrib.auth import get_user_model
from api.adapters import ProwlerSocialAccountAdapter
from api.db_router import MainRouter
from api.models import Membership, SAMLConfiguration, Tenant
User = get_user_model()
@@ -22,24 +20,24 @@ class TestProwlerSocialAccountAdapter:
adapter = ProwlerSocialAccountAdapter()
assert adapter.get_user_by_email("notfound@example.com") is None
def test_pre_social_login_links_existing_user(self, create_test_user, rf):
adapter = ProwlerSocialAccountAdapter()
# def test_pre_social_login_links_existing_user(self, create_test_user, rf):
# adapter = ProwlerSocialAccountAdapter()
sociallogin = MagicMock(spec=SocialLogin)
sociallogin.account = MagicMock()
sociallogin.account.provider = "saml"
sociallogin.account.extra_data = {}
sociallogin.user = create_test_user
sociallogin.connect = MagicMock()
# sociallogin = MagicMock(spec=SocialLogin)
# sociallogin.account = MagicMock()
# sociallogin.account.provider = "saml"
# sociallogin.account.extra_data = {}
# sociallogin.user = create_test_user
# sociallogin.connect = MagicMock()
adapter.pre_social_login(rf.get("/"), sociallogin)
# adapter.pre_social_login(rf.get("/"), sociallogin)
call_args = sociallogin.connect.call_args
assert call_args is not None
# call_args = sociallogin.connect.call_args
# assert call_args is not None
called_request, called_user = call_args[0]
assert called_request.path == "/"
assert called_user.email == create_test_user.email
# called_request, called_user = call_args[0]
# assert called_request.path == "/"
# assert called_user.email == create_test_user.email
def test_pre_social_login_no_link_if_email_missing(self, rf):
adapter = ProwlerSocialAccountAdapter()
@@ -54,37 +52,37 @@ class TestProwlerSocialAccountAdapter:
sociallogin.connect.assert_not_called()
def test_save_user_saml_flow(
self,
rf,
saml_setup,
saml_sociallogin,
):
adapter = ProwlerSocialAccountAdapter()
request = rf.get("/")
saml_sociallogin.user.email = saml_setup["email"]
saml_sociallogin.account.extra_data = {
"firstName": [],
"lastName": [],
"organization": [],
"userType": [],
}
# def test_save_user_saml_flow(
# self,
# rf,
# saml_setup,
# saml_sociallogin,
# ):
# adapter = ProwlerSocialAccountAdapter()
# request = rf.get("/")
# saml_sociallogin.user.email = saml_setup["email"]
# saml_sociallogin.account.extra_data = {
# "firstName": [],
# "lastName": [],
# "organization": [],
# "userType": [],
# }
tenant = Tenant.objects.using(MainRouter.admin_db).get(
id=saml_setup["tenant_id"]
)
saml_config = SAMLConfiguration.objects.using(MainRouter.admin_db).get(
tenant=tenant
)
assert saml_config.email_domain == saml_setup["domain"]
# tenant = Tenant.objects.using(MainRouter.admin_db).get(
# id=saml_setup["tenant_id"]
# )
# saml_config = SAMLConfiguration.objects.using(MainRouter.admin_db).get(
# tenant=tenant
# )
# assert saml_config.email_domain == saml_setup["domain"]
user = adapter.save_user(request, saml_sociallogin)
# user = adapter.save_user(request, saml_sociallogin)
assert user.name == "N/A"
assert user.company_name == ""
assert user.email == saml_setup["email"]
assert (
Membership.objects.using(MainRouter.admin_db)
.filter(user=user, tenant=tenant)
.exists()
)
# assert user.name == "N/A"
# assert user.company_name == ""
# assert user.email == saml_setup["email"]
# assert (
# Membership.objects.using(MainRouter.admin_db)
# .filter(user=user, tenant=tenant)
# .exists()
# )
+121 -124
View File
@@ -1,9 +1,6 @@
import pytest
from allauth.socialaccount.models import SocialApp
from django.core.exceptions import ValidationError
from api.db_router import MainRouter
from api.models import Resource, ResourceTag, SAMLConfiguration, Tenant
from api.models import Resource, ResourceTag
@pytest.mark.django_db
@@ -125,147 +122,147 @@ class TestResourceModel:
# assert Finding.objects.filter(uid=long_uid).exists()
@pytest.mark.django_db
class TestSAMLConfigurationModel:
VALID_METADATA = """<?xml version='1.0' encoding='UTF-8'?>
<md:EntityDescriptor entityID='TEST' xmlns:md='urn:oasis:names:tc:SAML:2.0:metadata'>
<md:IDPSSODescriptor WantAuthnRequestsSigned='false' protocolSupportEnumeration='urn:oasis:names:tc:SAML:2.0:protocol'>
<md:KeyDescriptor use='signing'>
<ds:KeyInfo xmlns:ds='http://www.w3.org/2000/09/xmldsig#'>
<ds:X509Data>
<ds:X509Certificate>FAKECERTDATA</ds:X509Certificate>
</ds:X509Data>
</ds:KeyInfo>
</md:KeyDescriptor>
<md:SingleSignOnService Binding='urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST' Location='https://idp.test/sso'/>
</md:IDPSSODescriptor>
</md:EntityDescriptor>
"""
# @pytest.mark.django_db
# class TestSAMLConfigurationModel:
# VALID_METADATA = """<?xml version='1.0' encoding='UTF-8'?>
# <md:EntityDescriptor entityID='TEST' xmlns:md='urn:oasis:names:tc:SAML:2.0:metadata'>
# <md:IDPSSODescriptor WantAuthnRequestsSigned='false' protocolSupportEnumeration='urn:oasis:names:tc:SAML:2.0:protocol'>
# <md:KeyDescriptor use='signing'>
# <ds:KeyInfo xmlns:ds='http://www.w3.org/2000/09/xmldsig#'>
# <ds:X509Data>
# <ds:X509Certificate>FAKECERTDATA</ds:X509Certificate>
# </ds:X509Data>
# </ds:KeyInfo>
# </md:KeyDescriptor>
# <md:SingleSignOnService Binding='urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST' Location='https://idp.test/sso'/>
# </md:IDPSSODescriptor>
# </md:EntityDescriptor>
# """
def test_creates_valid_configuration(self):
tenant = Tenant.objects.using(MainRouter.admin_db).create(name="Tenant A")
config = SAMLConfiguration.objects.using(MainRouter.admin_db).create(
email_domain="ssoexample.com",
metadata_xml=TestSAMLConfigurationModel.VALID_METADATA,
tenant=tenant,
)
# def test_creates_valid_configuration(self):
# tenant = Tenant.objects.using(MainRouter.admin_db).create(name="Tenant A")
# config = SAMLConfiguration.objects.using(MainRouter.admin_db).create(
# email_domain="ssoexample.com",
# metadata_xml=TestSAMLConfigurationModel.VALID_METADATA,
# tenant=tenant,
# )
assert config.email_domain == "ssoexample.com"
assert SocialApp.objects.filter(client_id="ssoexample.com").exists()
# assert config.email_domain == "ssoexample.com"
# assert SocialApp.objects.filter(client_id="ssoexample.com").exists()
def test_email_domain_with_at_symbol_fails(self):
tenant = Tenant.objects.using(MainRouter.admin_db).create(name="Tenant B")
config = SAMLConfiguration(
email_domain="invalid@domain.com",
metadata_xml=TestSAMLConfigurationModel.VALID_METADATA,
tenant=tenant,
)
# def test_email_domain_with_at_symbol_fails(self):
# tenant = Tenant.objects.using(MainRouter.admin_db).create(name="Tenant B")
# config = SAMLConfiguration(
# email_domain="invalid@domain.com",
# metadata_xml=TestSAMLConfigurationModel.VALID_METADATA,
# tenant=tenant,
# )
with pytest.raises(ValidationError) as exc_info:
config.clean()
# with pytest.raises(ValidationError) as exc_info:
# config.clean()
errors = exc_info.value.message_dict
assert "email_domain" in errors
assert "Domain must not contain @" in errors["email_domain"][0]
# errors = exc_info.value.message_dict
# assert "email_domain" in errors
# assert "Domain must not contain @" in errors["email_domain"][0]
def test_duplicate_email_domain_fails(self):
tenant1 = Tenant.objects.using(MainRouter.admin_db).create(name="Tenant C1")
tenant2 = Tenant.objects.using(MainRouter.admin_db).create(name="Tenant C2")
# def test_duplicate_email_domain_fails(self):
# tenant1 = Tenant.objects.using(MainRouter.admin_db).create(name="Tenant C1")
# tenant2 = Tenant.objects.using(MainRouter.admin_db).create(name="Tenant C2")
SAMLConfiguration.objects.using(MainRouter.admin_db).create(
email_domain="duplicate.com",
metadata_xml=TestSAMLConfigurationModel.VALID_METADATA,
tenant=tenant1,
)
# SAMLConfiguration.objects.using(MainRouter.admin_db).create(
# email_domain="duplicate.com",
# metadata_xml=TestSAMLConfigurationModel.VALID_METADATA,
# tenant=tenant1,
# )
config = SAMLConfiguration(
email_domain="duplicate.com",
metadata_xml=TestSAMLConfigurationModel.VALID_METADATA,
tenant=tenant2,
)
# config = SAMLConfiguration(
# email_domain="duplicate.com",
# metadata_xml=TestSAMLConfigurationModel.VALID_METADATA,
# tenant=tenant2,
# )
with pytest.raises(ValidationError) as exc_info:
config.clean()
# with pytest.raises(ValidationError) as exc_info:
# config.clean()
errors = exc_info.value.message_dict
assert "tenant" in errors
assert "There is a problem with your email domain." in errors["tenant"][0]
# errors = exc_info.value.message_dict
# assert "tenant" in errors
# assert "There is a problem with your email domain." in errors["tenant"][0]
def test_duplicate_tenant_config_fails(self):
tenant = Tenant.objects.using(MainRouter.admin_db).create(name="Tenant D")
# def test_duplicate_tenant_config_fails(self):
# tenant = Tenant.objects.using(MainRouter.admin_db).create(name="Tenant D")
SAMLConfiguration.objects.using(MainRouter.admin_db).create(
email_domain="unique1.com",
metadata_xml=TestSAMLConfigurationModel.VALID_METADATA,
tenant=tenant,
)
# SAMLConfiguration.objects.using(MainRouter.admin_db).create(
# email_domain="unique1.com",
# metadata_xml=TestSAMLConfigurationModel.VALID_METADATA,
# tenant=tenant,
# )
config = SAMLConfiguration(
email_domain="unique2.com",
metadata_xml=TestSAMLConfigurationModel.VALID_METADATA,
tenant=tenant,
)
# config = SAMLConfiguration(
# email_domain="unique2.com",
# metadata_xml=TestSAMLConfigurationModel.VALID_METADATA,
# tenant=tenant,
# )
with pytest.raises(ValidationError) as exc_info:
config.clean()
# with pytest.raises(ValidationError) as exc_info:
# config.clean()
errors = exc_info.value.message_dict
assert "tenant" in errors
assert (
"A SAML configuration already exists for this tenant."
in errors["tenant"][0]
)
# errors = exc_info.value.message_dict
# assert "tenant" in errors
# assert (
# "A SAML configuration already exists for this tenant."
# in errors["tenant"][0]
# )
def test_invalid_metadata_xml_fails(self):
tenant = Tenant.objects.using(MainRouter.admin_db).create(name="Tenant E")
config = SAMLConfiguration(
email_domain="brokenxml.com",
metadata_xml="<bad<xml>",
tenant=tenant,
)
# def test_invalid_metadata_xml_fails(self):
# tenant = Tenant.objects.using(MainRouter.admin_db).create(name="Tenant E")
# config = SAMLConfiguration(
# email_domain="brokenxml.com",
# metadata_xml="<bad<xml>",
# tenant=tenant,
# )
with pytest.raises(ValidationError) as exc_info:
config._parse_metadata()
# with pytest.raises(ValidationError) as exc_info:
# config._parse_metadata()
errors = exc_info.value.message_dict
assert "metadata_xml" in errors
assert "Invalid XML" in errors["metadata_xml"][0]
assert "not well-formed" in errors["metadata_xml"][0]
# errors = exc_info.value.message_dict
# assert "metadata_xml" in errors
# assert "Invalid XML" in errors["metadata_xml"][0]
# assert "not well-formed" in errors["metadata_xml"][0]
def test_metadata_missing_sso_fails(self):
tenant = Tenant.objects.using(MainRouter.admin_db).create(name="Tenant F")
xml = """<md:EntityDescriptor entityID="x" xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata">
<md:IDPSSODescriptor></md:IDPSSODescriptor>
</md:EntityDescriptor>"""
config = SAMLConfiguration(
email_domain="nosso.com",
metadata_xml=xml,
tenant=tenant,
)
# def test_metadata_missing_sso_fails(self):
# tenant = Tenant.objects.using(MainRouter.admin_db).create(name="Tenant F")
# xml = """<md:EntityDescriptor entityID="x" xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata">
# <md:IDPSSODescriptor></md:IDPSSODescriptor>
# </md:EntityDescriptor>"""
# config = SAMLConfiguration(
# email_domain="nosso.com",
# metadata_xml=xml,
# tenant=tenant,
# )
with pytest.raises(ValidationError) as exc_info:
config._parse_metadata()
# with pytest.raises(ValidationError) as exc_info:
# config._parse_metadata()
errors = exc_info.value.message_dict
assert "metadata_xml" in errors
assert "Missing SingleSignOnService" in errors["metadata_xml"][0]
# errors = exc_info.value.message_dict
# assert "metadata_xml" in errors
# assert "Missing SingleSignOnService" in errors["metadata_xml"][0]
def test_metadata_missing_certificate_fails(self):
tenant = Tenant.objects.using(MainRouter.admin_db).create(name="Tenant G")
xml = """<md:EntityDescriptor entityID="x" xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata">
<md:IDPSSODescriptor>
<md:SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" Location="https://example.com/sso"/>
</md:IDPSSODescriptor>
</md:EntityDescriptor>"""
config = SAMLConfiguration(
email_domain="nocert.com",
metadata_xml=xml,
tenant=tenant,
)
# def test_metadata_missing_certificate_fails(self):
# tenant = Tenant.objects.using(MainRouter.admin_db).create(name="Tenant G")
# xml = """<md:EntityDescriptor entityID="x" xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata">
# <md:IDPSSODescriptor>
# <md:SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" Location="https://example.com/sso"/>
# </md:IDPSSODescriptor>
# </md:EntityDescriptor>"""
# config = SAMLConfiguration(
# email_domain="nocert.com",
# metadata_xml=xml,
# tenant=tenant,
# )
with pytest.raises(ValidationError) as exc_info:
config._parse_metadata()
# with pytest.raises(ValidationError) as exc_info:
# config._parse_metadata()
errors = exc_info.value.message_dict
assert "metadata_xml" in errors
assert "X509Certificate" in errors["metadata_xml"][0]
# errors = exc_info.value.message_dict
# assert "metadata_xml" in errors
# assert "X509Certificate" in errors["metadata_xml"][0]
+345 -234
View File
@@ -9,19 +9,15 @@ from unittest.mock import ANY, MagicMock, Mock, patch
import jwt
import pytest
from allauth.socialaccount.models import SocialAccount, SocialApp
from botocore.exceptions import ClientError, NoCredentialsError
from conftest import API_JSON_CONTENT_TYPE, TEST_PASSWORD, TEST_USER
from django.conf import settings
from django.http import JsonResponse
from django.test import RequestFactory
from django.urls import reverse
from django_celery_results.models import TaskResult
from rest_framework import status
from rest_framework.response import Response
from api.compliance import get_compliance_frameworks
from api.db_router import MainRouter
from api.models import (
Integration,
Invitation,
@@ -32,7 +28,6 @@ from api.models import (
ProviderSecret,
Role,
RoleProviderGroupRelationship,
SAMLConfiguration,
Scan,
StateChoices,
Task,
@@ -40,7 +35,7 @@ from api.models import (
UserRoleRelationship,
)
from api.rls import Tenant
from api.v1.views import ComplianceOverviewViewSet, TenantFinishACSView
from api.v1.views import ComplianceOverviewViewSet
TODAY = str(datetime.today().date())
@@ -1241,10 +1236,10 @@ class TestProviderViewSet:
("uid.icontains", "1", 5),
("alias", "aws_testing_1", 1),
("alias.icontains", "aws", 2),
("inserted_at", TODAY, 5),
("inserted_at.gte", "2024-01-01", 5),
("inserted_at", TODAY, 6),
("inserted_at.gte", "2024-01-01", 6),
("inserted_at.lte", "2024-01-01", 0),
("updated_at.gte", "2024-01-01", 5),
("updated_at.gte", "2024-01-01", 6),
("updated_at.lte", "2024-01-01", 0),
]
),
@@ -1723,6 +1718,50 @@ class TestProviderSecretViewSet:
"kubeconfig_content": "kubeconfig-content",
},
),
# M365 with STATIC secret - no user or password
(
Provider.ProviderChoices.M365.value,
ProviderSecret.TypeChoices.STATIC,
{
"client_id": "client-id",
"client_secret": "client-secret",
"tenant_id": "tenant-id",
},
),
# M365 with user only
(
Provider.ProviderChoices.M365.value,
ProviderSecret.TypeChoices.STATIC,
{
"client_id": "client-id",
"client_secret": "client-secret",
"tenant_id": "tenant-id",
"user": "test@domain.com",
},
),
# M365 with password only
(
Provider.ProviderChoices.M365.value,
ProviderSecret.TypeChoices.STATIC,
{
"client_id": "client-id",
"client_secret": "client-secret",
"tenant_id": "tenant-id",
"password": "supersecret",
},
),
# M365 with user and password
(
Provider.ProviderChoices.M365.value,
ProviderSecret.TypeChoices.STATIC,
{
"client_id": "client-id",
"client_secret": "client-secret",
"tenant_id": "tenant-id",
"user": "test@domain.com",
"password": "supersecret",
},
),
],
)
def test_provider_secrets_create_valid(
@@ -1734,7 +1773,10 @@ class TestProviderSecretViewSet:
secret_data,
):
# Get the provider from the fixture and set its type
provider = Provider.objects.filter(provider=provider_type)[0]
try:
provider = Provider.objects.filter(provider=provider_type)[0]
except IndexError:
print(f"Provider {provider_type} not found")
data = {
"data": {
@@ -5561,265 +5603,334 @@ class TestIntegrationViewSet:
assert response.status_code == status.HTTP_400_BAD_REQUEST
@pytest.mark.django_db
class TestSAMLInitiateAPIView:
def test_valid_email_domain_and_certificates(
self, authenticated_client, saml_setup, monkeypatch
):
monkeypatch.setenv("SAML_PUBLIC_CERT", "fake_cert")
monkeypatch.setenv("SAML_PRIVATE_KEY", "fake_key")
# @pytest.mark.django_db
# class TestSAMLTokenValidation:
# def test_valid_token_returns_tokens(self, authenticated_client, create_test_user):
# user = create_test_user
# valid_token_data = {
# "access": "mock_access_token",
# "refresh": "mock_refresh_token",
# }
# saml_token = SAMLToken.objects.create(
# token=valid_token_data,
# user=user,
# expires_at=datetime.now(timezone.utc) + timedelta(seconds=10),
# )
url = reverse("api_saml_initiate")
payload = {"email_domain": saml_setup["email"]}
# url = reverse("token-saml")
# response = authenticated_client.post(f"{url}?id={saml_token.id}")
response = authenticated_client.post(url, data=payload, format="json")
# assert response.status_code == status.HTTP_200_OK
# assert response.json() == {"data": valid_token_data}
# assert not SAMLToken.objects.filter(id=saml_token.id).exists()
assert response.status_code == status.HTTP_302_FOUND
assert f"email={saml_setup['email']}" in response.url
assert (
reverse("saml_login", kwargs={"organization_slug": saml_setup["domain"]})
in response.url
)
# def test_invalid_token_id_returns_404(self, authenticated_client):
# url = reverse("token-saml")
# response = authenticated_client.post(f"{url}?id={str(uuid4())}")
def test_invalid_email_domain(self, authenticated_client):
url = reverse("api_saml_initiate")
payload = {"email_domain": "user@unauthorized.com"}
# assert response.status_code == status.HTTP_404_NOT_FOUND
# assert response.json()["errors"]["detail"] == "Invalid token ID."
response = authenticated_client.post(url, data=payload, format="json")
# def test_expired_token_returns_400(self, authenticated_client, create_test_user):
# user = create_test_user
# expired_token_data = {
# "access": "expired_access_token",
# "refresh": "expired_refresh_token",
# }
# saml_token = SAMLToken.objects.create(
# token=expired_token_data,
# user=user,
# expires_at=datetime.now(timezone.utc) - timedelta(seconds=1),
# )
assert response.status_code == status.HTTP_403_FORBIDDEN
assert response.json()["errors"]["detail"] == "Unauthorized domain."
# url = reverse("token-saml")
# response = authenticated_client.post(f"{url}?id={saml_token.id}")
def test_missing_certificates(self, authenticated_client, saml_setup, monkeypatch):
monkeypatch.setenv("SAML_PUBLIC_CERT", "")
monkeypatch.setenv("SAML_PRIVATE_KEY", "")
# assert response.status_code == status.HTTP_400_BAD_REQUEST
# assert response.json()["errors"]["detail"] == "Token expired."
# assert SAMLToken.objects.filter(id=saml_token.id).exists()
url = reverse("api_saml_initiate")
payload = {"email_domain": saml_setup["email"]}
# def test_token_can_be_used_only_once(self, authenticated_client, create_test_user):
# user = create_test_user
# token_data = {
# "access": "single_use_token",
# "refresh": "single_use_refresh",
# }
# saml_token = SAMLToken.objects.create(
# token=token_data,
# user=user,
# expires_at=datetime.now(timezone.utc) + timedelta(seconds=10),
# )
response = authenticated_client.post(url, data=payload, format="json")
# url = reverse("token-saml")
assert response.status_code == status.HTTP_403_FORBIDDEN
assert (
response.json()["errors"]["detail"]
== "SAML configuration is invalid: missing certificates."
)
# # First use: should succeed
# response1 = authenticated_client.post(f"{url}?id={saml_token.id}")
# assert response1.status_code == status.HTTP_200_OK
# # Second use: should fail (already deleted)
# response2 = authenticated_client.post(f"{url}?id={saml_token.id}")
# assert response2.status_code == status.HTTP_404_NOT_FOUND
@pytest.mark.django_db
class TestSAMLConfigurationViewSet:
def test_list_saml_configurations(self, authenticated_client, saml_setup):
config = SAMLConfiguration.objects.get(
email_domain=saml_setup["email"].split("@")[-1]
)
response = authenticated_client.get(reverse("saml-config-list"))
assert response.status_code == status.HTTP_200_OK
assert (
response.json()["data"][0]["attributes"]["email_domain"]
== config.email_domain
)
# @pytest.mark.django_db
# class TestSAMLInitiateAPIView:
# def test_valid_email_domain_and_certificates(
# self, authenticated_client, saml_setup, monkeypatch
# ):
# monkeypatch.setenv("SAML_PUBLIC_CERT", "fake_cert")
# monkeypatch.setenv("SAML_PRIVATE_KEY", "fake_key")
def test_retrieve_saml_configuration(self, authenticated_client, saml_setup):
config = SAMLConfiguration.objects.get(
email_domain=saml_setup["email"].split("@")[-1]
)
response = authenticated_client.get(
reverse("saml-config-detail", kwargs={"pk": config.id})
)
assert response.status_code == status.HTTP_200_OK
assert (
response.json()["data"]["attributes"]["metadata_xml"] == config.metadata_xml
)
# url = reverse("api_saml_initiate")
# payload = {"email_domain": saml_setup["email"]}
def test_create_saml_configuration(self, authenticated_client, tenants_fixture):
payload = {
"email_domain": "newdomain.com",
"metadata_xml": """<?xml version='1.0' encoding='UTF-8'?>
<md:EntityDescriptor entityID='TEST' xmlns:md='urn:oasis:names:tc:SAML:2.0:metadata'>
<md:IDPSSODescriptor WantAuthnRequestsSigned='false' protocolSupportEnumeration='urn:oasis:names:tc:SAML:2.0:protocol'>
<md:KeyDescriptor use='signing'>
<ds:KeyInfo xmlns:ds='http://www.w3.org/2000/09/xmldsig#'>
<ds:X509Data>
<ds:X509Certificate>TEST</ds:X509Certificate>
</ds:X509Data>
</ds:KeyInfo>
</md:KeyDescriptor>
<md:NameIDFormat>urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress</md:NameIDFormat>
<md:SingleSignOnService Binding='urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST' Location='https://TEST/sso/saml'/>
<md:SingleSignOnService Binding='urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect' Location='https://TEST/sso/saml'/>
</md:IDPSSODescriptor>
</md:EntityDescriptor>
""",
}
response = authenticated_client.post(
reverse("saml-config-list"), data=payload, format="json"
)
assert response.status_code == status.HTTP_201_CREATED
assert SAMLConfiguration.objects.filter(email_domain="newdomain.com").exists()
# response = authenticated_client.post(url, data=payload, format="json")
def test_update_saml_configuration(self, authenticated_client, saml_setup):
config = SAMLConfiguration.objects.get(
email_domain=saml_setup["email"].split("@")[-1]
)
payload = {
"data": {
"type": "saml-configurations",
"id": str(config.id),
"attributes": {
"metadata_xml": """<?xml version='1.0' encoding='UTF-8'?>
<md:EntityDescriptor entityID='TEST' xmlns:md='urn:oasis:names:tc:SAML:2.0:metadata'>
<md:IDPSSODescriptor WantAuthnRequestsSigned='false' protocolSupportEnumeration='urn:oasis:names:tc:SAML:2.0:protocol'>
<md:KeyDescriptor use='signing'>
<ds:KeyInfo xmlns:ds='http://www.w3.org/2000/09/xmldsig#'>
<ds:X509Data>
<ds:X509Certificate>TEST2</ds:X509Certificate>
</ds:X509Data>
</ds:KeyInfo>
</md:KeyDescriptor>
<md:NameIDFormat>urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress</md:NameIDFormat>
<md:SingleSignOnService Binding='urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST' Location='https://TEST/sso/saml'/>
<md:SingleSignOnService Binding='urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect' Location='https://TEST/sso/saml'/>
</md:IDPSSODescriptor>
</md:EntityDescriptor>
"""
},
}
}
response = authenticated_client.patch(
reverse("saml-config-detail", kwargs={"pk": config.id}),
data=payload,
content_type="application/vnd.api+json",
)
assert response.status_code == status.HTTP_200_OK
config.refresh_from_db()
assert (
config.metadata_xml.strip()
== payload["data"]["attributes"]["metadata_xml"].strip()
)
# assert response.status_code == status.HTTP_302_FOUND
# assert (
# reverse("saml_login", kwargs={"organization_slug": saml_setup["domain"]})
# in response.url
# )
# assert "SAMLRequest" not in response.url
def test_delete_saml_configuration(self, authenticated_client, saml_setup):
config = SAMLConfiguration.objects.get(
email_domain=saml_setup["email"].split("@")[-1]
)
response = authenticated_client.delete(
reverse("saml-config-detail", kwargs={"pk": config.id})
)
assert response.status_code == status.HTTP_204_NO_CONTENT
assert not SAMLConfiguration.objects.filter(id=config.id).exists()
# def test_invalid_email_domain(self, authenticated_client):
# url = reverse("api_saml_initiate")
# payload = {"email_domain": "user@unauthorized.com"}
# response = authenticated_client.post(url, data=payload, format="json")
# assert response.status_code == status.HTTP_403_FORBIDDEN
# assert response.json()["errors"]["detail"] == "Unauthorized domain."
@pytest.mark.django_db
class TestTenantFinishACSView:
def test_dispatch_skips_if_user_not_authenticated(self):
request = RequestFactory().get(
reverse("saml_finish_acs", kwargs={"organization_slug": "testtenant"})
)
request.user = type("Anonymous", (), {"is_authenticated": False})()
# @pytest.mark.django_db
# class TestSAMLConfigurationViewSet:
# def test_list_saml_configurations(self, authenticated_client, saml_setup):
# config = SAMLConfiguration.objects.get(
# email_domain=saml_setup["email"].split("@")[-1]
# )
# response = authenticated_client.get(reverse("saml-config-list"))
# assert response.status_code == status.HTTP_200_OK
# assert (
# response.json()["data"][0]["attributes"]["email_domain"]
# == config.email_domain
# )
with patch(
"allauth.socialaccount.providers.saml.views.get_app_or_404"
) as mock_get_app:
mock_get_app.return_value = SocialApp(
provider="saml",
client_id="testtenant",
name="Test App",
settings={},
)
# def test_retrieve_saml_configuration(self, authenticated_client, saml_setup):
# config = SAMLConfiguration.objects.get(
# email_domain=saml_setup["email"].split("@")[-1]
# )
# response = authenticated_client.get(
# reverse("saml-config-detail", kwargs={"pk": config.id})
# )
# assert response.status_code == status.HTTP_200_OK
# assert (
# response.json()["data"]["attributes"]["metadata_xml"] == config.metadata_xml
# )
view = TenantFinishACSView.as_view()
response = view(request, organization_slug="testtenant")
# def test_create_saml_configuration(self, authenticated_client, tenants_fixture):
# payload = {
# "email_domain": "newdomain.com",
# "metadata_xml": """<?xml version='1.0' encoding='UTF-8'?>
# <md:EntityDescriptor entityID='TEST' xmlns:md='urn:oasis:names:tc:SAML:2.0:metadata'>
# <md:IDPSSODescriptor WantAuthnRequestsSigned='false' protocolSupportEnumeration='urn:oasis:names:tc:SAML:2.0:protocol'>
# <md:KeyDescriptor use='signing'>
# <ds:KeyInfo xmlns:ds='http://www.w3.org/2000/09/xmldsig#'>
# <ds:X509Data>
# <ds:X509Certificate>TEST</ds:X509Certificate>
# </ds:X509Data>
# </ds:KeyInfo>
# </md:KeyDescriptor>
# <md:NameIDFormat>urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress</md:NameIDFormat>
# <md:SingleSignOnService Binding='urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST' Location='https://TEST/sso/saml'/>
# <md:SingleSignOnService Binding='urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect' Location='https://TEST/sso/saml'/>
# </md:IDPSSODescriptor>
# </md:EntityDescriptor>
# """,
# }
# response = authenticated_client.post(
# reverse("saml-config-list"), data=payload, format="json"
# )
# assert response.status_code == status.HTTP_201_CREATED
# assert SAMLConfiguration.objects.filter(email_domain="newdomain.com").exists()
assert response.status_code in [200, 302]
# def test_update_saml_configuration(self, authenticated_client, saml_setup):
# config = SAMLConfiguration.objects.get(
# email_domain=saml_setup["email"].split("@")[-1]
# )
# payload = {
# "data": {
# "type": "saml-configurations",
# "id": str(config.id),
# "attributes": {
# "metadata_xml": """<?xml version='1.0' encoding='UTF-8'?>
# <md:EntityDescriptor entityID='TEST' xmlns:md='urn:oasis:names:tc:SAML:2.0:metadata'>
# <md:IDPSSODescriptor WantAuthnRequestsSigned='false' protocolSupportEnumeration='urn:oasis:names:tc:SAML:2.0:protocol'>
# <md:KeyDescriptor use='signing'>
# <ds:KeyInfo xmlns:ds='http://www.w3.org/2000/09/xmldsig#'>
# <ds:X509Data>
# <ds:X509Certificate>TEST2</ds:X509Certificate>
# </ds:X509Data>
# </ds:KeyInfo>
# </md:KeyDescriptor>
# <md:NameIDFormat>urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress</md:NameIDFormat>
# <md:SingleSignOnService Binding='urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST' Location='https://TEST/sso/saml'/>
# <md:SingleSignOnService Binding='urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect' Location='https://TEST/sso/saml'/>
# </md:IDPSSODescriptor>
# </md:EntityDescriptor>
# """
# },
# }
# }
# response = authenticated_client.patch(
# reverse("saml-config-detail", kwargs={"pk": config.id}),
# data=payload,
# content_type="application/vnd.api+json",
# )
# assert response.status_code == status.HTTP_200_OK
# config.refresh_from_db()
# assert (
# config.metadata_xml.strip()
# == payload["data"]["attributes"]["metadata_xml"].strip()
# )
def test_dispatch_skips_if_social_app_not_found(self, users_fixture):
request = RequestFactory().get(
reverse("saml_finish_acs", kwargs={"organization_slug": "testtenant"})
)
request.user = users_fixture[0]
# def test_delete_saml_configuration(self, authenticated_client, saml_setup):
# config = SAMLConfiguration.objects.get(
# email_domain=saml_setup["email"].split("@")[-1]
# )
# response = authenticated_client.delete(
# reverse("saml-config-detail", kwargs={"pk": config.id})
# )
# assert response.status_code == status.HTTP_204_NO_CONTENT
# assert not SAMLConfiguration.objects.filter(id=config.id).exists()
with patch(
"allauth.socialaccount.providers.saml.views.get_app_or_404"
) as mock_get_app:
mock_get_app.return_value = SocialApp(
provider="saml",
client_id="testtenant",
name="Test App",
settings={},
)
view = TenantFinishACSView.as_view()
response = view(request, organization_slug="testtenant")
# @pytest.mark.django_db
# class TestTenantFinishACSView:
# def test_dispatch_skips_if_user_not_authenticated(self):
# request = RequestFactory().get(
# reverse("saml_finish_acs", kwargs={"organization_slug": "testtenant"})
# )
# request.user = type("Anonymous", (), {"is_authenticated": False})()
assert isinstance(response, JsonResponse) or response.status_code in [200, 302]
# with patch(
# "allauth.socialaccount.providers.saml.views.get_app_or_404"
# ) as mock_get_app:
# mock_get_app.return_value = SocialApp(
# provider="saml",
# client_id="testtenant",
# name="Test App",
# settings={},
# )
def test_dispatch_sets_user_profile_and_assigns_role(
self, create_test_user, tenants_fixture, saml_setup
):
user = create_test_user
original_email = user.email
original_name = user.name
original_company = user.company_name
user.email = f"doe@{saml_setup['email']}"
# view = TenantFinishACSView.as_view()
# response = view(request, organization_slug="testtenant")
social_account = SocialAccount(
user=user,
provider="saml",
extra_data={
"firstName": ["John"],
"lastName": ["Doe"],
"organization": ["TestOrg"],
"userType": ["saml_default_role"],
},
)
# assert response.status_code in [200, 302]
request = RequestFactory().get(
reverse("saml_finish_acs", kwargs={"organization_slug": "testtenant"})
)
request.user = user
# def test_dispatch_skips_if_social_app_not_found(self, users_fixture):
# request = RequestFactory().get(
# reverse("saml_finish_acs", kwargs={"organization_slug": "testtenant"})
# )
# request.user = users_fixture[0]
with (
patch(
"allauth.socialaccount.providers.saml.views.get_app_or_404"
) as mock_get_app_or_404,
patch("allauth.socialaccount.models.SocialApp.objects.get"),
patch(
"allauth.socialaccount.models.SocialAccount.objects.get"
) as mock_socialaccount_get,
patch("api.v1.serializers.TokenSocialLoginSerializer") as mock_serializer,
):
mock_get_app_or_404.return_value = MagicMock(
provider="saml", client_id="testtenant", name="Test App", settings={}
)
# with patch(
# "allauth.socialaccount.providers.saml.views.get_app_or_404"
# ) as mock_get_app:
# mock_get_app.return_value = SocialApp(
# provider="saml",
# client_id="testtenant",
# name="Test App",
# settings={},
# )
mock_socialaccount_get.return_value = social_account
# view = TenantFinishACSView.as_view()
# response = view(request, organization_slug="testtenant")
mock_instance = mock_serializer.return_value
mock_instance.is_valid.return_value = True
mock_instance.validated_data = {
"token": "mocktoken",
"refresh_token": "mockrefresh",
}
# assert isinstance(response, JsonResponse) or response.status_code in [200, 302]
view = TenantFinishACSView.as_view()
response = view(request, organization_slug="testtenant")
# def test_dispatch_sets_user_profile_and_assigns_role_and_creates_token(
# self, create_test_user, tenants_fixture, saml_setup, settings, monkeypatch
# ):
# monkeypatch.setenv("SAML_SSO_CALLBACK_URL", "http://localhost/sso-complete")
# user = create_test_user
# original_email = user.email
# original_name = user.name
# original_company = user.company_name
# user.email = f"doe@{saml_setup['email']}"
assert response.status_code == 200
user.refresh_from_db()
assert user.name == "John Doe"
assert user.company_name == "TestOrg"
# social_account = SocialAccount(
# user=user,
# provider="saml",
# extra_data={
# "firstName": ["John"],
# "lastName": ["Doe"],
# "organization": ["TestOrg"],
# "userType": ["saml_default_role"],
# },
# )
role = Role.objects.using(MainRouter.admin_db).get(name="saml_default_role")
assert role.tenant == tenants_fixture[0]
# request = RequestFactory().get(
# reverse("saml_finish_acs", kwargs={"organization_slug": "testtenant"})
# )
# request.user = user
assert (
UserRoleRelationship.objects.using(MainRouter.admin_db)
.filter(user=user, tenant_id=tenants_fixture[0].id)
.exists()
)
user.email = original_email
user.name = original_name
user.company_name = original_company
user.save()
# with (
# patch(
# "allauth.socialaccount.providers.saml.views.get_app_or_404"
# ) as mock_get_app_or_404,
# patch("allauth.socialaccount.models.SocialApp.objects.get"),
# patch(
# "allauth.socialaccount.models.SocialAccount.objects.get"
# ) as mock_sa_get,
# ):
# mock_get_app_or_404.return_value = MagicMock(
# provider="saml", client_id="testtenant", name="Test App", settings={}
# )
# mock_sa_get.return_value = social_account
# view = TenantFinishACSView.as_view()
# response = view(request, organization_slug="testtenant")
# assert response.status_code == 302
# expected_callback_host = "localhost"
# parsed_url = urlparse(response.url)
# assert parsed_url.netloc == expected_callback_host
# query_params = parse_qs(parsed_url.query)
# assert "id" in query_params
# token_id = query_params["id"][0]
# token_obj = SAMLToken.objects.get(id=token_id)
# assert token_obj.user == user
# assert not token_obj.is_expired()
# user.refresh_from_db()
# assert user.name == "John Doe"
# assert user.company_name == "TestOrg"
# role = Role.objects.using(MainRouter.admin_db).get(name="saml_default_role")
# assert role.tenant == tenants_fixture[0]
# assert (
# UserRoleRelationship.objects.using(MainRouter.admin_db)
# .filter(user=user, tenant_id=tenants_fixture[0].id)
# .exists()
# )
# # Membership should have been created with default role
# membership = Membership.objects.using(MainRouter.admin_db).get(
# user=user, tenant=tenants_fixture[0]
# )
# assert membership.role == Membership.RoleChoices.MEMBER
# assert membership.user == user
# assert membership.tenant == tenants_fixture[0]
# # Restore original user state
# user.email = original_email
# user.name = original_name
# user.company_name = original_company
# user.save()
@pytest.mark.django_db
+14 -15
View File
@@ -29,7 +29,6 @@ from api.models import (
ResourceTag,
Role,
RoleProviderGroupRelationship,
SAMLConfiguration,
Scan,
StateChoices,
StatusChoices,
@@ -1200,8 +1199,8 @@ class M365ProviderSecret(serializers.Serializer):
client_id = serializers.CharField()
client_secret = serializers.CharField()
tenant_id = serializers.CharField()
user = serializers.EmailField()
password = serializers.CharField()
user = serializers.EmailField(required=False)
password = serializers.CharField(required=False)
class Meta:
resource_name = "provider-secrets"
@@ -2068,23 +2067,23 @@ class IntegrationUpdateSerializer(BaseWriteIntegrationSerializer):
# SSO
class SamlInitiateSerializer(serializers.Serializer):
email_domain = serializers.CharField()
# class SamlInitiateSerializer(serializers.Serializer):
# email_domain = serializers.CharField()
class JSONAPIMeta:
resource_name = "saml-initiate"
# class JSONAPIMeta:
# resource_name = "saml-initiate"
class SamlMetadataSerializer(serializers.Serializer):
class JSONAPIMeta:
resource_name = "saml-meta"
# class SamlMetadataSerializer(serializers.Serializer):
# class JSONAPIMeta:
# resource_name = "saml-meta"
class SAMLConfigurationSerializer(RLSSerializer):
class Meta:
model = SAMLConfiguration
fields = ["id", "email_domain", "metadata_xml", "created_at", "updated_at"]
read_only_fields = ["id", "created_at", "updated_at"]
# class SAMLConfigurationSerializer(RLSSerializer):
# class Meta:
# model = SAMLConfiguration
# fields = ["id", "email_domain", "metadata_xml", "created_at", "updated_at"]
# read_only_fields = ["id", "created_at", "updated_at"]
class LighthouseConfigSerializer(RLSSerializer):
+19 -15
View File
@@ -23,13 +23,10 @@ from api.v1.views import (
ResourceViewSet,
RoleProviderGroupRelationshipView,
RoleViewSet,
SAMLConfigurationViewSet,
SAMLInitiateAPIView,
ScanViewSet,
ScheduleViewSet,
SchemaView,
TaskViewSet,
TenantFinishACSView,
TenantMembersViewSet,
TenantViewSet,
UserRoleRelationshipView,
@@ -53,7 +50,7 @@ router.register(
router.register(r"overviews", OverviewViewSet, basename="overview")
router.register(r"schedules", ScheduleViewSet, basename="schedule")
router.register(r"integrations", IntegrationViewSet, basename="integration")
router.register(r"saml-config", SAMLConfigurationViewSet, basename="saml-config")
# router.register(r"saml-config", SAMLConfigurationViewSet, basename="saml-config")
router.register(
r"lighthouse-configurations",
LighthouseConfigViewSet,
@@ -122,17 +119,24 @@ urlpatterns = [
),
name="provider_group-providers-relationship",
),
# API endpoint to start SAML SSO flow
path(
"auth/saml/initiate/", SAMLInitiateAPIView.as_view(), name="api_saml_initiate"
),
# Allauth SAML endpoints for tenants
path("accounts/", include("allauth.urls")),
path(
"api/v1/accounts/saml/<organization_slug>/acs/finish/",
TenantFinishACSView.as_view(),
name="saml_finish_acs",
),
# API endpoint to start SAML SSO flow (WIP)
# path(
# "auth/saml/initiate/", SAMLInitiateAPIView.as_view(), name="api_saml_initiate"
# ),
# # Custom SAML endpoints (must come before allauth.urls) (WIP)
# path(
# "accounts/saml/<organization_slug>/login/",
# CustomSAMLLoginView.as_view(),
# name="saml_login",
# ),
# path(
# "accounts/saml/<organization_slug>/acs/finish/",
# TenantFinishACSView.as_view(),
# name="saml_finish_acs",
# ),
# Allauth SAML endpoints for tenants (WIP)
# path("accounts/", include("allauth.urls")),
# path("tokens/saml", SAMLTokenValidateView.as_view(), name="token-saml"),
path("tokens/google", GoogleSocialLoginView.as_view(), name="token-google"),
path("tokens/github", GithubSocialLoginView.as_view(), name="token-github"),
path("", include(router.urls)),
+220 -159
View File
@@ -3,10 +3,8 @@ import os
from datetime import datetime, timedelta, timezone
import sentry_sdk
from allauth.socialaccount.models import SocialAccount, SocialApp
from allauth.socialaccount.providers.github.views import GitHubOAuth2Adapter
from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter
from allauth.socialaccount.providers.saml.views import FinishACSView
from botocore.exceptions import ClientError, NoCredentialsError, ParamValidationError
from celery.result import AsyncResult
from config.env import env
@@ -21,8 +19,7 @@ from django.contrib.postgres.search import SearchQuery
from django.db import transaction
from django.db.models import Count, Exists, F, OuterRef, Prefetch, Q, Sum
from django.db.models.functions import Coalesce
from django.http import HttpResponse, JsonResponse
from django.shortcuts import redirect
from django.http import HttpResponse
from django.urls import reverse
from django.utils.dateparse import parse_date
from django.utils.decorators import method_decorator
@@ -67,7 +64,6 @@ from api.compliance import (
get_compliance_frameworks,
)
from api.db_router import MainRouter
from api.db_utils import rls_transaction
from api.exceptions import TaskFailedException
from api.filters import (
ComplianceOverviewFilter,
@@ -105,8 +101,6 @@ from api.models import (
ResourceScanSummary,
Role,
RoleProviderGroupRelationship,
SAMLConfiguration,
SAMLDomainIndex,
Scan,
ScanSummary,
SeverityChoices,
@@ -163,8 +157,6 @@ from api.v1.serializers import (
RoleProviderGroupRelationshipSerializer,
RoleSerializer,
RoleUpdateSerializer,
SAMLConfigurationSerializer,
SamlInitiateSerializer,
ScanComplianceReportSerializer,
ScanCreateSerializer,
ScanReportSerializer,
@@ -401,171 +393,240 @@ class GithubSocialLoginView(SocialLoginView):
return original_response
@extend_schema(exclude=True)
class SAMLInitiateAPIView(GenericAPIView):
serializer_class = SamlInitiateSerializer
permission_classes = []
# @extend_schema(exclude=True)
# class SAMLTokenValidateView(GenericAPIView):
# resource_name = "tokens"
# http_method_names = ["post"]
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
email = serializer.validated_data["email_domain"]
domain = email.split("@", 1)[-1].lower()
# def post(self, request):
# token_id = request.query_params.get("id", "invalid")
# try:
# saml_token = SAMLToken.objects.using(MainRouter.admin_db).get(id=token_id)
# except SAMLToken.DoesNotExist:
# return Response({"detail": "Invalid token ID."}, status=404)
try:
check = SAMLDomainIndex.objects.get(email_domain=domain)
with rls_transaction(str(check.tenant_id)):
config = SAMLConfiguration.objects.get(tenant_id=str(check.tenant_id))
except (SAMLDomainIndex.DoesNotExist, SAMLConfiguration.DoesNotExist):
return Response(
{"detail": "Unauthorized domain."}, status=status.HTTP_403_FORBIDDEN
)
# if saml_token.is_expired():
# return Response({"detail": "Token expired."}, status=400)
# Check certificates are not empty
saml_public_cert = os.getenv("SAML_PUBLIC_CERT", "").strip()
saml_private_key = os.getenv("SAML_PRIVATE_KEY", "").strip()
# token_data = saml_token.token
# # Currently we don't store the tokens in the database, so we delete the token after use
# saml_token.delete()
if not saml_public_cert or not saml_private_key:
return Response(
{"detail": "SAML configuration is invalid: missing certificates."},
status=status.HTTP_403_FORBIDDEN,
)
saml_login_url = reverse(
"saml_login", kwargs={"organization_slug": config.email_domain}
)
return redirect(f"{saml_login_url}?email={email}")
# return Response(token_data, status=200)
@extend_schema_view(
list=extend_schema(
tags=["SAML"],
summary="List all SSO configurations",
description="Returns all the SAML-based SSO configurations associated with the current tenant.",
),
retrieve=extend_schema(
tags=["SAML"],
summary="Retrieve SSO configuration details",
description="Returns the details of a specific SAML configuration belonging to the current tenant.",
),
create=extend_schema(
tags=["SAML"],
summary="Create the SSO configuration",
description="Creates a new SAML SSO configuration for the current tenant, including email domain and metadata XML.",
),
partial_update=extend_schema(
tags=["SAML"],
summary="Update the SSO configuration",
description="Partially updates an existing SAML SSO configuration. Supports changes to email domain and metadata XML.",
),
destroy=extend_schema(
tags=["SAML"],
summary="Delete the SSO configuration",
description="Deletes an existing SAML SSO configuration associated with the current tenant.",
),
)
@method_decorator(CACHE_DECORATOR, name="retrieve")
@method_decorator(CACHE_DECORATOR, name="list")
class SAMLConfigurationViewSet(BaseRLSViewSet):
"""
ViewSet for managing SAML SSO configurations per tenant.
# @extend_schema(exclude=True)
# class CustomSAMLLoginView(LoginView):
# def dispatch(self, request, *args, **kwargs):
# """
# Convert GET requests to POST to bypass allauth's confirmation screen.
This endpoint allows authorized users to perform CRUD operations on SAMLConfiguration,
which define how a tenant integrates with an external SAML Identity Provider (IdP).
# Why this is necessary:
# - django-allauth requires POST for social logins to prevent open redirect attacks
# - SAML login links typically use GET requests (e.g., <a href="...">)
# - This conversion allows seamless login without user-facing confirmation
Typical use cases include:
- Listing all existing configurations for auditing or UI display.
- Retrieving a single configuration to show setup details.
- Creating or updating a configuration to onboard or modify SAML integration.
- Deleting a configuration when deactivating SAML for a tenant.
"""
# Security considerations:
# 1. Preserves CSRF protection: Original POST handling remains intact
# 2. Avoids global SOCIALACCOUNT_LOGIN_ON_GET=True which would:
# - Enable GET logins for ALL providers (security risk)
# - Potentially expose open redirect vulnerabilities
# 3. SAML payloads remain signed/encrypted regardless of HTTP method
# 4. No sensitive parameters are exposed in URLs (copied to POST body)
serializer_class = SAMLConfigurationSerializer
required_permissions = [Permissions.MANAGE_INTEGRATIONS]
queryset = SAMLConfiguration.objects.all()
def get_queryset(self):
# If called during schema generation, return an empty queryset
if getattr(self, "swagger_fake_view", False):
return SAMLConfiguration.objects.none()
return SAMLConfiguration.objects.filter(tenant=self.request.tenant_id)
# This approach maintains security while providing better UX.
# """
# if request.method == "GET":
# # Convert GET to POST while preserving parameters
# request.method = "POST"
# # Safe because SAML validates signatures
# request.POST = request.GET.copy()
# return super().dispatch(request, *args, **kwargs)
class TenantFinishACSView(FinishACSView):
def dispatch(self, request, organization_slug):
response = super().dispatch(request, organization_slug)
user = getattr(request, "user", None)
if not user or not user.is_authenticated:
return response
# @extend_schema(exclude=True)
# class SAMLInitiateAPIView(GenericAPIView):
# serializer_class = SamlInitiateSerializer
# permission_classes = []
try:
social_app = SocialApp.objects.get(
provider="saml", client_id=organization_slug
)
social_account = SocialAccount.objects.get(
user=user, provider=social_app.provider
)
except (SocialApp.DoesNotExist, SocialAccount.DoesNotExist):
return response
# def post(self, request, *args, **kwargs):
# # Validate the input payload and extract the domain
# serializer = self.get_serializer(data=request.data)
# serializer.is_valid(raise_exception=True)
# email = serializer.validated_data["email_domain"]
# domain = email.split("@", 1)[-1].lower()
extra = social_account.extra_data
user.first_name = (
extra.get("firstName", [""])[0] if extra.get("firstName") else ""
)
user.last_name = extra.get("lastName", [""])[0] if extra.get("lastName") else ""
user.company_name = (
extra.get("organization", [""])[0] if extra.get("organization") else ""
)
user.name = f"{user.first_name} {user.last_name}".strip()
if user.name == "":
user.name = "N/A"
user.save()
# # Retrieve the SAML configuration for the given email domain
# try:
# check = SAMLDomainIndex.objects.get(email_domain=domain)
# with rls_transaction(str(check.tenant_id)):
# config = SAMLConfiguration.objects.get(tenant_id=str(check.tenant_id))
# except (SAMLDomainIndex.DoesNotExist, SAMLConfiguration.DoesNotExist):
# return Response(
# {"detail": "Unauthorized domain."}, status=status.HTTP_403_FORBIDDEN
# )
email_domain = user.email.split("@")[-1]
tenant = (
SAMLConfiguration.objects.using(MainRouter.admin_db)
.get(email_domain=email_domain)
.tenant
)
role_name = (
extra.get("userType", ["saml_default_role"])[0].strip()
if extra.get("userType")
else "saml_default_role"
)
try:
role = Role.objects.using(MainRouter.admin_db).get(
name=role_name, tenant=tenant
)
except Role.DoesNotExist:
role = Role.objects.using(MainRouter.admin_db).create(
name=role_name,
tenant=tenant,
manage_users=False,
manage_account=False,
manage_billing=False,
manage_providers=False,
manage_integrations=False,
manage_scans=False,
unlimited_visibility=False,
)
UserRoleRelationship.objects.using(MainRouter.admin_db).filter(
user=user,
tenant_id=tenant.id,
).delete()
UserRoleRelationship.objects.using(MainRouter.admin_db).create(
user=user,
role=role,
tenant_id=tenant.id,
)
# # Check certificates are not empty (TODO: Validate certificates)
# # saml_public_cert = os.getenv("SAML_PUBLIC_CERT", "").strip()
# # saml_private_key = os.getenv("SAML_PRIVATE_KEY", "").strip()
serializer = TokenSocialLoginSerializer(data={"email": user.email})
serializer.is_valid(raise_exception=True)
return JsonResponse(
{
"type": "saml-social-tokens",
"attributes": serializer.validated_data,
}
)
# # if not saml_public_cert or not saml_private_key:
# # return Response(
# # {"detail": "SAML configuration is invalid: missing certificates."},
# # status=status.HTTP_403_FORBIDDEN,
# # )
# # Build the SAML login URL using the configured API host
# api_host = os.getenv("API_BASE_URL")
# login_path = reverse(
# "saml_login", kwargs={"organization_slug": config.email_domain}
# )
# login_url = urljoin(api_host, login_path)
# return redirect(login_url)
# @extend_schema_view(
# list=extend_schema(
# tags=["SAML"],
# summary="List all SSO configurations",
# description="Returns all the SAML-based SSO configurations associated with the current tenant.",
# ),
# retrieve=extend_schema(
# tags=["SAML"],
# summary="Retrieve SSO configuration details",
# description="Returns the details of a specific SAML configuration belonging to the current tenant.",
# ),
# create=extend_schema(
# tags=["SAML"],
# summary="Create the SSO configuration",
# description="Creates a new SAML SSO configuration for the current tenant, including email domain and metadata XML.",
# ),
# partial_update=extend_schema(
# tags=["SAML"],
# summary="Update the SSO configuration",
# description="Partially updates an existing SAML SSO configuration. Supports changes to email domain and metadata XML.",
# ),
# destroy=extend_schema(
# tags=["SAML"],
# summary="Delete the SSO configuration",
# description="Deletes an existing SAML SSO configuration associated with the current tenant.",
# ),
# )
# @method_decorator(CACHE_DECORATOR, name="retrieve")
# @method_decorator(CACHE_DECORATOR, name="list")
# class SAMLConfigurationViewSet(BaseRLSViewSet):
# """
# ViewSet for managing SAML SSO configurations per tenant.
# This endpoint allows authorized users to perform CRUD operations on SAMLConfiguration,
# which define how a tenant integrates with an external SAML Identity Provider (IdP).
# Typical use cases include:
# - Listing all existing configurations for auditing or UI display.
# - Retrieving a single configuration to show setup details.
# - Creating or updating a configuration to onboard or modify SAML integration.
# - Deleting a configuration when deactivating SAML for a tenant.
# """
# serializer_class = SAMLConfigurationSerializer
# required_permissions = [Permissions.MANAGE_INTEGRATIONS]
# queryset = SAMLConfiguration.objects.all()
# def get_queryset(self):
# # If called during schema generation, return an empty queryset
# if getattr(self, "swagger_fake_view", False):
# return SAMLConfiguration.objects.none()
# return SAMLConfiguration.objects.filter(tenant=self.request.tenant_id)
# class TenantFinishACSView(FinishACSView):
# def dispatch(self, request, organization_slug):
# response = super().dispatch(request, organization_slug)
# user = getattr(request, "user", None)
# if not user or not user.is_authenticated:
# return response
# try:
# social_app = SocialApp.objects.get(
# provider="saml", client_id=organization_slug
# )
# social_account = SocialAccount.objects.get(
# user=user, provider=social_app.provider
# )
# except (SocialApp.DoesNotExist, SocialAccount.DoesNotExist):
# return response
# extra = social_account.extra_data
# user.first_name = (
# extra.get("firstName", [""])[0] if extra.get("firstName") else ""
# )
# user.last_name = extra.get("lastName", [""])[0] if extra.get("lastName") else ""
# user.company_name = (
# extra.get("organization", [""])[0] if extra.get("organization") else ""
# )
# user.name = f"{user.first_name} {user.last_name}".strip()
# if user.name == "":
# user.name = "N/A"
# user.save()
# email_domain = user.email.split("@")[-1]
# tenant = (
# SAMLConfiguration.objects.using(MainRouter.admin_db)
# .get(email_domain=email_domain)
# .tenant
# )
# role_name = (
# extra.get("userType", ["saml_default_role"])[0].strip()
# if extra.get("userType")
# else "saml_default_role"
# )
# try:
# role = Role.objects.using(MainRouter.admin_db).get(
# name=role_name, tenant=tenant
# )
# except Role.DoesNotExist:
# role = Role.objects.using(MainRouter.admin_db).create(
# name=role_name,
# tenant=tenant,
# manage_users=False,
# manage_account=False,
# manage_billing=False,
# manage_providers=False,
# manage_integrations=False,
# manage_scans=False,
# unlimited_visibility=False,
# )
# UserRoleRelationship.objects.using(MainRouter.admin_db).filter(
# user=user,
# tenant_id=tenant.id,
# ).delete()
# UserRoleRelationship.objects.using(MainRouter.admin_db).create(
# user=user,
# role=role,
# tenant_id=tenant.id,
# )
# membership, _ = Membership.objects.using(MainRouter.admin_db).get_or_create(
# user=user,
# tenant=tenant,
# defaults={
# "user": user,
# "tenant": tenant,
# "role": Membership.RoleChoices.MEMBER,
# },
# )
# serializer = TokenSocialLoginSerializer(data={"email": user.email})
# serializer.is_valid(raise_exception=True)
# token_data = serializer.validated_data
# saml_token = SAMLToken.objects.using(MainRouter.admin_db).create(
# token=token_data, user=user
# )
# callback_url = env.str("SAML_SSO_CALLBACK_URL")
# redirect_url = f"{callback_url}?id={saml_token.id}"
# return redirect(redirect_url)
@extend_schema_view(
@@ -25,9 +25,9 @@ SOCIALACCOUNT_EMAIL_AUTHENTICATION = True
SOCIALACCOUNT_EMAIL_AUTHENTICATION_AUTO_CONNECT = True
SOCIALACCOUNT_ADAPTER = "api.adapters.ProwlerSocialAccountAdapter"
# SAML keys
SAML_PUBLIC_CERT = env("SAML_PUBLIC_CERT", default="")
SAML_PRIVATE_KEY = env("SAML_PRIVATE_KEY", default="")
# SAML keys (TODO: Validate certificates)
# SAML_PUBLIC_CERT = env("SAML_PUBLIC_CERT", default="")
# SAML_PRIVATE_KEY = env("SAML_PRIVATE_KEY", default="")
SOCIALACCOUNT_PROVIDERS = {
"google": {
@@ -60,12 +60,17 @@ SOCIALACCOUNT_PROVIDERS = {
"entity_id": "urn:prowler.com:sp",
},
"advanced": {
"x509cert": SAML_PUBLIC_CERT,
"private_key": SAML_PRIVATE_KEY,
# "x509cert": SAML_PUBLIC_CERT,
# "private_key": SAML_PRIVATE_KEY,
# "authn_request_signed": True,
# "want_assertion_signed": True,
# "want_message_signed": True,
"name_id_format": "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress",
"authn_request_signed": True,
"want_assertion_signed": True,
"want_message_signed": True,
"authn_request_signed": False,
"logout_request_signed": False,
"logout_response_signed": False,
"want_assertion_encrypted": False,
"want_name_id_encrypted": False,
},
},
}
+56 -53
View File
@@ -1,9 +1,8 @@
import logging
from datetime import datetime, timedelta, timezone
from unittest.mock import MagicMock, patch
from unittest.mock import patch
import pytest
from allauth.socialaccount.models import SocialLogin
from django.conf import settings
from django.db import connection as django_connection
from django.db import connections as django_connections
@@ -29,8 +28,6 @@ from api.models import (
Resource,
ResourceTag,
Role,
SAMLConfiguration,
SAMLDomainIndex,
Scan,
ScanSummary,
StateChoices,
@@ -381,8 +378,14 @@ def providers_fixture(tenants_fixture):
tenant_id=tenant.id,
scanner_args={"key1": "value1", "key2": {"key21": "value21"}},
)
provider6 = Provider.objects.create(
provider="m365",
uid="m365.test.com",
alias="m365_testing",
tenant_id=tenant.id,
)
return provider1, provider2, provider3, provider4, provider5
return provider1, provider2, provider3, provider4, provider5, provider6
@pytest.fixture
@@ -1115,62 +1118,62 @@ def latest_scan_finding(authenticated_client, providers_fixture, resources_fixtu
return finding
@pytest.fixture
def saml_setup(tenants_fixture):
tenant_id = tenants_fixture[0].id
domain = "example.com"
# @pytest.fixture
# def saml_setup(tenants_fixture):
# tenant_id = tenants_fixture[0].id
# domain = "example.com"
SAMLDomainIndex.objects.create(email_domain=domain, tenant_id=tenant_id)
# SAMLDomainIndex.objects.create(email_domain=domain, tenant_id=tenant_id)
metadata_xml = """<?xml version='1.0' encoding='UTF-8'?>
<md:EntityDescriptor entityID='TEST' xmlns:md='urn:oasis:names:tc:SAML:2.0:metadata'>
<md:IDPSSODescriptor WantAuthnRequestsSigned='false' protocolSupportEnumeration='urn:oasis:names:tc:SAML:2.0:protocol'>
<md:KeyDescriptor use='signing'>
<ds:KeyInfo xmlns:ds='http://www.w3.org/2000/09/xmldsig#'>
<ds:X509Data>
<ds:X509Certificate>TEST</ds:X509Certificate>
</ds:X509Data>
</ds:KeyInfo>
</md:KeyDescriptor>
<md:NameIDFormat>urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress</md:NameIDFormat>
<md:SingleSignOnService Binding='urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST' Location='https://TEST/sso/saml'/>
<md:SingleSignOnService Binding='urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect' Location='https://TEST/sso/saml'/>
</md:IDPSSODescriptor>
</md:EntityDescriptor>
"""
SAMLConfiguration.objects.create(
tenant_id=str(tenant_id),
email_domain=domain,
metadata_xml=metadata_xml,
)
# metadata_xml = """<?xml version='1.0' encoding='UTF-8'?>
# <md:EntityDescriptor entityID='TEST' xmlns:md='urn:oasis:names:tc:SAML:2.0:metadata'>
# <md:IDPSSODescriptor WantAuthnRequestsSigned='false' protocolSupportEnumeration='urn:oasis:names:tc:SAML:2.0:protocol'>
# <md:KeyDescriptor use='signing'>
# <ds:KeyInfo xmlns:ds='http://www.w3.org/2000/09/xmldsig#'>
# <ds:X509Data>
# <ds:X509Certificate>TEST</ds:X509Certificate>
# </ds:X509Data>
# </ds:KeyInfo>
# </md:KeyDescriptor>
# <md:NameIDFormat>urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress</md:NameIDFormat>
# <md:SingleSignOnService Binding='urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST' Location='https://TEST/sso/saml'/>
# <md:SingleSignOnService Binding='urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect' Location='https://TEST/sso/saml'/>
# </md:IDPSSODescriptor>
# </md:EntityDescriptor>
# """
# SAMLConfiguration.objects.create(
# tenant_id=str(tenant_id),
# email_domain=domain,
# metadata_xml=metadata_xml,
# )
return {
"email": f"user@{domain}",
"domain": domain,
"tenant_id": tenant_id,
}
# return {
# "email": f"user@{domain}",
# "domain": domain,
# "tenant_id": tenant_id,
# }
@pytest.fixture
def saml_sociallogin(users_fixture):
user = users_fixture[0]
user.email = "samlsso@acme.com"
extra_data = {
"firstName": ["Test"],
"lastName": ["User"],
"organization": ["Prowler"],
"userType": ["member"],
}
# @pytest.fixture
# def saml_sociallogin(users_fixture):
# user = users_fixture[0]
# user.email = "samlsso@acme.com"
# extra_data = {
# "firstName": ["Test"],
# "lastName": ["User"],
# "organization": ["Prowler"],
# "userType": ["member"],
# }
account = MagicMock()
account.provider = "saml"
account.extra_data = extra_data
# account = MagicMock()
# account.provider = "saml"
# account.extra_data = extra_data
sociallogin = MagicMock(spec=SocialLogin)
sociallogin.account = account
sociallogin.user = user
# sociallogin = MagicMock(spec=SocialLogin)
# sociallogin.account = account
# sociallogin.user = user
return sociallogin
# return sociallogin
def get_authorization_header(access_token: str) -> dict:
+2
View File
@@ -31,6 +31,7 @@ from prowler.lib.outputs.compliance.iso27001.iso27001_gcp import GCPISO27001
from prowler.lib.outputs.compliance.iso27001.iso27001_kubernetes import (
KubernetesISO27001,
)
from prowler.lib.outputs.compliance.iso27001.iso27001_m365 import M365ISO27001
from prowler.lib.outputs.compliance.kisa_ismsp.kisa_ismsp_aws import AWSKISAISMSP
from prowler.lib.outputs.compliance.mitre_attack.mitre_attack_aws import AWSMitreAttack
from prowler.lib.outputs.compliance.mitre_attack.mitre_attack_azure import (
@@ -90,6 +91,7 @@ COMPLIANCE_CLASS_MAP = {
"m365": [
(lambda name: name.startswith("cis_"), M365CIS),
(lambda name: name == "prowler_threatscore_m365", ProwlerThreatScoreM365),
(lambda name: name.startswith("iso27001_"), M365ISO27001),
],
}
+4 -3
View File
@@ -26,7 +26,7 @@ from api.models import (
StateChoices,
)
from api.models import StatusChoices as FindingStatus
from api.utils import initialize_prowler_provider
from api.utils import initialize_prowler_provider, return_prowler_provider
from api.v1.serializers import ScanTaskSerializer
from prowler.lib.outputs.finding import Finding as ProwlerFinding
from prowler.lib.scan.scan import Scan as ProwlerScan
@@ -149,7 +149,8 @@ def perform_prowler_scan(
provider_instance.save()
# If the provider is not connected, raise an exception outside the transaction.
# If raised within the transaction, the transaction will be rolled back and the provider will not be marked as not connected.
# If raised within the transaction, the transaction will be rolled back and the provider will not be marked
# as not connected.
if exc:
raise exc
@@ -526,7 +527,7 @@ def create_compliance_requirements(tenant_id: str, scan_id: str):
with rls_transaction(tenant_id):
scan_instance = Scan.objects.get(pk=scan_id)
provider_instance = scan_instance.provider
prowler_provider = initialize_prowler_provider(provider_instance)
prowler_provider = return_prowler_provider(provider_instance)
# Get check status data by region from findings
check_status_by_region = {}
+24 -50
View File
@@ -399,9 +399,7 @@ class TestCreateComplianceRequirements:
):
with (
patch("api.db_utils.rls_transaction"),
patch(
"tasks.jobs.scan.initialize_prowler_provider"
) as mock_initialize_prowler_provider,
patch("tasks.jobs.scan.return_prowler_provider") as mock_prowler_provider,
patch(
"tasks.jobs.scan.PROWLER_COMPLIANCE_OVERVIEW_TEMPLATE"
) as mock_compliance_template,
@@ -427,9 +425,7 @@ class TestCreateComplianceRequirements:
"us-east-1",
"us-west-2",
]
mock_initialize_prowler_provider.return_value = (
mock_prowler_provider_instance
)
mock_prowler_provider.return_value = mock_prowler_provider_instance
mock_compliance_template.__getitem__.return_value = {
"cis_1.4_aws": {
@@ -512,9 +508,7 @@ class TestCreateComplianceRequirements:
):
with (
patch("api.db_utils.rls_transaction"),
patch(
"tasks.jobs.scan.initialize_prowler_provider"
) as mock_initialize_prowler_provider,
patch("tasks.jobs.scan.return_prowler_provider") as mock_prowler_provider,
patch(
"tasks.jobs.scan.PROWLER_COMPLIANCE_OVERVIEW_TEMPLATE"
) as mock_compliance_template,
@@ -557,9 +551,7 @@ class TestCreateComplianceRequirements:
"us-east-1",
"us-west-2",
]
mock_initialize_prowler_provider.return_value = (
mock_prowler_provider_instance
)
mock_prowler_provider.return_value = mock_prowler_provider_instance
mock_compliance_template.__getitem__.return_value = {
"test_compliance": {
@@ -607,9 +599,7 @@ class TestCreateComplianceRequirements:
):
with (
patch("api.db_utils.rls_transaction"),
patch(
"tasks.jobs.scan.initialize_prowler_provider"
) as mock_initialize_prowler_provider,
patch("tasks.jobs.scan.return_prowler_provider") as mock_prowler_provider,
patch(
"tasks.jobs.scan.PROWLER_COMPLIANCE_OVERVIEW_TEMPLATE"
) as mock_compliance_template,
@@ -641,9 +631,7 @@ class TestCreateComplianceRequirements:
mock_prowler_provider_instance.get_regions.side_effect = AttributeError(
"No get_regions method"
)
mock_initialize_prowler_provider.return_value = (
mock_prowler_provider_instance
)
mock_prowler_provider.return_value = mock_prowler_provider_instance
mock_compliance_template.__getitem__.return_value = {
"kubernetes_cis": {
@@ -676,9 +664,7 @@ class TestCreateComplianceRequirements:
):
with (
patch("api.db_utils.rls_transaction"),
patch(
"tasks.jobs.scan.initialize_prowler_provider"
) as mock_initialize_prowler_provider,
patch("tasks.jobs.scan.return_prowler_provider") as mock_prowler_provider,
patch(
"tasks.jobs.scan.PROWLER_COMPLIANCE_OVERVIEW_TEMPLATE"
) as mock_compliance_template,
@@ -704,9 +690,7 @@ class TestCreateComplianceRequirements:
mock_prowler_provider_instance = MagicMock()
mock_prowler_provider_instance.get_regions.return_value = ["us-east-1"]
mock_initialize_prowler_provider.return_value = (
mock_prowler_provider_instance
)
mock_prowler_provider.return_value = mock_prowler_provider_instance
mock_compliance_template.__getitem__.return_value = {
"cis_1.4_aws": {
@@ -743,9 +727,7 @@ class TestCreateComplianceRequirements:
):
with (
patch("api.db_utils.rls_transaction"),
patch(
"tasks.jobs.scan.initialize_prowler_provider"
) as mock_initialize_prowler_provider,
patch("tasks.jobs.scan.return_prowler_provider") as mock_prowler_provider,
):
tenant = tenants_fixture[0]
scan = scans_fixture[0]
@@ -759,7 +741,7 @@ class TestCreateComplianceRequirements:
tenant_id = str(tenant.id)
scan_id = str(scan.id)
mock_initialize_prowler_provider.side_effect = Exception(
mock_prowler_provider.side_effect = Exception(
"Provider initialization failed"
)
@@ -774,9 +756,7 @@ class TestCreateComplianceRequirements:
):
with (
patch("api.db_utils.rls_transaction"),
patch(
"tasks.jobs.scan.initialize_prowler_provider"
) as mock_initialize_prowler_provider,
patch("tasks.jobs.scan.return_prowler_provider") as mock_prowler_provider,
patch(
"tasks.jobs.scan.PROWLER_COMPLIANCE_OVERVIEW_TEMPLATE"
) as mock_compliance_template,
@@ -800,9 +780,7 @@ class TestCreateComplianceRequirements:
mock_prowler_provider_instance = MagicMock()
mock_prowler_provider_instance.get_regions.return_value = ["us-east-1"]
mock_initialize_prowler_provider.return_value = (
mock_prowler_provider_instance
)
mock_prowler_provider.return_value = mock_prowler_provider_instance
mock_compliance_template.__getitem__.return_value = {}
@@ -821,8 +799,8 @@ class TestCreateComplianceRequirements:
with (
patch("api.db_utils.rls_transaction"),
patch(
"tasks.jobs.scan.initialize_prowler_provider"
) as mock_initialize_prowler_provider,
"tasks.jobs.scan.return_prowler_provider"
) as mock_return_prowler_provider,
patch(
"tasks.jobs.scan.PROWLER_COMPLIANCE_OVERVIEW_TEMPLATE"
) as mock_compliance_template,
@@ -862,9 +840,7 @@ class TestCreateComplianceRequirements:
mock_prowler_provider_instance = MagicMock()
mock_prowler_provider_instance.get_regions.return_value = ["us-east-1"]
mock_initialize_prowler_provider.return_value = (
mock_prowler_provider_instance
)
mock_return_prowler_provider.return_value = mock_prowler_provider_instance
mock_compliance_template.__getitem__.return_value = {
"cis_1.4_aws": {
@@ -898,8 +874,8 @@ class TestCreateComplianceRequirements:
with (
patch("api.db_utils.rls_transaction"),
patch(
"tasks.jobs.scan.initialize_prowler_provider"
) as mock_initialize_prowler_provider,
"tasks.jobs.scan.return_prowler_provider"
) as mock_return_prowler_provider,
patch(
"tasks.jobs.scan.PROWLER_COMPLIANCE_OVERVIEW_TEMPLATE"
) as mock_compliance_template,
@@ -911,7 +887,6 @@ class TestCreateComplianceRequirements:
):
tenant = tenants_fixture[0]
scan = scans_fixture[0]
providers_fixture[0]
mock_findings_filter.return_value = []
@@ -921,7 +896,7 @@ class TestCreateComplianceRequirements:
"us-west-2",
"eu-west-1",
]
mock_initialize_prowler_provider.return_value = mock_prowler_provider
mock_return_prowler_provider.return_value = mock_prowler_provider
mock_compliance_template.__getitem__.return_value = {
"test_compliance": {
@@ -990,8 +965,8 @@ class TestCreateComplianceRequirements:
with (
patch("api.db_utils.rls_transaction"),
patch(
"tasks.jobs.scan.initialize_prowler_provider"
) as mock_initialize_prowler_provider,
"tasks.jobs.scan.return_prowler_provider"
) as mock_return_prowler_provider,
patch(
"tasks.jobs.scan.PROWLER_COMPLIANCE_OVERVIEW_TEMPLATE"
) as mock_compliance_template,
@@ -1009,7 +984,7 @@ class TestCreateComplianceRequirements:
mock_prowler_provider = MagicMock()
mock_prowler_provider.get_regions.return_value = ["us-east-1", "us-west-2"]
mock_initialize_prowler_provider.return_value = mock_prowler_provider
mock_return_prowler_provider.return_value = mock_prowler_provider
mock_compliance_template.__getitem__.return_value = {
"test_compliance": {
@@ -1077,8 +1052,8 @@ class TestCreateComplianceRequirements:
with (
patch("api.db_utils.rls_transaction"),
patch(
"tasks.jobs.scan.initialize_prowler_provider"
) as mock_initialize_prowler_provider,
"tasks.jobs.scan.return_prowler_provider"
) as mock_return_prowler_provider,
patch(
"tasks.jobs.scan.PROWLER_COMPLIANCE_OVERVIEW_TEMPLATE"
) as mock_compliance_template,
@@ -1090,13 +1065,12 @@ class TestCreateComplianceRequirements:
):
tenant = tenants_fixture[0]
scan = scans_fixture[0]
providers_fixture[0]
mock_findings_filter.return_value = []
mock_prowler_provider = MagicMock()
mock_prowler_provider.get_regions.return_value = ["us-east-1", "us-west-2"]
mock_initialize_prowler_provider.return_value = mock_prowler_provider
mock_return_prowler_provider.return_value = mock_prowler_provider
mock_compliance_template.__getitem__.return_value = {
"test_compliance": {
+2 -27
View File
@@ -212,34 +212,9 @@ Each check **must** populate the report with an unique identifier for the audite
- Resource Name — `report.resource_name`.
- The name of the Github resource. In the case of a repository, this is just the repository name. For full repository names use the resource `full_name`.
### Using the Audit Configuration
### Configurable Checks in Prowler
Prowler has a [configuration file](../tutorials/configuration_file.md) which is used to pass certain configuration values to the checks. For example:
```python title="ec2_securitygroup_with_many_ingress_egress_rules.py"
class ec2_securitygroup_with_many_ingress_egress_rules(Check):
def execute(self):
findings = []
max_security_group_rules = ec2_client.audit_config.get(
"max_security_group_rules", 50
)
for security_group_arn, security_group in ec2_client.security_groups.items():
```
We use the `audit_config` object to retrieve the value of `max_security_group_rules`, which is the default value of 50 if the configuration value is not present.
The configuration file is located at [`prowler/config/config.yaml`](https://github.com/prowler-cloud/prowler/blob/master/prowler/config/config.yaml) and is used to pass certain configuration values to the checks. For example:
```yaml title="config.yaml"
aws:
max_security_group_rules: 50
```
This `audit_config` object is a Python dictionary that stores values read from the configuration file. It can be accessed by the check using the `audit_config` attribute of the service client.
???+ note
Always use the `dictionary.get(value, default)` syntax to ensure a default value is set when the configuration value is not present.
See [Configurable Checks](./configurable-checks.md) for detailed information on making checks configurable using the `audit_config` object and configuration file.
## Metadata Structure for Prowler Checks
@@ -0,0 +1,46 @@
# Configurable Checks in Prowler
Prowler empowers users to extend and adapt cloud security coverage by making checks configurable through the use of the `audit_config` object. This approach enables customization of checks to meet specific requirements through a configuration file.
## Understanding the `audit_config` Object
The `audit_config` object is a dictionary attached to each provider's service client (for example, `<service_name>_client.audit_config`). This object loads configuration values from the main configuration file (`prowler/config/config.yaml`). Use `audit_config` to make checks flexible and user-configurable.
## Using `audit_config` to Configure Checks
Retrieve configuration values in a check by using the `.get()` method on the `audit_config` object. For example, to get the minimum number of Availability Zones for Lambda from the configuration file, use the following code. If the value is not set in the configuration, the check defaults to 2:
```python
LAMBDA_MIN_AZS = awslambda_client.audit_config.get("lambda_min_azs", 2)
```
Always provide a default value in `.get()` to ensure the check works even if the configuration is missing the variable.
### Example: Security Group Rule Limit
```python title="ec2_securitygroup_with_many_ingress_egress_rules.py"
class ec2_securitygroup_with_many_ingress_egress_rules(Check):
def execute(self):
findings = []
max_security_group_rules = ec2_client.audit_config.get(
"max_security_group_rules", 50
)
for security_group_arn, security_group in ec2_client.security_groups.items():
# ... check logic ...
```
## Required File Updates for Configurable Variables
When adding a new configurable check to Prowler, update the following files:
- **Configuration File:** Add the new variable under the relevant provider or service section in `prowler/config/config.yaml`.
```yaml
# aws.awslambda_function_vpc_multi_az
lambda_min_azs: 2
```
- **Test Fixtures:** If tests depend on this configuration, add the variable to `tests/config/fixtures/config.yaml`.
- **Documentation:** Document the new variable in the list of configurable checks in `docs/tutorials/configuration_file.md`.
For a complete list of checks that already support configuration, see the [Configuration File Tutorial](../tutorials/configuration_file.md).
This approach ensures that checks are easily configurable, making Prowler highly adaptable to different environments and requirements.
+62 -4
View File
@@ -139,7 +139,7 @@ Prowler for M365 currently supports the following authentication types:
???+ warning
For Prowler App only the Service Principal with User Credentials authentication method is supported.
### Service Principal authentication
### Service Principal authentication (recommended)
Authentication flag: `--sp-env-auth`
@@ -154,9 +154,11 @@ export AZURE_TENANT_ID="XXXXXXXXX"
If you try to execute Prowler with the `--sp-env-auth` flag and those variables are empty or not exported, the execution is going to fail.
Follow the instructions in the [Create Prowler Service Principal](../tutorials/microsoft365/getting-started-m365.md#create-the-service-principal-app) section to create a service principal.
With this credentials you will only be able to run the checks that work through MS Graph, this means that you won't run all the provider. If you want to scan all the checks from M365 you will need to use the recommended authentication method.
If you don't add the external API permissions described in the mentioned section above you will only be able to run the checks that work through MS Graph. This means that you won't run all the provider.
### Service Principal and User Credentials authentication (recommended)
If you want to scan all the checks from M365 you will need to use the recommended authentication method or add the external API permissions.
### Service Principal and User Credentials authentication
Authentication flag: `--env-auth`
@@ -173,6 +175,7 @@ export M365_PASSWORD="examplepassword"
These two new environment variables are **required** to execute the PowerShell modules needed to retrieve information from M365 services. Prowler uses Service Principal authentication to access Microsoft Graph and user credentials to authenticate to Microsoft PowerShell modules.
- `M365_USER` should be your Microsoft account email using the **assigned domain in the tenant**. This means it must look like `example@YourCompany.onmicrosoft.com` or `example@YourCompany.com`, but it must be the exact domain assigned to that user in the tenant.
???+ warning
If the user is newly created, you need to sign in with that account first, as Microsoft will prompt you to change the password. If you don’t complete this step, user authentication will fail because Microsoft marks the initial password as expired.
@@ -213,6 +216,8 @@ Prowler for M365 requires two types of permission scopes to be set (if you want
- `Policy.Read.All`: Required for all services.
- `SharePointTenantSettings.Read.All`: Required for SharePoint service.
- `User.Read` (IMPORTANT: this must be set as **delegated**): Required for the sign-in.
- `Exchange.ManageAsApp` from external API `Office 365 Exchange Online`: Required for Exchange PowerShell module app authentication. You also need to assign the `Exchange Administrator` role to the app.
- `application_access` from external API `Skype and Teams Tenant Admin API`: Required for Teams PowerShell module app authentication.
???+ note
You can replace `Directory.Read.All` with `Domain.Read.All` is a more restrictive permission but you won't be able to run the Entra checks related with DirectoryRoles and GetUsers.
@@ -221,7 +226,8 @@ Prowler for M365 requires two types of permission scopes to be set (if you want
- **Powershell Modules Permissions**: These are set at the `M365_USER` level, so the user used to run Prowler must have one of the following roles:
- **Powershell Modules Permissions** (if using user credentials): These are set at the `M365_USER` level, so the user used to run Prowler must have one of the following roles:
- `Global Reader` (recommended): this allows you to read all roles needed.
- `Exchange Administrator` and `Teams Administrator`: user needs both roles but with this [roles](https://learn.microsoft.com/en-us/exchange/permissions-exo/permissions-exo#microsoft-365-permissions-in-exchange-online) you can access to the same information as a Global Reader (since only read access is needed, Global Reader is recommended).
@@ -439,6 +445,7 @@ The required modules are:
- [ExchangeOnlineManagement](https://www.powershellgallery.com/packages/ExchangeOnlineManagement/3.6.0): Minimum version 3.6.0. Required for several checks across Exchange, Defender, and Purview.
- [MicrosoftTeams](https://www.powershellgallery.com/packages/MicrosoftTeams/6.6.0): Minimum version 6.6.0. Required for all Teams checks.
- [MSAL.PS](https://www.powershellgallery.com/packages/MSAL.PS/4.32.0): Required for Exchange module via application authentication.
## GitHub
### Authentication
@@ -455,3 +462,54 @@ The provided credentials must have the appropriate permissions to perform all th
???+ note
GitHub App Credentials support less checks than other authentication methods.
## Infrastructure as Code (IaC)
Prowler's Infrastructure as Code (IaC) provider enables you to scan local infrastructure code for security and compliance issues using [Checkov](https://www.checkov.io/). This provider supports a wide range of IaC frameworks and requires no cloud authentication.
### Authentication
The IaC provider does not require any authentication or credentials since it scans local files directly. This makes it ideal for CI/CD pipelines and local development environments.
### Supported Frameworks
The IaC provider leverages Checkov to support multiple frameworks, including:
- Terraform
- CloudFormation
- Kubernetes
- ARM (Azure Resource Manager)
- Serverless
- Dockerfile
- YAML/JSON (generic IaC)
- Bicep
- Helm
- GitHub Actions, GitLab CI, Bitbucket Pipelines, Azure Pipelines, CircleCI, Argo Workflows
- Ansible
- Kustomize
- OpenAPI
- SAST, SCA (Software Composition Analysis)
### Usage
To run Prowler with the IaC provider, use the `iac` flag. You can specify the directory to scan, frameworks to include, and paths to exclude.
#### Basic Example
```console
prowler iac --scan-path ./my-iac-directory
```
#### Specify Frameworks
Scan only Terraform and Kubernetes files:
```console
prowler iac --scan-path ./my-iac-directory --frameworks terraform kubernetes
```
#### Exclude Paths
```console
prowler iac --scan-path ./my-iac-directory --exclude-path ./my-iac-directory/test,./my-iac-directory/examples
```
+25 -3
View File
@@ -572,12 +572,12 @@ With M365 you need to specify which auth method is going to be used:
```console
# To use service principal authentication for MSGraph and PowerShell modules
prowler m365 --sp-env-auth
# To use both service principal (for MSGraph) and user credentials (for PowerShell modules)
prowler m365 --env-auth
# To use service principal authentication
prowler m365 --sp-env-auth
# To use az cli authentication
prowler m365 --az-cli-auth
@@ -612,5 +612,27 @@ prowler github --github-app-id app_id --github-app-key app_key
2. `OAUTH_APP_TOKEN`
3. `GITHUB_APP_ID` and `GITHUB_APP_KEY`
#### Infrastructure as Code (IaC)
Prowler's Infrastructure as Code (IaC) provider enables you to scan local infrastructure code for security and compliance issues using [Checkov](https://www.checkov.io/). This provider supports a wide range of IaC frameworks, allowing you to assess your code before deployment.
```console
# Scan a directory for IaC files
prowler iac --scan-path ./my-iac-directory
# Specify frameworks to scan (default: all)
prowler iac --scan-path ./my-iac-directory --frameworks terraform kubernetes
# Exclude specific paths
prowler iac --scan-path ./my-iac-directory --exclude-path ./my-iac-directory/test,./my-iac-directory/examples
```
???+ note
- The IaC provider does not require cloud authentication
- It is ideal for CI/CD pipelines and local development environments
- For more details on supported frameworks and rules, see the [Checkov documentation](https://www.checkov.io/1.Welcome/Quick%20Start.html)
See more details about IaC scanning in the [IaC Tutorial](tutorials/iac/getting-started-iac.md) section.
## Prowler v2 Documentation
For **Prowler v2 Documentation**, please check it out [here](https://github.com/prowler-cloud/prowler/blob/8818f47333a0c1c1a457453c87af0ea5b89a385f/README.md).
+67
View File
@@ -0,0 +1,67 @@
# Getting Started with the IaC Provider
Prowler's Infrastructure as Code (IaC) provider enables you to scan local infrastructure code for security and compliance issues using [Checkov](https://www.checkov.io/). This provider supports a wide range of IaC frameworks, allowing you to assess your code before deployment.
## Supported Frameworks
The IaC provider leverages Checkov to support multiple frameworks, including:
- Terraform
- CloudFormation
- Kubernetes
- ARM (Azure Resource Manager)
- Serverless
- Dockerfile
- YAML/JSON (generic IaC)
- Bicep
- Helm
- GitHub Actions, GitLab CI, Bitbucket Pipelines, Azure Pipelines, CircleCI, Argo Workflows
- Ansible
- Kustomize
- OpenAPI
- SAST, SCA (Software Composition Analysis)
## How It Works
- The IaC provider scans your local directory (or a specified path) for supported IaC files.
- No cloud credentials or authentication are required.
- Mutelist logic is handled by Checkov, not Prowler.
- Results are output in the same formats as other Prowler providers (CSV, JSON, HTML, etc.).
## Usage
To run Prowler with the IaC provider, use the `iac` argument. You can specify the directory to scan, frameworks to include, and paths to exclude.
### Basic Example
```sh
prowler iac --scan-path ./my-iac-directory
```
### Specify Frameworks
Scan only Terraform and Kubernetes files:
```sh
prowler iac --scan-path ./my-iac-directory --frameworks terraform kubernetes
```
### Exclude Paths
```sh
prowler iac --scan-path ./my-iac-directory --exclude-path ./my-iac-directory/test,./my-iac-directory/examples
```
## Output
You can use the standard Prowler output options, for example:
```sh
prowler iac --scan-path ./iac --output-formats csv json html
```
## Notes
- The IaC provider does not require cloud authentication.
- It is ideal for CI/CD pipelines and local development environments.
- For more details on supported frameworks and rules, see the [Checkov documentation](https://www.checkov.io/1.Welcome/Quick%20Start.html).
Binary file not shown.

After

Width:  |  Height:  |  Size: 255 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 332 KiB

@@ -30,7 +30,7 @@ Go to the Entra ID portal, then you can search for `Domain` or go to Identity >
![Custom Domain Names](./img/custom-domain-names.png)
Once you are there just select the domain you want to use.
Once you are there just select the domain you want to use as unique identifier for your M365 account in Prowler Cloud/App.
---
@@ -92,7 +92,7 @@ With this done you will have all the needed keys, summarized in the following ta
---
### Grant required API permissions
### Grant required Graph API permissions
Assign the following Microsoft Graph permissions:
@@ -100,7 +100,7 @@ Assign the following Microsoft Graph permissions:
- `Directory.Read.All`: Required for all services.
- `Policy.Read.All`: Required for all services.
- `SharePointTenantSettings.Read.All`: Required for SharePoint service.
- `User.Read` (IMPORTANT: this is set as **delegated**): Required for the sign-in.
- `User.Read` (IMPORTANT: this is set as **delegated**): Required for the sign-in only if using user authentication.
???+ note
You can replace `Directory.Read.All` with `Domain.Read.All` is a more restrictive permission but you won't be able to run the Entra checks related with DirectoryRoles and GetUsers.
@@ -128,18 +128,83 @@ Follow these steps to assign the permissions:
![Application Permissions](./img/app-permissions.png)
---
4. Click `+ Add a permission` > `Microsoft Graph` > `Delegated permissions`
![Add API Permission](./img/add-delegated-api-permission.png)
### Grant PowerShell modules permissions
5. Search and select:
The permissions you need to grant depends on whether you are using user credentials or service principal to authenticate to the M365 modules.
???+ warning "Warning"
Make sure you add the correct set of permissions for the authentication method you are using.
#### If using application(service principal) authentication (Recommended)
To grant the permissions for the PowerShell modules via application authentication, you need to add the necessary APIs to your app registration.
???+ warning "Warning"
You need to have a license that allows you to use the APIs.
1. Add Exchange API:
- Search and select`Office 365 Exchange Online` API in **APIs my organization uses**.
![Office 365 Exchange Online API](./img/search-exchange-api.png)
- Select `Exchange.ManageAsApp` permission and click on `Add permissions`.
![Exchange.ManageAsApp Permission](./img/exchange-permission.png)
You also need to assign the `Exchange Administrator` role to the app. For that go to `Roles and administrators` and in the `Administrative roles` section click `here` to go to the directory level assignment:
![Roles and administrators](./img/here.png)
Once in the directory level assignment, search for `Exchange Administrator` and click on it to open the assginments page of that role.
![Exchange Administrator Role](./img/exchange-administrator-role.png)
Click on `Add assignments`, search for your app and click on `Assign`.
You have to select it as `Active` and click on `Assign` to assign the role to the app.
![Assign Exchange Administrator Role](./img/assign-exchange-administrator-role.png)
2. Add Teams API:
- Search and select `Skype and Teams Tenant Admin API` API in **APIs my organization uses**.
![Skype and Teams Tenant Admin API](./img/search-skype-teams-tenant-admin-api.png)
- Select `application_access` permission and click on `Add permissions`.
![application_access Permission](./img/teams-permission.png)
3. Click on `Grant admin consent for <your-tenant-name>` to grant admin consent.
![Grant Admin Consent](./img/grant-external-api-permissions.png)
The final result of permission assignment should be this:
![Final Permission Assignment](./img/final-permissions.png)
---
#### If using user authentication
This method is not recommended because it requires a user with MFA enabled and Microsoft will not allow MFA capable users to authenticate programmatically after 1st September 2025. See [Microsoft documentation](https://learn.microsoft.com/en-us/entra/identity/authentication/concept-mandatory-multifactor-authentication?tabs=dotnet) for more information.
???+ warning
Remember that if the user is newly created, you need to sign in with that account first, as Microsoft will prompt you to change the password. If you don’t complete this step, user authentication will fail because Microsoft marks the initial password as expired.
1. Search and select:
- `User.Read`
![Permission Screenshots](./img/directory-permission-delegated.png)
6. After adding all the permissions, click on `Grant admin consent`
2. Click `Add permissions`, then **grant admin consent**
![Grant Admin Consent](./img/grant-admin-consent.png)
@@ -147,37 +212,32 @@ Follow these steps to assign the permissions:
![Final Permission Assignment](./img/final-permissions-m365.png)
---
3. Assign **required roles** to your **user**
### Assign required roles to your user
Assign one of the following roles to your User:
Assign one of the following roles to your User:
- `Global Reader` (recommended): this allows you to read all roles needed.
- `Exchange Administrator` and `Teams Administrator`: user needs both roles but with this [roles](https://learn.microsoft.com/en-us/exchange/permissions-exo/permissions-exo#microsoft-365-permissions-in-exchange-online) you can access to the same information as a Global Reader (here you only read so that's why we recomend that role).
- `Global Reader` (recommended): this allows you to read all roles needed.
- `Exchange Administrator` and `Teams Administrator`: user needs both roles but with this [roles](https://learn.microsoft.com/en-us/exchange/permissions-exo/permissions-exo#microsoft-365-permissions-in-exchange-online) you can access to the same information as a Global Reader (here you only read so that's why we recomend that role).
Follow these steps to assign the role:
Follow these steps to assign the role:
1. Go to Users > All Users > Click on the email for the user you will use
1. Go to Users > All Users > Click on the email for the user you will use
![User Overview](./img/user-info-page.png)
![User Overview](./img/user-info-page.png)
2. Click `Assigned Roles`
2. Click `Assigned Roles`
![User Roles](./img/user-role-page.png)
![User Roles](./img/user-role-page.png)
3. Click on `Add assignments`, then search and select:
3. Click on `Add assignments`, then search and select:
- `Global Reader` This is the recommended, if you want to use the others just search for them
- `Global Reader` This is the recommended, if you want to use the others just search for them
![Global Reader Screenshots](./img/global-reader.png)
![Global Reader Screenshots](./img/global-reader.png)
4. Click on next, then assign the role as `Active`, and click on `Assign` to grant admin consent
4. Click on next, then assign the role as `Active`, and click on `Assign` to grant admin consent
![Grant Admin Consent for Role](./img/grant-admin-consent-for-role.png)
???+ warning
Remember that if the user is newly created, you need to sign in with that account first, as Microsoft will prompt you to change the password. If you don’t complete this step, user authentication will fail because Microsoft marks the initial password as expired.
![Grant Admin Consent for Role](./img/grant-admin-consent-for-role.png)
---
Binary file not shown.

After

Width:  |  Height:  |  Size: 118 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 141 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 111 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 82 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 195 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 268 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 349 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 91 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 69 KiB

+37 -7
View File
@@ -24,7 +24,7 @@ DJANGO_ALLOWED_HOSTS=localhost,127.0.0.1,prowler-api,mycompany.prowler
To enable SAML support, you must provide a public certificate and private key to allow Prowler to sign SAML requests and validate responses.
### Why is this necessary?
### Why is this necessary?
SAML relies on digital signatures to verify trust between the Identity Provider (IdP) and the Service Provider (SP). Prowler acts as the SP and must use a certificate to sign outbound authentication requests.
@@ -121,7 +121,7 @@ Start ngrok on port 8080:
ngrok http 8080
```
Then, copy the generated ngrok URL and include it in the ALLOWED_HOSTS setting. If you’re using the development environment, it usually defaults to *, but in some cases this may not work properly, like in my tests (investigate):
Then, copy the generated ngrok URL and include it in the ALLOWED_HOSTS setting. If you're using the development environment, it usually defaults to *, but in some cases this may not work properly, like in my tests (investigate):
```
ALLOWED_HOSTS = env.list("DJANGO_ALLOWED_HOSTS", default=["*"])
@@ -129,7 +129,7 @@ ALLOWED_HOSTS = env.list("DJANGO_ALLOWED_HOSTS", default=["*"])
## 4. Configure the Identity Provider (IdP)
Start your environment and configure your IdP. You will need to download the IdP’s metadata XML file.
Start your environment and configure your IdP. You will need to download the IdP's metadata XML file.
Your Assertion Consumer Service (ACS) URL must follow this format:
@@ -147,7 +147,7 @@ The following fields are expected from the IdP:
- userType (this is the name of the role the user should be assigned)
- companyName (this is filled automatically if the IdP includes an “organization” field)
- companyName (this is filled automatically if the IdP includes an "organization" field)
These values are dynamic. If the values change in the IdP, they will be updated on the next login.
@@ -171,7 +171,37 @@ curl --location 'http://localhost:8080/api/v1/saml-config' \
}'
```
## 7. Start SAML Login Flow
## 7. SAML SSO Callback Configuration
### Environment Variable Configuration
The SAML authentication flow requires proper callback URL configuration to handle post-authentication redirects. Configure the following environment variables:
#### `SAML_SSO_CALLBACK_URL`
Specifies the callback endpoint that will be invoked upon successful SAML authentication completion. This URL directs users back to the web application interface.
```env
SAML_SSO_CALLBACK_URL="${AUTH_URL}/api/auth/callback/saml"
```
#### `AUTH_URL`
Defines the base URL of the web user interface application that serves as the authentication callback destination.
```env
AUTH_URL="<WEB_UI_URL>"
```
### Configuration Notes
- The `SAML_SSO_CALLBACK_URL` dynamically references the `AUTH_URL` variable to construct the complete callback endpoint
- Ensure the `AUTH_URL` points to the correct web UI deployment (development, staging, or production)
- The callback endpoint `/api/auth/callback/saml` must be accessible and properly configured to handle SAML authentication responses
- Both environment variables are required for proper SAML SSO functionality
- Verify that the `NEXT_PUBLIC_API_BASE_URL` environment variable is properly configured to reference the correct API server base URL corresponding to your target deployment environment. This ensures proper routing of SAML callback requests to the appropriate backend services.
## 8. Start SAML Login Flow
Once everything is configured, start the SAML login process by visiting the following URL:
@@ -181,6 +211,6 @@ https://<PROXY_IP>/api/v1/accounts/saml/<CONFIGURED_DOMAIN>/login/?email=<USER_E
At the end you will get a valid access and refresh token
## 8. Notes on the initiate Endpoint
## 9. Notes on the initiate Endpoint
The initiate endpoint is not strictly required. It was created to allow extra checks or behavior modifications (like enumeration mitigation). It also simplifies UI integration with SAML, but again, it’s optional.
The initiate endpoint is not strictly required. It was created to allow extra checks or behavior modifications (like enumeration mitigation). It also simplifies UI integration with SAML, but again, it's optional.
+21 -2
View File
@@ -101,7 +101,26 @@ For Azure, Prowler App uses a service principal application to authenticate, for
---
### **Step 4.3: GCP Credentials**
To connect your GCP Project, you need to use the Application Default Credentials (ADC) returned by the `gcloud` CLI. Here’s how to set up:
For Google Cloud, first enter your `GCP Project ID` and then select the authentication method you want to use:
- **Service Account Authentication** (**Recommended**)
- **Application Default Credentials**
**Service Account Authentication** is the recommended authentication method for automated systems and machine-to-machine interactions, like Prowler. For detailed information about this, refer to the [Google Cloud documentation](https://cloud.google.com/iam/docs/service-account-overview).
<img src="../img/gcp-auth-methods.png" alt="GCP Authentication Methods" width="700"/>
#### **Step 4.3.1: Service Account Authentication**
First of all, in the same project that you selected in the previous step, you need to create a service account and then generate a key in JSON format for it. For more information about this, you can follow the next Google Cloud documentation tutorials:
- [Create a service account](https://cloud.google.com/iam/docs/creating-managing-service-accounts)
- [Generate a key for a service account](https://cloud.google.com/iam/docs/creating-managing-service-account-keys)
<img src="../img/gcp-service-account-creds.png" alt="GCP Service Account Credentials" width="700"/>
#### **Step 4.3.2: Application Default Credentials**
1. Run the following command in your terminal to authenticate with GCP:
```bash
@@ -151,7 +170,7 @@ By default, the `kubeconfig` file is located at `~/.kube/config`.
---
### **Step 4.5: M365 Credentials**
For M365, Prowler App uses a service principal application with user and password to authenticate, for more information about the requirements needed for this provider check this [section](../getting-started/requirements.md#microsoft-365). Also, the detailed steps of how to add this provider to Prowler Cloud and start using it are [here](./microsoft365/getting-started-m365.md).
For M365, Prowler App uses a service principal application (before we already asked for user and password but now those parameters are optional, they will continue working only if you don't have MFA enabled) to authenticate, for more information about the requirements needed for this provider check this [section](../getting-started/requirements.md#microsoft-365). Also, the detailed steps of how to add this provider to Prowler Cloud and start using it are [here](./microsoft365/getting-started-m365.md).
<img src="../../img/m365-credentials.png" alt="Prowler Cloud M365 Credentials" width="700"/>
+3
View File
@@ -106,6 +106,8 @@ nav:
- Getting Started: tutorials/microsoft365/getting-started-m365.md
- Authentication: tutorials/microsoft365/authentication.md
- Use of PowerShell: tutorials/microsoft365/use-of-powershell.md
- IaC:
- Getting Started: tutorials/iac/getting-started-iac.md
- Developer Guide:
- General Concepts:
- Introduction: developer-guide/introduction.md
@@ -128,6 +130,7 @@ nav:
- Unit Tests: developer-guide/unit-testing.md
- Integration Tests: developer-guide/integration-testing.md
- Debugging: developer-guide/debugging.md
- Configurable Checks: developer-guide/configurable-checks.md
- Security: security.md
- Contact Us: contact.md
- Troubleshooting: troubleshooting.md
Generated
+893 -867
View File
File diff suppressed because it is too large. Load diff
+34 -25
View File
@@ -2,18 +2,30 @@
All notable changes to the **Prowler SDK** are documented in this file.
## [v5.8.0] (Prowler UNRELEASED)
## [v5.9.0] (Prowler UNRELEASED)
### Added
- Add `storage_geo_redundant_enabled` check for Azure provider. [(#7980)](https://github.com/prowler-cloud/prowler/pull/7980)
- Add `storage_cross_tenant_replication_disabled` check for Azure provider. [(#7977)](https://github.com/prowler-cloud/prowler/pull/7977)
### Changed
### Fixed
- fix(iam): detect wildcarded ARNs in sts:AssumeRole policy resources [(#8164)](https://github.com/prowler-cloud/prowler/pull/8164)
---
## [v5.8.0] (Prowler v5.8.0)
### Added
- `storage_geo_redundant_enabled` check for Azure provider [(#7980)](https://github.com/prowler-cloud/prowler/pull/7980)
- `storage_cross_tenant_replication_disabled` check for Azure provider [(#7977)](https://github.com/prowler-cloud/prowler/pull/7977)
- CIS 1.11 compliance framework for Kubernetes [(#7790)](https://github.com/prowler-cloud/prowler/pull/7790)
- Support `HTTPS_PROXY` and `K8S_SKIP_TLS_VERIFY` in Kubernetes [(#7720)](https://github.com/prowler-cloud/prowler/pull/7720)
- Weight for Prowler ThreatScore scoring [(#7795)](https://github.com/prowler-cloud/prowler/pull/7795)
- New check `entra_users_mfa_capable` for M365 provider [(#7734)](https://github.com/prowler-cloud/prowler/pull/7734)
- New check `admincenter_organization_customer_lockbox_enabled` for M365 provider [(#7732)](https://github.com/prowler-cloud/prowler/pull/7732)
- New check `admincenter_external_calendar_sharing_disabled` for M365 provider [(#7733)](https://github.com/prowler-cloud/prowler/pull/7733)
- a level for Prowler ThreatScore in the accordion in Dashboard [(#7739)](https://github.com/prowler-cloud/prowler/pull/7739)
- `entra_users_mfa_capable` check for M365 provider [(#7734)](https://github.com/prowler-cloud/prowler/pull/7734)
- `admincenter_organization_customer_lockbox_enabled` check for M365 provider [(#7732)](https://github.com/prowler-cloud/prowler/pull/7732)
- `admincenter_external_calendar_sharing_disabled` check for M365 provider [(#7733)](https://github.com/prowler-cloud/prowler/pull/7733)
- Level for Prowler ThreatScore in the accordion in Dashboard [(#7739)](https://github.com/prowler-cloud/prowler/pull/7739)
- CIS 4.0 compliance framework for GCP [(7785)](https://github.com/prowler-cloud/prowler/pull/7785)
- `repository_has_codeowners_file` check for GitHub provider [(#7752)](https://github.com/prowler-cloud/prowler/pull/7752)
- `repository_default_branch_requires_signed_commits` check for GitHub provider [(#7777)](https://github.com/prowler-cloud/prowler/pull/7777)
@@ -31,20 +43,29 @@ All notable changes to the **Prowler SDK** are documented in this file.
- Avoid bypassing IAM check using wildcards [(#7708)](https://github.com/prowler-cloud/prowler/pull/7708)
- `storage_blob_versioning_is_enabled` new check for Azure provider [(#7927)](https://github.com/prowler-cloud/prowler/pull/7927)
- New method to authenticate in AppInsights in check `app_function_application_insights_enabled` [(#7763)](https://github.com/prowler-cloud/prowler/pull/7763)
- ISO 27001 2022 for M365 provider. [(#7985)](https://github.com/prowler-cloud/prowler/pull/7985)
- ISO 27001 2022 for M365 provider [(#7985)](https://github.com/prowler-cloud/prowler/pull/7985)
- `codebuild_project_uses_allowed_github_organizations` check for AWS provider [(#7595)](https://github.com/prowler-cloud/prowler/pull/7595)
- IaC provider [(#7852)](https://github.com/prowler-cloud/prowler/pull/7852)
- Azure Databricks service integration for Azure provider, including the `databricks_workspace_vnet_injection_enabled` check [(#8008)](https://github.com/prowler-cloud/prowler/pull/8008)
- Azure Databricks check `databricks_workspace_cmk_encryption_enabled` to ensure workspaces use customer-managed keys (CMK) for encryption at rest [(#8017)](https://github.com/prowler-cloud/prowler/pull/8017)
- Add `storage_account_default_to_entra_authorization_enabled` check for Azure provider. [(#7981)](https://github.com/prowler-cloud/prowler/pull/7981)
- `databricks_workspace_cmk_encryption_enabled` check for Azure provider [(#8017)](https://github.com/prowler-cloud/prowler/pull/8017)
- Appication auth for PowerShell in M365 provider [(#7992)](https://github.com/prowler-cloud/prowler/pull/7992)
- `storage_account_default_to_entra_authorization_enabled` check for Azure provider [(#7981)](https://github.com/prowler-cloud/prowler/pull/7981)
- Improve overview page from Prowler Dashboard [(#8118)](https://github.com/prowler-cloud/prowler/pull/8118)
- `keyvault_ensure_public_network_access_disabled` check for Azure provider. [(#8072)](https://github.com/prowler-cloud/prowler/pull/8072)
- New check `monitor_alert_service_health_exists` for Azure provider [(#8067)](https://github.com/prowler-cloud/prowler/pull/8067)
- `keyvault_ensure_public_network_access_disabled` check for Azure provider [(#8072)](https://github.com/prowler-cloud/prowler/pull/8072)
- `monitor_alert_service_health_exists` check for Azure provider [(#8067)](https://github.com/prowler-cloud/prowler/pull/8067)
- Replace `Domain.Read.All` with `Directory.Read.All` in Azure and M365 docs [(#8075)](https://github.com/prowler-cloud/prowler/pull/8075)
- Refactor IaC provider to use Checkov as Python library [(#8093)](https://github.com/prowler-cloud/prowler/pull/8093)
- New check `codebuild_project_not_publicly_accessible` for AWS provider [(#8127)](https://github.com/prowler-cloud/prowler/pull/8127)
### Fixed
- Consolidate Azure Storage file service properties to the account level, improving the accuracy of the `storage_ensure_file_shares_soft_delete_is_enabled` check [(#8087)](https://github.com/prowler-cloud/prowler/pull/8087)
- Migrate Azure VM service and managed disk logic to Pydantic models for better serialization and type safety, and update all related tests to use the new models and fix UUID handling [(#https://github.com/prowler-cloud/prowler/pull/8151)](https://github.com/prowler-cloud/prowler/pull/https://github.com/prowler-cloud/prowler/pull/8151)
- `organizations_scp_check_deny_regions` check to pass when SCP policies have no statements [(#8091)](https://github.com/prowler-cloud/prowler/pull/8091)
- Fix logic in VPC and ELBv2 checks [(#8077)](https://github.com/prowler-cloud/prowler/pull/8077)
- Retrieve correctly ECS Container insights settings [(#8097)](https://github.com/prowler-cloud/prowler/pull/8097)
- Fix correct handling for different accounts-dates in prowler dashboard compliance page [(#8108)](https://github.com/prowler-cloud/prowler/pull/8108)
- Handling of `block-project-ssh-keys` in GCP check `compute_instance_block_project_wide_ssh_keys_disabled` [(#8115)](https://github.com/prowler-cloud/prowler/pull/8115)
- Handle empty name in Azure Defender and GCP checks [(#8120)](https://github.com/prowler-cloud/prowler/pull/8120)
### Changed
- Reworked `S3.test_connection` to match the AwsProvider logic [(#8088)](https://github.com/prowler-cloud/prowler/pull/8088)
@@ -54,23 +75,11 @@ All notable changes to the **Prowler SDK** are documented in this file.
---
## [v5.7.6] (Prowler UNRELEASED)
### Fixed
- `organizations_scp_check_deny_regions` check to pass when SCP policies have no statements [(#8091)](https://github.com/prowler-cloud/prowler/pull/8091)
- Fix logic in VPC and ELBv2 checks [(#8077)](https://github.com/prowler-cloud/prowler/pull/8077)
- Retrieve correctly ECS Container insights settings [(#8097)](https://github.com/prowler-cloud/prowler/pull/8097)
- Fix correct handling for different accounts-dates in prowler dashboard compliance page [(#8108)](https://github.com/prowler-cloud/prowler/pull/8108)
- Handling of `block-project-ssh-keys` in GCP check `compute_instance_block_project_wide_ssh_keys_disabled` [(#8115)](https://github.com/prowler-cloud/prowler/pull/8115)
- Handle empty name in Azure Defender and GCP checks [(#8120)](https://github.com/prowler-cloud/prowler/pull/8120)
---
## [v5.7.5] (Prowler 5.7.5)
### Fixed
- Use unified timestamp for all requirements [(#8059)](https://github.com/prowler-cloud/prowler/pull/8059)
- Add EKS to service without subservices. [(#7959)](https://github.com/prowler-cloud/prowler/pull/7959)
- Add EKS to service without subservices [(#7959)](https://github.com/prowler-cloud/prowler/pull/7959)
- `apiserver_strong_ciphers_only` check for K8S provider [(#7952)](https://github.com/prowler-cloud/prowler/pull/7952)
- Handle `0` at the start and end of account uids in Prowler Dashboard [(#7955)](https://github.com/prowler-cloud/prowler/pull/7955)
- Typo in PCI 4.0 for K8S provider [(#7971)](https://github.com/prowler-cloud/prowler/pull/7971)
+1 -1
View File
@@ -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.8.0"
prowler_version = "5.9.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"
@@ -951,6 +951,7 @@
"aws": [
"af-south-1",
"ap-east-1",
"ap-east-2",
"ap-northeast-1",
"ap-northeast-2",
"ap-northeast-3",
@@ -1336,7 +1337,9 @@
"aws": [
"us-east-1"
],
"aws-cn": [],
"aws-cn": [
"cn-northwest-1"
],
"aws-us-gov": []
}
},
@@ -2785,6 +2788,9 @@
"regions": {
"aws": [
"af-south-1",
"ap-northeast-1",
"ap-northeast-2",
"ap-southeast-1",
"ap-southeast-2",
"ca-central-1",
"eu-central-1",
@@ -3461,6 +3467,7 @@
"aws": [
"af-south-1",
"ap-east-1",
"ap-east-2",
"ap-northeast-1",
"ap-northeast-2",
"ap-northeast-3",
@@ -3506,6 +3513,7 @@
"regions": {
"aws": [
"ap-northeast-1",
"ap-northeast-2",
"ap-northeast-3",
"eu-west-1",
"eu-west-2",
@@ -4987,6 +4995,8 @@
"ap-south-1",
"ap-southeast-1",
"ap-southeast-2",
"ap-southeast-5",
"ap-southeast-7",
"ca-central-1",
"eu-central-1",
"eu-north-1",
@@ -9901,7 +9911,10 @@
"cn-north-1",
"cn-northwest-1"
],
"aws-us-gov": []
"aws-us-gov": [
"us-gov-east-1",
"us-gov-west-1"
]
}
},
"schemas": {
@@ -10319,17 +10332,20 @@
"ap-northeast-2",
"ap-northeast-3",
"ap-south-1",
"ap-south-2",
"ap-southeast-1",
"ap-southeast-2",
"ap-southeast-3",
"ca-central-1",
"eu-central-1",
"eu-central-2",
"eu-north-1",
"eu-south-1",
"eu-west-1",
"eu-west-2",
"eu-west-3",
"il-central-1",
"me-central-1",
"me-south-1",
"sa-east-1",
"us-east-1",
@@ -10352,17 +10368,20 @@
"ap-northeast-2",
"ap-northeast-3",
"ap-south-1",
"ap-south-2",
"ap-southeast-1",
"ap-southeast-2",
"ap-southeast-3",
"ca-central-1",
"eu-central-1",
"eu-central-2",
"eu-north-1",
"eu-south-1",
"eu-west-1",
"eu-west-2",
"eu-west-3",
"il-central-1",
"me-central-1",
"me-south-1",
"sa-east-1",
"us-east-1",
@@ -0,0 +1,30 @@
{
"Provider": "aws",
"CheckID": "codebuild_project_not_publicly_accessible",
"CheckTitle": "Ensure AWS CodeBuild projects are not public",
"CheckType": [],
"ServiceName": "codebuild",
"SubServiceName": "",
"ResourceIdTemplate": "arn:aws:codebuild:region:account-id:project:project-name",
"Severity": "high",
"ResourceType": "AwsCodeBuildProject",
"Description": "Check for CodeBuild projects ensuring that the project visibility is appropriate",
"Risk": "Public CodeBuild Project ensures all build logs and artifacts are available to the public. Environment variables, source code, and other sensitive information may have been output to the build logs and artifacts. You must be careful about what information is output to the build logs.",
"RelatedUrl": "",
"Remediation": {
"Code": {
"NativeIaC": "",
"Terraform": "",
"CLI": "aws codebuild update-project --name <project-name> --project-visibility PRIVATE",
"Other": ""
},
"Recommendation": {
"Text": "Ensure that all CodeBuild projects are private to avoid fact gathering about builds from an Attacker.",
"Url": "https://docs.aws.amazon.com/codebuild/latest/userguide/public-builds.html"
}
},
"Categories": [],
"DependsOn": [],
"RelatedTo": [],
"Notes": ""
}
@@ -0,0 +1,26 @@
from typing import List
from prowler.lib.check.models import Check, Check_Report_AWS
from prowler.providers.aws.services.codebuild.codebuild_client import codebuild_client
class codebuild_project_not_publicly_accessible(Check):
def execute(self) -> List[Check_Report_AWS]:
findings = []
projects = codebuild_client.projects
for arn, project in projects.items():
report = Check_Report_AWS(self.metadata(), resource=project)
report.resource_id = project.name
report.resource_arn = arn
report.region = project.region
report.status = "FAIL"
report.status_extended = f"CodeBuild project {project.name} is public."
if project.project_visibility == "PRIVATE":
report.status = "PASS"
report.status_extended = f"CodeBuild project {project.name} is private."
findings.append(report)
return findings
@@ -121,6 +121,7 @@ class Codebuild(AWSService):
)
project.tags = project_info.get("tags", [])
project.service_role_arn = project_info.get("serviceRole", "")
project.project_visibility = project_info.get("projectVisibility", "")
except Exception as error:
logger.error(
f"{error.__class__.__name__}[{error.__traceback__.tb_lineno}]: {error}"
@@ -222,6 +223,7 @@ class Project(BaseModel):
s3_logs: Optional[s3Logs]
cloudwatch_logs: Optional[CloudWatchLogs]
tags: Optional[list]
project_visibility: Optional[str] = None
class ExportConfig(BaseModel):
@@ -5,6 +5,14 @@ from prowler.providers.aws.services.iam.iam_client import iam_client
class iam_no_custom_policy_permissive_role_assumption(Check):
def execute(self) -> Check_Report_AWS:
findings = []
def resource_has_wildcard(resource):
if isinstance(resource, str):
return "*" in resource
if isinstance(resource, list):
return any("*" in r for r in resource)
return False
for policy in iam_client.policies:
# Check only custom policies
if policy.type == "Custom":
@@ -12,6 +20,7 @@ class iam_no_custom_policy_permissive_role_assumption(Check):
report.region = iam_client.region
report.status = "PASS"
report.status_extended = f"Custom Policy {policy.name} does not allow permissive STS Role assumption."
if policy.document:
if not isinstance(policy.document["Statement"], list):
policy_statements = [policy.document["Statement"]]
@@ -19,30 +28,23 @@ class iam_no_custom_policy_permissive_role_assumption(Check):
policy_statements = policy.document["Statement"]
for statement in policy_statements:
if (
statement["Effect"] == "Allow"
statement.get("Effect") == "Allow"
and "Action" in statement
and "Resource" in statement
and "*" in statement["Resource"]
and resource_has_wildcard(statement["Resource"])
):
if isinstance(statement["Action"], list):
for action in statement["Action"]:
if (
action == "sts:AssumeRole"
or action == "sts:*"
or action == "*"
):
report.status = "FAIL"
report.status_extended = f"Custom Policy {policy.name} allows permissive STS Role assumption."
break
else:
if (
statement["Action"] == "sts:AssumeRole"
or statement["Action"] == "sts:*"
or statement["Action"] == "*"
):
actions = (
statement["Action"]
if isinstance(statement["Action"], list)
else [statement["Action"]]
)
for action in actions:
if action in ["sts:AssumeRole", "sts:*", "*"]:
report.status = "FAIL"
report.status_extended = f"Custom Policy {policy.name} allows permissive STS Role assumption."
break
break
if report.status == "FAIL":
break
findings.append(report)
@@ -15,17 +15,17 @@ class vm_ensure_using_managed_disks(Check):
using_managed_disks = (
True
if vm.storage_profile
and getattr(vm.storage_profile, "os_disk", False)
and getattr(vm.storage_profile.os_disk, "managed_disk", False)
if getattr(
getattr(getattr(vm, "storage_profile", None), "os_disk", None),
"managed_disk",
None,
)
else False
)
if using_managed_disks and getattr(
vm.storage_profile, "data_disks", False
):
if using_managed_disks and getattr(vm, "storage_profile", None):
for data_disk in vm.storage_profile.data_disks:
if not getattr(data_disk, "managed_disk", False):
if not getattr(data_disk, "managed_disk", None):
using_managed_disks = False
break
@@ -1,7 +1,9 @@
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional
from azure.mgmt.compute import ComputeManagementClient
from pydantic import BaseModel
from prowler.lib.logger import logger
from prowler.providers.azure.azure_provider import AzureProvider
@@ -30,24 +32,33 @@ class VirtualMachines(AzureService):
if storage_profile
else None
)
data_disks = []
if storage_profile and getattr(storage_profile, "data_disks", []):
data_disks = [
DataDisk(
lun=data_disk.lun,
name=data_disk.name,
managed_disk=data_disk.managed_disk,
managed_disk=ManagedDiskParameters(
id=(
getattr(
getattr(data_disk, "managed_disk", None),
"id",
None,
)
if data_disk.managed_disk
else None
)
),
)
for data_disk in getattr(storage_profile, "data_disks", [])
if data_disk
]
extensions = []
if getattr(vm, "resources", []):
extensions = [
VirtualMachineExtension(id=extension.id)
for extension in getattr(vm, "resources", [])
for extension in vm.resources
if extension
]
@@ -60,8 +71,17 @@ class VirtualMachines(AzureService):
StorageProfile(
os_disk=OSDisk(
name=getattr(os_disk, "name", None),
managed_disk=getattr(
os_disk, "managed_disk", None
operating_system_type=getattr(
os_disk, "os_type", None
),
managed_disk=ManagedDiskParameters(
id=getattr(
getattr(
os_disk, "managed_disk", None
),
"id",
None,
)
),
),
data_disks=data_disks,
@@ -130,32 +150,37 @@ class SecurityProfile:
uefi_settings: Optional[UefiSettings]
@dataclass
class OSDisk:
name: Optional[str]
managed_disk: Optional[bool]
class OperatingSystemType(Enum):
WINDOWS = "Windows"
LINUX = "Linux"
@dataclass
class DataDisk:
class ManagedDiskParameters(BaseModel):
id: str
class OSDisk(BaseModel):
name: str
operating_system_type: OperatingSystemType
managed_disk: Optional[ManagedDiskParameters]
class DataDisk(BaseModel):
lun: int
name: str
managed_disk: bool
managed_disk: Optional[ManagedDiskParameters]
@dataclass
class StorageProfile:
class StorageProfile(BaseModel):
os_disk: Optional[OSDisk]
data_disks: List[DataDisk]
@dataclass
class VirtualMachineExtension:
class VirtualMachineExtension(BaseModel):
id: str
@dataclass
class VirtualMachine:
class VirtualMachine(BaseModel):
resource_id: str
resource_name: str
location: str
@@ -164,8 +189,7 @@ class VirtualMachine:
storage_profile: Optional[StorageProfile] = None
@dataclass
class Disk:
class Disk(BaseModel):
resource_id: str
resource_name: str
vms_attached: list[str]
@@ -114,6 +114,18 @@ class M365BaseException(ProwlerException):
"message": "The provided User does not belong to the specified tenant.",
"remediation": "Check the User email domain and ensure it belongs to the specified tenant.",
},
(6027, "M365GraphConnectionError"): {
"message": "Failed to establish connection to Microsoft Graph API.",
"remediation": "Check your Microsoft Application credentials and ensure the app has proper permissions.",
},
(6028, "M365TeamsConnectionError"): {
"message": "Failed to establish connection to Microsoft Teams API.",
"remediation": "Ensure the application has proper permission granted to access Microsoft Teams.",
},
(6029, "M365ExchangeConnectionError"): {
"message": "Failed to establish connection to Exchange Online API.",
"remediation": "Ensure the application has proper permission granted to access Exchange Online.",
},
}
def __init__(self, code, file=None, original_exception=None, message=None):
@@ -324,3 +336,24 @@ class M365UserNotBelongingToTenantError(M365CredentialsError):
super().__init__(
6026, file=file, original_exception=original_exception, message=message
)
class M365GraphConnectionError(M365CredentialsError):
def __init__(self, file=None, original_exception=None, message=None):
super().__init__(
6027, file=file, original_exception=original_exception, message=message
)
class M365TeamsConnectionError(M365CredentialsError):
def __init__(self, file=None, original_exception=None, message=None):
super().__init__(
6028, file=file, original_exception=original_exception, message=message
)
class M365ExchangeConnectionError(M365CredentialsError):
def __init__(self, file=None, original_exception=None, message=None):
super().__init__(
6029, file=file, original_exception=original_exception, message=message
)
@@ -6,6 +6,9 @@ import msal
from prowler.lib.logger import logger
from prowler.lib.powershell.powershell import PowerShellSession
from prowler.providers.m365.exceptions.exceptions import (
M365ExchangeConnectionError,
M365GraphConnectionError,
M365TeamsConnectionError,
M365UserNotBelongingToTenantError,
)
from prowler.providers.m365.models import M365Credentials, M365IdentityInfo
@@ -65,21 +68,33 @@ class M365PowerShell(PowerShellSession):
The credentials are sanitized to prevent command injection and
stored securely in the PowerShell session.
"""
# User Auth (Will be deprecated in September 2025)
if credentials.user and credentials.passwd:
credentials.encrypted_passwd = self.encrypt_password(credentials.passwd)
credentials.encrypted_passwd = self.encrypt_password(credentials.passwd)
# Sanitize user and password
sanitized_user = self.sanitize(credentials.user)
sanitized_encrypted_passwd = self.sanitize(credentials.encrypted_passwd)
# Sanitize user and password
sanitized_user = self.sanitize(credentials.user)
sanitized_encrypted_passwd = self.sanitize(credentials.encrypted_passwd)
# Securely convert encrypted password to SecureString
self.execute(f'$user = "{sanitized_user}"')
self.execute(
f'$secureString = "{sanitized_encrypted_passwd}" | ConvertTo-SecureString'
)
self.execute(
"$credential = New-Object System.Management.Automation.PSCredential ($user, $secureString)"
)
# Securely convert encrypted password to SecureString
self.execute(f'$user = "{sanitized_user}"')
self.execute(
f'$secureString = "{sanitized_encrypted_passwd}" | ConvertTo-SecureString'
)
self.execute(
"$credential = New-Object System.Management.Automation.PSCredential ($user, $secureString)"
)
else:
# Application Auth
self.execute(f'$clientID = "{credentials.client_id}"')
self.execute(f'$clientSecret = "{credentials.client_secret}"')
self.execute(f'$tenantID = "{credentials.tenant_id}"')
self.execute(
'$graphtokenBody = @{ Grant_Type = "client_credentials"; Scope = "https://graph.microsoft.com/.default"; Client_Id = $clientID; Client_Secret = $clientSecret }'
)
self.execute(
'$graphToken = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$tenantID/oauth2/v2.0/token" -Method POST -Body $graphtokenBody | Select-Object -ExpandProperty Access_Token'
)
def encrypt_password(self, password: str) -> str:
"""
@@ -129,46 +144,151 @@ class M365PowerShell(PowerShellSession):
Returns:
bool: True if credentials are valid and authentication succeeds, False otherwise.
"""
self.execute(
f'$securePassword = "{credentials.encrypted_passwd}" | ConvertTo-SecureString' # encrypted password already sanitized
)
self.execute(
f'$credential = New-Object System.Management.Automation.PSCredential("{self.sanitize(credentials.user)}", $securePassword)'
)
if credentials.user and credentials.passwd:
self.execute(
f'$securePassword = "{credentials.encrypted_passwd}" | ConvertTo-SecureString' # encrypted password already sanitized
)
self.execute(
f'$credential = New-Object System.Management.Automation.PSCredential("{self.sanitize(credentials.user)}", $securePassword)'
)
# Validate user belongs to tenant
user_domain = credentials.user.split("@")[1]
if not any(
user_domain.endswith(domain)
for domain in self.tenant_identity.tenant_domains
):
raise M365UserNotBelongingToTenantError(
user_domain = credentials.user.split("@")[1]
if not any(
user_domain.endswith(domain)
for domain in self.tenant_identity.tenant_domains
):
raise M365UserNotBelongingToTenantError(
file=os.path.basename(__file__),
message=f"The user domain {user_domain} does not match any of the tenant domains: {', '.join(self.tenant_identity.tenant_domains)}",
)
app = msal.ConfidentialClientApplication(
client_id=credentials.client_id,
client_credential=credentials.client_secret,
authority=f"https://login.microsoftonline.com/{credentials.tenant_id}",
)
# Validate credentials
result = app.acquire_token_by_username_password(
username=credentials.user,
password=credentials.passwd,
scopes=["https://graph.microsoft.com/.default"],
)
if result is None:
raise Exception(
"Unexpected error: Acquiring token in behalf of user did not return a result."
)
if "access_token" not in result:
raise Exception(f"MsGraph Error {result.get('error_description')}")
return True
else:
# Test Microsoft Graph connection
try:
logger.info("Testing Microsoft Graph connection...")
self.test_graph_connection()
logger.info("Microsoft Graph connection successful")
except Exception as e:
logger.error(f"Microsoft Graph connection failed: {e}")
raise M365GraphConnectionError(
file=os.path.basename(__file__),
original_exception=e,
message="Check your Microsoft Application credentials and ensure the app has proper permissions",
)
# Test Microsoft Teams connection
try:
logger.info("Testing Microsoft Teams connection...")
self.test_teams_connection()
logger.info("Microsoft Teams connection successful")
except Exception as e:
logger.error(f"Microsoft Teams connection failed: {e}")
raise M365TeamsConnectionError(
file=os.path.basename(__file__),
original_exception=e,
message="Ensure the application has proper permission granted to access Microsoft Teams.",
)
# Test Exchange Online connection
try:
logger.info("Testing Exchange Online connection...")
self.test_exchange_connection()
logger.info("Exchange Online connection successful")
except Exception as e:
logger.error(f"Exchange Online connection failed: {e}")
raise M365ExchangeConnectionError(
file=os.path.basename(__file__),
original_exception=e,
message="Ensure the application has proper permission granted to access Exchange Online.",
)
return True
def test_graph_connection(self) -> bool:
"""Test Microsoft Graph API connection and raise exception if it fails."""
try:
if self.execute("Write-Output $graphToken") == "":
raise M365GraphConnectionError(
file=os.path.basename(__file__),
message="Microsoft Graph token is empty or invalid.",
)
return True
except Exception as e:
logger.error(f"Microsoft Graph connection failed: {e}")
raise M365GraphConnectionError(
file=os.path.basename(__file__),
message=f"The user domain {user_domain} does not match any of the tenant domains: {', '.join(self.tenant_identity.tenant_domains)}",
original_exception=e,
message=f"Failed to connect to Microsoft Graph API: {str(e)}",
)
app = msal.ConfidentialClientApplication(
client_id=credentials.client_id,
client_credential=credentials.client_secret,
authority=f"https://login.microsoftonline.com/{credentials.tenant_id}",
)
# Validate credentials
result = app.acquire_token_by_username_password(
username=credentials.user,
password=credentials.passwd,
scopes=["https://graph.microsoft.com/.default"],
)
if result is None:
raise Exception(
"Unexpected error: Acquiring token in behalf of user did not return a result."
def test_teams_connection(self) -> bool:
"""Test Microsoft Teams API connection and raise exception if it fails."""
try:
self.execute(
'$teamstokenBody = @{ Grant_Type = "client_credentials"; Scope = "48ac35b8-9aa8-4d74-927d-1f4a14a0b239/.default"; Client_Id = $clientID; Client_Secret = $clientSecret }'
)
self.execute(
'$teamsToken = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$tenantID/oauth2/v2.0/token" -Method POST -Body $teamstokenBody | Select-Object -ExpandProperty Access_Token'
)
if self.execute("Write-Output $teamsToken") == "":
raise M365TeamsConnectionError(
file=os.path.basename(__file__),
message="Microsoft Teams token is empty or invalid.",
)
return True
except Exception as e:
logger.error(f"Microsoft Teams connection failed: {e}")
raise M365TeamsConnectionError(
file=os.path.basename(__file__),
original_exception=e,
message=f"Failed to connect to Microsoft Teams API: {str(e)}",
)
if "access_token" not in result:
raise Exception(f"MsGraph Error {result.get('error_description')}")
return True
def test_exchange_connection(self) -> bool:
"""Test Exchange Online API connection and raise exception if it fails."""
try:
self.execute(
'$SecureSecret = ConvertTo-SecureString "$clientSecret" -AsPlainText -Force'
)
self.execute(
'$exchangeToken = Get-MsalToken -clientID "$clientID" -tenantID "$tenantID" -clientSecret $SecureSecret -Scopes "https://outlook.office365.com/.default"'
)
if self.execute("Write-Output $exchangeToken") == "":
raise M365ExchangeConnectionError(
file=os.path.basename(__file__),
message="Exchange Online token is empty or invalid.",
)
return True
except Exception as e:
logger.error(f"Exchange Online connection failed: {e}")
raise M365ExchangeConnectionError(
file=os.path.basename(__file__),
original_exception=e,
message=f"Failed to connect to Exchange Online API: {str(e)}",
)
def connect_microsoft_teams(self) -> dict:
"""
@@ -182,7 +302,18 @@ class M365PowerShell(PowerShellSession):
Note:
This method requires the Microsoft Teams PowerShell module to be installed.
"""
return self.execute("Connect-MicrosoftTeams -Credential $credential")
if self.execute("Write-Output $credential") != "": # User Auth
return self.execute("Connect-MicrosoftTeams -Credential $credential")
else: # Application Auth
self.execute(
'$teamstokenBody = @{ Grant_Type = "client_credentials"; Scope = "48ac35b8-9aa8-4d74-927d-1f4a14a0b239/.default"; Client_Id = $clientID; Client_Secret = $clientSecret }'
)
self.execute(
'$teamsToken = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$tenantID/oauth2/v2.0/token" -Method POST -Body $teamstokenBody | Select-Object -ExpandProperty Access_Token'
)
return self.execute(
'Connect-MicrosoftTeams -AccessTokens @("$graphToken","$teamsToken")'
)
def get_teams_settings(self) -> dict:
"""
@@ -276,7 +407,18 @@ class M365PowerShell(PowerShellSession):
Note:
This method requires the Exchange Online PowerShell module to be installed.
"""
return self.execute("Connect-ExchangeOnline -Credential $credential")
if self.execute("Write-Output $credential") != "": # User Auth
return self.execute("Connect-ExchangeOnline -Credential $credential")
else: # Application Auth
self.execute(
'$SecureSecret = ConvertTo-SecureString "$clientSecret" -AsPlainText -Force'
)
self.execute(
'$exchangeToken = Get-MsalToken -clientID "$clientID" -tenantID "$tenantID" -clientSecret $SecureSecret -Scopes "https://outlook.office365.com/.default"'
)
return self.execute(
'Connect-ExchangeOnline -AccessToken $exchangeToken.AccessToken -Organization "$tenantID"'
)
def get_audit_log_config(self) -> dict:
"""
@@ -758,25 +900,20 @@ def initialize_m365_powershell_modules():
bool: True if all modules were successfully initialized, False otherwise
"""
REQUIRED_MODULES = [
"ExchangeOnlineManagement",
"MicrosoftTeams",
]
REQUIRED_MODULES = ["ExchangeOnlineManagement", "MicrosoftTeams", "MSAL.PS"]
pwsh = PowerShellSession()
try:
for module in REQUIRED_MODULES:
try:
# Check if module is already installed
result = pwsh.execute(
f"Get-Module -ListAvailable -Name {module}", timeout=5
)
result = pwsh.execute(f"Get-Module -ListAvailable {module}", timeout=5)
# Install module if not installed
if not result:
install_result = pwsh.execute(
f'Install-Module -Name "{module}" -Force -AllowClobber -Scope CurrentUser',
timeout=30,
f'Install-Module "{module}" -Force -AllowClobber -Scope CurrentUser',
timeout=60,
)
if install_result:
logger.warning(
@@ -786,7 +923,7 @@ def initialize_m365_powershell_modules():
logger.info(f"Successfully installed module {module}")
# Import module
pwsh.execute(f'Import-Module -Name "{module}" -Force', timeout=1)
pwsh.execute(f'Import-Module "{module}" -Force', timeout=1)
except Exception as error:
logger.error(f"Failed to initialize module {module}: {str(error)}")
+32 -35
View File
@@ -43,9 +43,7 @@ from prowler.providers.m365.exceptions.exceptions import (
M365NotTenantIdButClientIdAndClientSecretError,
M365NotValidClientIdError,
M365NotValidClientSecretError,
M365NotValidPasswordError,
M365NotValidTenantIdError,
M365NotValidUserError,
M365SetUpRegionConfigError,
M365SetUpSessionError,
M365TenantIdAndClientIdNotBelongingToClientSecretError,
@@ -172,7 +170,7 @@ class M365Provider(Provider):
# Get the dict from the static credentials
m365_credentials = None
if tenant_id and client_id and client_secret and user and password:
if tenant_id and client_id and client_secret:
m365_credentials = self.validate_static_credentials(
tenant_id=tenant_id,
client_id=client_id,
@@ -204,6 +202,7 @@ class M365Provider(Provider):
# Set up PowerShell session credentials
self._credentials = self.setup_powershell(
env_auth=env_auth,
sp_env_auth=sp_env_auth,
m365_credentials=m365_credentials,
identity=self.identity,
init_modules=init_modules,
@@ -378,6 +377,7 @@ class M365Provider(Provider):
@staticmethod
def setup_powershell(
env_auth: bool = False,
sp_env_auth: bool = False,
m365_credentials: dict = {},
identity: M365IdentityInfo = None,
init_modules: bool = False,
@@ -392,12 +392,13 @@ class M365Provider(Provider):
If env_auth is True, retrieves from environment variables.
If False, returns empty credentials.
"""
logger.info("M365 provider: Setting up PowerShell session...")
credentials = None
if m365_credentials:
credentials = M365Credentials(
user=m365_credentials.get("user", ""),
passwd=m365_credentials.get("password", ""),
user=m365_credentials.get("user", None),
passwd=m365_credentials.get("password", None),
client_id=m365_credentials.get("client_id", ""),
client_secret=m365_credentials.get("client_secret", ""),
tenant_id=m365_credentials.get("tenant_id", ""),
@@ -418,6 +419,7 @@ class M365Provider(Provider):
file=os.path.basename(__file__),
message="Missing M365_USER or M365_PASSWORD environment variables required for credentials authentication.",
)
credentials = M365Credentials(
client_id=client_id,
client_secret=client_secret,
@@ -427,14 +429,25 @@ class M365Provider(Provider):
passwd=m365_password,
)
elif sp_env_auth:
client_id = getenv("AZURE_CLIENT_ID")
client_secret = getenv("AZURE_CLIENT_SECRET")
tenant_id = getenv("AZURE_TENANT_ID")
credentials = M365Credentials(
client_id=client_id,
client_secret=client_secret,
tenant_id=tenant_id,
tenant_domains=identity.tenant_domains,
)
if credentials:
if identity:
if identity and credentials.user:
identity.user = credentials.user
test_session = M365PowerShell(credentials, identity)
try:
if init_modules:
initialize_m365_powershell_modules()
if test_session.test_credentials(credentials):
if init_modules:
initialize_m365_powershell_modules()
return credentials
raise M365UserCredentialsError(
file=os.path.basename(__file__),
@@ -523,6 +536,8 @@ class M365Provider(Provider):
tenant_id=m365_credentials["tenant_id"],
client_id=m365_credentials["client_id"],
client_secret=m365_credentials["client_secret"],
user=m365_credentials["user"],
password=m365_credentials["password"],
)
return credentials
except ClientAuthenticationError as error:
@@ -688,8 +703,8 @@ class M365Provider(Provider):
tenant_id=tenant_id,
client_id=client_id,
client_secret=client_secret,
user="user",
password="password",
user=None,
password=None,
)
else:
m365_credentials = M365Provider.validate_static_credentials(
@@ -739,17 +754,13 @@ class M365Provider(Provider):
logger.info("M365 provider: Identity retrieved successfully")
# Set up PowerShell credentials
if user and password:
M365Provider.setup_powershell(
env_auth,
m365_credentials,
identity,
)
logger.info("M365 provider: Connection to PowerShell successful")
else:
logger.info(
"M365 provider: Connection to PowerShell has not been requested"
)
M365Provider.setup_powershell(
env_auth,
sp_env_auth,
m365_credentials,
identity,
)
logger.info("M365 provider: Connection to PowerShell successful")
return Connection(is_connected=True)
@@ -1030,20 +1041,6 @@ class M365Provider(Provider):
message="The provided Client Secret is not valid.",
)
# Validate the User
if not user:
raise M365NotValidUserError(
file=os.path.basename(__file__),
message="The provided User is not valid.",
)
# Validate the Password
if not password:
raise M365NotValidPasswordError(
file=os.path.basename(__file__),
message="The provided Password is not valid.",
)
try:
M365Provider.verify_client(tenant_id, client_id, client_secret)
return {
+3 -3
View File
@@ -24,9 +24,9 @@ class M365RegionConfig(BaseModel):
class M365Credentials(BaseModel):
user: str = ""
passwd: str = ""
encrypted_passwd: str = ""
user: Optional[str] = None
passwd: Optional[str] = None
encrypted_passwd: Optional[str] = None
client_id: str = ""
client_secret: str = ""
tenant_id: str = ""
@@ -260,7 +260,7 @@ class ExternalMailConfig(BaseModel):
class TransportRule(BaseModel):
name: str
scl: Optional[int]
sender_domain_is: list[str]
sender_domain_is: Optional[list[str]]
redirect_message_to: Optional[list[str]]
+1 -1
View File
@@ -68,7 +68,7 @@ maintainers = [{name = "Prowler Engineering", email = "engineering@prowler.com"}
name = "prowler"
readme = "README.md"
requires-python = ">3.9.1,<3.13"
version = "5.8.0"
version = "5.9.0"
[project.scripts]
prowler = "prowler.__main__:prowler"
@@ -0,0 +1,176 @@
from unittest import mock
from prowler.providers.aws.services.codebuild.codebuild_service import Project
AWS_REGION = "eu-west-1"
AWS_ACCOUNT_NUMBER = "123456789012"
class Test_codebuild_project_not_publicly_accessible:
def test_project_public(self):
codebuild_client = mock.MagicMock
project_name = "test-project"
project_arn = f"arn:aws:codebuild:{AWS_REGION}:{AWS_ACCOUNT_NUMBER}:project/{project_name}"
codebuild_client.projects = {
project_arn: Project(
name=project_name,
arn=project_arn,
region="eu-west-1",
project_visibility="PUBLIC",
tags=[],
)
}
with (
mock.patch(
"prowler.providers.aws.services.codebuild.codebuild_service.Codebuild",
codebuild_client,
),
mock.patch(
"prowler.providers.aws.services.codebuild.codebuild_project_not_publicly_accessible.codebuild_project_not_publicly_accessible.codebuild_client",
codebuild_client,
),
):
from prowler.providers.aws.services.codebuild.codebuild_project_not_publicly_accessible.codebuild_project_not_publicly_accessible import (
codebuild_project_not_publicly_accessible,
)
check = codebuild_project_not_publicly_accessible()
result = check.execute()
assert len(result) == 1
assert result[0].status == "FAIL"
assert (
result[0].status_extended
== f"CodeBuild project {project_name} is public."
)
assert result[0].resource_id == project_name
assert result[0].resource_arn == project_arn
assert result[0].resource_tags == []
assert result[0].region == AWS_REGION
def test_project_private(self):
codebuild_client = mock.MagicMock
project_name = "test-project"
project_arn = f"arn:aws:codebuild:{AWS_REGION}:{AWS_ACCOUNT_NUMBER}:project/{project_name}"
codebuild_client.projects = {
project_arn: Project(
name=project_name,
arn=project_arn,
region="eu-west-1",
project_visibility="PRIVATE",
tags=[],
)
}
with (
mock.patch(
"prowler.providers.aws.services.codebuild.codebuild_service.Codebuild",
codebuild_client,
),
mock.patch(
"prowler.providers.aws.services.codebuild.codebuild_project_not_publicly_accessible.codebuild_project_not_publicly_accessible.codebuild_client",
codebuild_client,
),
):
from prowler.providers.aws.services.codebuild.codebuild_project_not_publicly_accessible.codebuild_project_not_publicly_accessible import (
codebuild_project_not_publicly_accessible,
)
check = codebuild_project_not_publicly_accessible()
result = check.execute()
assert len(result) == 1
assert result[0].status == "PASS"
assert (
result[0].status_extended
== f"CodeBuild project {project_name} is private."
)
assert result[0].resource_id == project_name
assert result[0].resource_arn == project_arn
assert result[0].resource_tags == []
assert result[0].region == AWS_REGION
def test_project_no_visibility_set(self):
codebuild_client = mock.MagicMock
project_name = "test-project"
project_arn = f"arn:aws:codebuild:{AWS_REGION}:{AWS_ACCOUNT_NUMBER}:project/{project_name}"
codebuild_client.projects = {
project_arn: Project(
name=project_name,
arn=project_arn,
region="eu-west-1",
project_visibility=None,
tags=[],
)
}
with (
mock.patch(
"prowler.providers.aws.services.codebuild.codebuild_service.Codebuild",
codebuild_client,
),
mock.patch(
"prowler.providers.aws.services.codebuild.codebuild_project_not_publicly_accessible.codebuild_project_not_publicly_accessible.codebuild_client",
codebuild_client,
),
):
from prowler.providers.aws.services.codebuild.codebuild_project_not_publicly_accessible.codebuild_project_not_publicly_accessible import (
codebuild_project_not_publicly_accessible,
)
check = codebuild_project_not_publicly_accessible()
result = check.execute()
assert len(result) == 1
assert result[0].status == "FAIL"
assert (
result[0].status_extended
== f"CodeBuild project {project_name} is public."
)
assert result[0].resource_id == project_name
assert result[0].resource_arn == project_arn
assert result[0].resource_tags == []
assert result[0].region == AWS_REGION
def test_project_empty_visibility(self):
codebuild_client = mock.MagicMock
project_name = "test-project"
project_arn = f"arn:aws:codebuild:{AWS_REGION}:{AWS_ACCOUNT_NUMBER}:project/{project_name}"
codebuild_client.projects = {
project_arn: Project(
name=project_name,
arn=project_arn,
region="eu-west-1",
project_visibility="",
tags=[],
)
}
with (
mock.patch(
"prowler.providers.aws.services.codebuild.codebuild_service.Codebuild",
codebuild_client,
),
mock.patch(
"prowler.providers.aws.services.codebuild.codebuild_project_not_publicly_accessible.codebuild_project_not_publicly_accessible.codebuild_client",
codebuild_client,
),
):
from prowler.providers.aws.services.codebuild.codebuild_project_not_publicly_accessible.codebuild_project_not_publicly_accessible import (
codebuild_project_not_publicly_accessible,
)
check = codebuild_project_not_publicly_accessible()
result = check.execute()
assert len(result) == 1
assert result[0].status == "FAIL"
assert (
result[0].status_extended
== f"CodeBuild project {project_name} is public."
)
assert result[0].resource_id == project_name
assert result[0].resource_arn == project_arn
assert result[0].resource_tags == []
assert result[0].region == AWS_REGION
@@ -28,6 +28,7 @@ build_id = "test:93f838a7-cd20-48ae-90e5-c10fbbc78ca6"
last_invoked_time = datetime.now() - timedelta(days=2)
bitbucket_url = "https://bitbucket.org/example/repo.git"
secondary_bitbucket_url = "https://bitbucket.org/example/secondary-repo.git"
project_visibility = "PRIVATE"
report_group_arn = f"arn:{AWS_COMMERCIAL_PARTITION}:codebuild:{AWS_REGION_EU_WEST_1}:{AWS_ACCOUNT_NUMBER}:report-group/{project_name}"
@@ -71,6 +72,7 @@ def mock_make_api_call(self, operation_name, kwarg):
},
},
"tags": [{"key": "Name", "value": project_name}],
"projectVisibility": project_visibility,
}
]
}
@@ -152,6 +154,7 @@ class Test_Codebuild_Service:
)
assert codebuild.projects[project_arn].tags[0]["key"] == "Name"
assert codebuild.projects[project_arn].tags[0]["value"] == project_name
assert codebuild.projects[project_arn].project_visibility == project_visibility
# Asserttions related with report groups
assert len(codebuild.report_groups) == 1
assert isinstance(codebuild.report_groups, dict)
@@ -232,3 +232,179 @@ class Test_iam_no_custom_policy_permissive_role_assumption:
result[1].status_extended,
)
assert result[1].resource_id == policy_name_permissive
@mock_aws
def test_policy_resource_with_embedded_wildcard_in_arn(self):
iam_client = client("iam")
policy_name = "policy_with_wildcard_in_arn"
policy_document = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "sts:AssumeRole",
"Resource": "arn:aws:iam::*:role/eks-terraform-*",
}
],
}
arn = iam_client.create_policy(
PolicyName=policy_name, PolicyDocument=dumps(policy_document)
)["Policy"]["Arn"]
from prowler.providers.aws.services.iam.iam_service import IAM
aws_provider = set_mocked_aws_provider([AWS_REGION_US_EAST_1])
with mock.patch(
"prowler.providers.common.provider.Provider.get_global_provider",
return_value=aws_provider,
):
with mock.patch(
"prowler.providers.aws.services.iam.iam_no_custom_policy_permissive_role_assumption.iam_no_custom_policy_permissive_role_assumption.iam_client",
new=IAM(aws_provider),
):
from prowler.providers.aws.services.iam.iam_no_custom_policy_permissive_role_assumption.iam_no_custom_policy_permissive_role_assumption import (
iam_no_custom_policy_permissive_role_assumption,
)
check = iam_no_custom_policy_permissive_role_assumption()
result = check.execute()
assert result[0].status == "FAIL"
assert result[0].resource_arn == arn
assert search(
"allows permissive STS Role assumption", result[0].status_extended
)
assert result[0].resource_id == policy_name
@mock_aws
def test_policy_resource_list_containing_wildcard(self):
iam_client = client("iam")
policy_name = "policy_with_resource_list"
policy_document = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "sts:AssumeRole",
"Resource": ["arn:aws:iam::123456789012:role/SomeRole", "*"],
}
],
}
arn = iam_client.create_policy(
PolicyName=policy_name, PolicyDocument=dumps(policy_document)
)["Policy"]["Arn"]
from prowler.providers.aws.services.iam.iam_service import IAM
aws_provider = set_mocked_aws_provider([AWS_REGION_US_EAST_1])
with mock.patch(
"prowler.providers.common.provider.Provider.get_global_provider",
return_value=aws_provider,
):
with mock.patch(
"prowler.providers.aws.services.iam.iam_no_custom_policy_permissive_role_assumption.iam_no_custom_policy_permissive_role_assumption.iam_client",
new=IAM(aws_provider),
):
from prowler.providers.aws.services.iam.iam_no_custom_policy_permissive_role_assumption.iam_no_custom_policy_permissive_role_assumption import (
iam_no_custom_policy_permissive_role_assumption,
)
check = iam_no_custom_policy_permissive_role_assumption()
result = check.execute()
assert result[0].status == "FAIL"
assert result[0].resource_arn == arn
assert search(
"allows permissive STS Role assumption", result[0].status_extended
)
assert result[0].resource_id == policy_name
@mock_aws
def test_policy_resource_list_with_arn_wildcards_should_fail(self):
iam_client = client("iam")
policy_name = "policy_list_wildcard_arn"
policy_document = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "sts:AssumeRole",
"Resource": [
"arn:aws:iam::123456789012:role/eks-admin",
"arn:aws:iam::*:role/eks-*",
],
}
],
}
arn = iam_client.create_policy(
PolicyName=policy_name, PolicyDocument=dumps(policy_document)
)["Policy"]["Arn"]
from prowler.providers.aws.services.iam.iam_service import IAM
aws_provider = set_mocked_aws_provider([AWS_REGION_US_EAST_1])
with mock.patch(
"prowler.providers.common.provider.Provider.get_global_provider",
return_value=aws_provider,
):
with mock.patch(
"prowler.providers.aws.services.iam.iam_no_custom_policy_permissive_role_assumption.iam_no_custom_policy_permissive_role_assumption.iam_client",
new=IAM(aws_provider),
):
from prowler.providers.aws.services.iam.iam_no_custom_policy_permissive_role_assumption.iam_no_custom_policy_permissive_role_assumption import (
iam_no_custom_policy_permissive_role_assumption,
)
check = iam_no_custom_policy_permissive_role_assumption()
result = check.execute()
assert result[0].status == "FAIL"
assert result[0].resource_arn == arn
assert search(
"allows permissive STS Role assumption", result[0].status_extended
)
@mock_aws
def test_policy_resource_list_with_only_wildcarded_arns_should_fail(self):
iam_client = client("iam")
policy_name = "policy_list_scoped_wildcards_only"
policy_document = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "sts:AssumeRole",
"Resource": [
"arn:aws:iam::*:role/team-*",
"arn:aws:iam::*:role/dev-*",
],
}
],
}
arn = iam_client.create_policy(
PolicyName=policy_name, PolicyDocument=dumps(policy_document)
)["Policy"]["Arn"]
from prowler.providers.aws.services.iam.iam_service import IAM
aws_provider = set_mocked_aws_provider([AWS_REGION_US_EAST_1])
with mock.patch(
"prowler.providers.common.provider.Provider.get_global_provider",
return_value=aws_provider,
):
with mock.patch(
"prowler.providers.aws.services.iam.iam_no_custom_policy_permissive_role_assumption.iam_no_custom_policy_permissive_role_assumption.iam_client",
new=IAM(aws_provider),
):
from prowler.providers.aws.services.iam.iam_no_custom_policy_permissive_role_assumption.iam_no_custom_policy_permissive_role_assumption import (
iam_no_custom_policy_permissive_role_assumption,
)
check = iam_no_custom_policy_permissive_role_assumption()
result = check.execute()
assert result[0].status == "FAIL"
assert result[0].resource_arn == arn
assert search(
"allows permissive STS Role assumption", result[0].status_extended
)
@@ -54,15 +54,15 @@ class Test_vm_ensure_attached_disks_encrypted_with_cmk:
assert len(result) == 0
def test_vm_subscription_one_disk_attached_encrypt_pk(self):
disk_id = uuid4()
resource_id = uuid4()
disk_id = str(uuid4())
resource_id = str(uuid4())
vm_client = mock.MagicMock
vm_client.disks = {
AZURE_SUBSCRIPTION_ID: {
disk_id: Disk(
resource_id=resource_id,
resource_name="test-disk",
vms_attached=[uuid4()],
vms_attached=[str(uuid4())],
encryption_type="EncryptionAtRestWithPlatformKey",
location="location",
)
@@ -97,15 +97,15 @@ class Test_vm_ensure_attached_disks_encrypted_with_cmk:
)
def test_vm_subscription_one_disk_attached_encrypt_cmk(self):
disk_id = uuid4()
resource_id = uuid4()
disk_id = str(uuid4())
resource_id = str(uuid4())
vm_client = mock.MagicMock
vm_client.disks = {
AZURE_SUBSCRIPTION_ID: {
disk_id: Disk(
resource_id=resource_id,
resource_name="test-disk",
vms_attached=[uuid4()],
vms_attached=[str(uuid4())],
encryption_type="EncryptionAtRestWithCustomerKey",
location="location",
)
@@ -140,24 +140,24 @@ class Test_vm_ensure_attached_disks_encrypted_with_cmk:
)
def test_vm_subscription_two_disk_attached_encrypt_cmk_and_pk(self):
disk_id_1 = uuid4()
resource_id_1 = uuid4()
disk_id_2 = uuid4()
resource_id_2 = uuid4()
disk_id_1 = str(uuid4())
resource_id_1 = str(uuid4())
disk_id_2 = str(uuid4())
resource_id_2 = str(uuid4())
vm_client = mock.MagicMock
vm_client.disks = {
AZURE_SUBSCRIPTION_ID: {
disk_id_1: Disk(
resource_id=resource_id_1,
resource_name="test-disk",
vms_attached=[uuid4()],
vms_attached=[str(uuid4())],
encryption_type="EncryptionAtRestWithPlatformKey",
location="location",
),
disk_id_2: Disk(
resource_id=resource_id_2,
resource_name="test-disk-2",
vms_attached=[uuid4(), uuid4()],
vms_attached=[str(uuid4()), str(uuid4())],
encryption_type="EncryptionAtRestWithCustomerKey",
location="location2",
),
@@ -200,8 +200,8 @@ class Test_vm_ensure_attached_disks_encrypted_with_cmk:
)
def test_vm_unattached_disk_encrypt_cmk(self):
disk_id = uuid4()
resource_id = uuid4()
disk_id = str(uuid4())
resource_id = str(uuid4())
vm_client = mock.MagicMock
vm_client.disks = {
AZURE_SUBSCRIPTION_ID: {
@@ -209,8 +209,8 @@ class Test_vm_ensure_attached_disks_encrypted_with_cmk:
resource_id=resource_id,
resource_name="test-disk",
vms_attached=[],
location="location",
encryption_type="EncryptionAtRestWithCustomerKey",
location="location",
)
}
}
@@ -54,8 +54,8 @@ class Test_vm_ensure_unattached_disks_encrypted_with_cmk:
assert len(result) == 0
def test_vm_one_unattached_disk_encrypt_pk(self):
disk_id = uuid4()
resource_id = uuid4()
disk_id = str(uuid4())
resource_id = str(uuid4())
vm_client = mock.MagicMock
vm_client.disks = {
AZURE_SUBSCRIPTION_ID: {
@@ -97,8 +97,8 @@ class Test_vm_ensure_unattached_disks_encrypted_with_cmk:
)
def test_vm_one_unattached_disk_encrypt_cmk(self):
disk_id = uuid4()
resource_id = uuid4()
disk_id = str(uuid4())
resource_id = str(uuid4())
vm_client = mock.MagicMock
vm_client.disks = {
AZURE_SUBSCRIPTION_ID: {
@@ -140,10 +140,10 @@ class Test_vm_ensure_unattached_disks_encrypted_with_cmk:
)
def test_vm_subscription_two_unattached_disk_encrypt_cmk_and_pk(self):
disk_id_1 = uuid4()
resource_id_1 = uuid4()
disk_id_2 = uuid4()
resource_id_2 = uuid4()
disk_id_1 = str(uuid4())
resource_id_1 = str(uuid4())
disk_id_2 = str(uuid4())
resource_id_2 = str(uuid4())
vm_client = mock.MagicMock
vm_client.disks = {
AZURE_SUBSCRIPTION_ID: {
@@ -200,17 +200,17 @@ class Test_vm_ensure_unattached_disks_encrypted_with_cmk:
)
def test_vm_attached_disk_encrypt_cmk(self):
disk_id = uuid4()
resource_id = uuid4()
disk_id = str(uuid4())
resource_id = str(uuid4())
vm_client = mock.MagicMock
vm_client.disks = {
AZURE_SUBSCRIPTION_ID: {
disk_id: Disk(
resource_id=resource_id,
resource_name="test-disk",
location="location",
vms_attached=[uuid4()],
vms_attached=[str(uuid4())],
encryption_type="EncryptionAtRestWithCustomerKey",
location="location",
)
}
}
@@ -1,7 +1,15 @@
from unittest import mock
from uuid import uuid4
from prowler.providers.azure.services.vm.vm_service import VirtualMachine
from prowler.providers.azure.services.vm.vm_service import (
DataDisk,
ManagedDiskParameters,
OSDisk,
SecurityProfile,
StorageProfile,
UefiSettings,
VirtualMachine,
)
from tests.providers.azure.azure_fixtures import (
AZURE_SUBSCRIPTION_ID,
set_mocked_azure_provider,
@@ -62,18 +70,19 @@ class Test_vm_ensure_using_managed_disks:
resource_id=vm_id,
resource_name="VMTest",
location="location",
security_profile=mock.MagicMock(
security_profile=SecurityProfile(
security_type="TrustedLaunch",
uefi_settings=mock.MagicMock(
uefi_settings=UefiSettings(
secure_boot_enabled=True,
v_tpm_enabled=True,
),
),
extensions=[],
storage_profile=mock.MagicMock(
os_disk=mock.MagicMock(
create_option="FromImage",
managed_disk=mock.MagicMock(id="managed_disk_id"),
storage_profile=StorageProfile(
os_disk=OSDisk(
name="os_disk_name",
operating_system_type="Linux",
managed_disk=ManagedDiskParameters(id="managed_disk_id"),
),
data_disks=[],
),
@@ -117,17 +126,18 @@ class Test_vm_ensure_using_managed_disks:
resource_id=vm_id,
resource_name="VMTest",
location="location",
security_profile=mock.MagicMock(
security_profile=SecurityProfile(
security_type="TrustedLaunch",
uefi_settings=mock.MagicMock(
uefi_settings=UefiSettings(
secure_boot_enabled=True,
v_tpm_enabled=True,
),
),
extensions=[],
storage_profile=mock.MagicMock(
os_disk=mock.MagicMock(
create_option="FromImage",
storage_profile=StorageProfile(
os_disk=OSDisk(
name="os_disk_name",
operating_system_type="Linux",
managed_disk=None,
),
data_disks=[],
@@ -172,20 +182,23 @@ class Test_vm_ensure_using_managed_disks:
resource_id=vm_id,
resource_name="VMTest",
location="location",
security_profile=mock.MagicMock(
security_profile=SecurityProfile(
security_type="TrustedLaunch",
uefi_settings=mock.MagicMock(
uefi_settings=UefiSettings(
secure_boot_enabled=True,
v_tpm_enabled=True,
),
),
extensions=[],
storage_profile=mock.MagicMock(
os_disk=mock.MagicMock(
create_option="FromImage",
managed_disk=mock.MagicMock(id="managed_disk_id"),
storage_profile=StorageProfile(
os_disk=OSDisk(
name="os_disk_name",
operating_system_type="Linux",
managed_disk=ManagedDiskParameters(id="managed_disk_id"),
),
data_disks=[mock.MagicMock(managed_disk=None)],
data_disks=[
DataDisk(lun=0, name="data_disk_1", managed_disk=None)
],
),
)
}
@@ -1,10 +1,13 @@
from unittest import mock
from unittest.mock import patch
from azure.mgmt.compute.models import ManagedDiskParameters, OSDisk, StorageProfile
from prowler.providers.azure.services.vm.vm_service import (
Disk,
ManagedDiskParameters,
OperatingSystemType,
OSDisk,
SecurityProfile,
StorageProfile,
UefiSettings,
VirtualMachine,
VirtualMachines,
)
@@ -21,9 +24,9 @@ def mock_vm_get_virtual_machines(_):
resource_id="/subscriptions/resource_id",
resource_name="VMTest",
location="location",
security_profile=mock.MagicMock(
security_profile=SecurityProfile(
security_type="TrustedLaunch",
uefi_settings=mock.MagicMock(
uefi_settings=UefiSettings(
secure_boot_enabled=True,
v_tpm_enabled=True,
),
@@ -31,7 +34,8 @@ def mock_vm_get_virtual_machines(_):
extensions=[],
storage_profile=StorageProfile(
os_disk=OSDisk(
create_option="FromImage",
name="os_disk_name",
operating_system_type=OperatingSystemType.LINUX,
managed_disk=ManagedDiskParameters(id="managed_disk_id"),
),
data_disks=[],
@@ -49,7 +53,7 @@ def mock_vm_get_virtual_machines_with_none(_):
resource_name="VMWithNoneValues",
location="location",
security_profile=None,
extensions=None,
extensions=[],
storage_profile=None,
),
"vm_id-2": VirtualMachine(
@@ -57,10 +61,10 @@ def mock_vm_get_virtual_machines_with_none(_):
resource_name="VMWithPartialNone",
location="location",
security_profile=None,
extensions=None,
extensions=[],
storage_profile=StorageProfile(
os_disk=None,
data_disks=None,
data_disks=[],
),
),
}
@@ -180,5 +184,5 @@ class Test_VirtualMachines_NoneCases:
virtual_machines = VirtualMachines(set_mocked_azure_provider())
vm_2 = virtual_machines.virtual_machines[AZURE_SUBSCRIPTION_ID]["vm_id-2"]
assert vm_2.storage_profile.os_disk is None
assert vm_2.storage_profile.data_disks is None
assert vm_2.storage_profile.data_disks == []
assert vm_2.resource_name == "VMWithPartialNone"
@@ -1,6 +1,14 @@
from unittest import mock
from uuid import uuid4
from prowler.providers.azure.services.vm.vm_service import (
ManagedDiskParameters,
OSDisk,
SecurityProfile,
StorageProfile,
UefiSettings,
VirtualMachine,
)
from tests.providers.azure.azure_fixtures import (
AZURE_SUBSCRIPTION_ID,
set_mocked_azure_provider,
@@ -63,7 +71,6 @@ class Test_vm_trusted_launch_enabled:
new=vm_client,
),
):
from prowler.providers.azure.services.vm.vm_service import VirtualMachine
from prowler.providers.azure.services.vm.vm_trusted_launch_enabled.vm_trusted_launch_enabled import (
vm_trusted_launch_enabled,
)
@@ -74,18 +81,21 @@ class Test_vm_trusted_launch_enabled:
resource_id=vm_id,
resource_name="VMTest",
location="location",
security_profile=mock.MagicMock(
security_profile=SecurityProfile(
security_type="TrustedLaunch",
uefi_settings=mock.MagicMock(
uefi_settings=UefiSettings(
secure_boot_enabled=True,
v_tpm_enabled=True,
),
),
extensions=[],
storage_profile=mock.MagicMock(
os_disk=mock.MagicMock(
create_option="FromImage",
managed_disk=mock.MagicMock(id="managed_disk_id"),
storage_profile=StorageProfile(
os_disk=OSDisk(
name="os_disk_name",
operating_system_type="Linux",
managed_disk=ManagedDiskParameters(
id="managed_disk_id"
),
),
data_disks=[],
),
@@ -117,7 +127,6 @@ class Test_vm_trusted_launch_enabled:
new=vm_client,
),
):
from prowler.providers.azure.services.vm.vm_service import VirtualMachine
from prowler.providers.azure.services.vm.vm_trusted_launch_enabled.vm_trusted_launch_enabled import (
vm_trusted_launch_enabled,
)
@@ -128,18 +137,21 @@ class Test_vm_trusted_launch_enabled:
resource_id=vm_id,
resource_name="VMTest",
location="location",
security_profile=mock.MagicMock(
security_profile=SecurityProfile(
security_type="TrustedLaunch",
uefi_settings=mock.MagicMock(
uefi_settings=UefiSettings(
secure_boot_enabled=False,
v_tpm_enabled=False,
),
),
extensions=[],
storage_profile=mock.MagicMock(
os_disk=mock.MagicMock(
create_option="FromImage",
managed_disk=mock.MagicMock(id="managed_disk_id"),
storage_profile=StorageProfile(
os_disk=OSDisk(
name="os_disk_name",
operating_system_type="Linux",
managed_disk=ManagedDiskParameters(
id="managed_disk_id"
),
),
data_disks=[],
),
@@ -172,7 +184,6 @@ class Test_vm_trusted_launch_enabled:
new=vm_client,
),
):
from prowler.providers.azure.services.vm.vm_service import VirtualMachine
from prowler.providers.azure.services.vm.vm_trusted_launch_enabled.vm_trusted_launch_enabled import (
vm_trusted_launch_enabled,
)
@@ -185,10 +196,13 @@ class Test_vm_trusted_launch_enabled:
location="location",
security_profile=None,
extensions=[],
storage_profile=mock.MagicMock(
os_disk=mock.MagicMock(
create_option="FromImage",
managed_disk=mock.MagicMock(id="managed_disk_id"),
storage_profile=StorageProfile(
os_disk=OSDisk(
name="os_disk_name",
operating_system_type="Linux",
managed_disk=ManagedDiskParameters(
id="managed_disk_id"
),
),
data_disks=[],
),
@@ -4,6 +4,9 @@ import pytest
from prowler.lib.powershell.powershell import PowerShellSession
from prowler.providers.m365.exceptions.exceptions import (
M365ExchangeConnectionError,
M365GraphConnectionError,
M365TeamsConnectionError,
M365UserNotBelongingToTenantError,
)
from prowler.providers.m365.lib.powershell.m365_powershell import M365PowerShell
@@ -97,7 +100,7 @@ class Testm365PowerShell:
session.init_credential(credentials)
# Verify encrypt_password was called
session.encrypt_password.assert_called_once_with(credentials.passwd)
session.encrypt_password.assert_any_call(credentials.passwd)
# Verify execute was called with the correct commands
session.execute.assert_any_call(f'$user = "{credentials.user}"')
@@ -167,6 +170,37 @@ class Testm365PowerShell:
)
session.close()
@patch("subprocess.Popen")
def test_test_credentials_application_auth(self, mock_popen):
mock_process = MagicMock()
mock_popen.return_value = mock_process
with patch(
"prowler.providers.m365.lib.powershell.m365_powershell.M365Credentials",
autospec=True,
) as mock_creds:
credentials = mock_creds.return_value
credentials.user = ""
credentials.passwd = ""
credentials.encrypted_passwd = ""
credentials.client_id = "test_client_id"
credentials.client_secret = "test_client_secret"
credentials.tenant_id = "test_tenant_id"
identity = M365IdentityInfo(
identity_id="test_id",
identity_type="Application",
tenant_id="test_tenant",
tenant_domain="contoso.onmicrosoft.com",
tenant_domains=["contoso.onmicrosoft.com"],
location="test_location",
)
session = M365PowerShell(credentials, identity)
session.execute = MagicMock(return_value="sometoken")
result = session.test_credentials(credentials)
assert result is True
session.execute.assert_any_call("Write-Output $graphToken")
session.close()
@patch("subprocess.Popen")
@patch("msal.ConfidentialClientApplication")
def test_test_credentials_user_not_belonging_to_tenant(self, mock_msal, mock_popen):
@@ -514,12 +548,13 @@ class Testm365PowerShell:
# Verify successful initialization
assert result is True
# Verify that execute was called for each module
assert mock_execute_obj.call_count == 6 # 2 modules * 3 commands each
assert mock_execute_obj.call_count == 9 # 3 modules * 3 commands each
# Verify success messages were logged
mock_info.assert_any_call(
"Successfully installed module ExchangeOnlineManagement"
)
mock_info.assert_any_call("Successfully installed module MicrosoftTeams")
mock_info.assert_any_call("Successfully installed module MSAL.PS")
@patch("subprocess.Popen")
def test_initialize_m365_powershell_modules_failure(self, mock_popen):
@@ -582,11 +617,12 @@ class Testm365PowerShell:
main()
# Verify all info messages were logged in the correct order
assert mock_info.call_count == 3
assert mock_info.call_count == 4
mock_info.assert_has_calls(
[
call("Successfully installed module ExchangeOnlineManagement"),
call("Successfully installed module MicrosoftTeams"),
call("Successfully installed module MSAL.PS"),
call("M365 PowerShell modules initialized successfully"),
]
)
@@ -629,6 +665,260 @@ class Testm365PowerShell:
# Verify no info messages were logged
mock_info.assert_not_called()
@patch("subprocess.Popen")
def test_test_graph_connection_success(self, mock_popen):
"""Test test_graph_connection when token is valid"""
mock_process = MagicMock()
mock_popen.return_value = mock_process
credentials = M365Credentials(user="test@example.com", passwd="test_password")
identity = M365IdentityInfo(
identity_id="test_id",
identity_type="Application",
tenant_id="test_tenant",
tenant_domain="example.com",
tenant_domains=["example.com"],
location="test_location",
)
session = M365PowerShell(credentials, identity)
# Mock execute to return a valid token
session.execute = MagicMock(return_value="valid_token")
result = session.test_graph_connection()
assert result is True
session.execute.assert_called_once_with("Write-Output $graphToken")
session.close()
@patch("subprocess.Popen")
def test_test_graph_connection_empty_token(self, mock_popen):
"""Test test_graph_connection when token is empty"""
mock_process = MagicMock()
mock_popen.return_value = mock_process
credentials = M365Credentials(user="test@example.com", passwd="test_password")
identity = M365IdentityInfo(
identity_id="test_id",
identity_type="Application",
tenant_id="test_tenant",
tenant_domain="example.com",
tenant_domains=["example.com"],
location="test_location",
)
session = M365PowerShell(credentials, identity)
# Mock execute to return empty token
session.execute = MagicMock(return_value="")
with pytest.raises(M365GraphConnectionError) as exc_info:
session.test_graph_connection()
assert "Microsoft Graph token is empty or invalid" in str(exc_info.value)
session.execute.assert_called_once_with("Write-Output $graphToken")
session.close()
@patch("subprocess.Popen")
def test_test_graph_connection_exception(self, mock_popen):
"""Test test_graph_connection when an exception occurs"""
mock_process = MagicMock()
mock_popen.return_value = mock_process
credentials = M365Credentials(user="test@example.com", passwd="test_password")
identity = M365IdentityInfo(
identity_id="test_id",
identity_type="Application",
tenant_id="test_tenant",
tenant_domain="example.com",
tenant_domains=["example.com"],
location="test_location",
)
session = M365PowerShell(credentials, identity)
# Mock execute to raise an exception
session.execute = MagicMock(side_effect=Exception("PowerShell error"))
with pytest.raises(M365GraphConnectionError) as exc_info:
session.test_graph_connection()
assert "Failed to connect to Microsoft Graph API: PowerShell error" in str(
exc_info.value
)
session.close()
@patch("subprocess.Popen")
def test_test_teams_connection_success(self, mock_popen):
"""Test test_teams_connection when token is valid"""
mock_process = MagicMock()
mock_popen.return_value = mock_process
credentials = M365Credentials(user="test@example.com", passwd="test_password")
identity = M365IdentityInfo(
identity_id="test_id",
identity_type="Application",
tenant_id="test_tenant",
tenant_domain="example.com",
tenant_domains=["example.com"],
location="test_location",
)
session = M365PowerShell(credentials, identity)
# Mock execute to return valid responses
def mock_execute(command, *args, **kwargs):
if "Write-Output $teamsToken" in command:
return "valid_teams_token"
return None
session.execute = MagicMock(side_effect=mock_execute)
result = session.test_teams_connection()
assert result is True
# Verify all expected PowerShell commands were called
assert session.execute.call_count == 3
session.close()
@patch("subprocess.Popen")
def test_test_teams_connection_empty_token(self, mock_popen):
"""Test test_teams_connection when token is empty"""
mock_process = MagicMock()
mock_popen.return_value = mock_process
credentials = M365Credentials(user="test@example.com", passwd="test_password")
identity = M365IdentityInfo(
identity_id="test_id",
identity_type="Application",
tenant_id="test_tenant",
tenant_domain="example.com",
tenant_domains=["example.com"],
location="test_location",
)
session = M365PowerShell(credentials, identity)
# Mock execute to return empty token when checking
def mock_execute(command, *args, **kwargs):
if "Write-Output $teamsToken" in command:
return ""
return None
session.execute = MagicMock(side_effect=mock_execute)
with pytest.raises(M365TeamsConnectionError) as exc_info:
session.test_teams_connection()
assert "Microsoft Teams token is empty or invalid" in str(exc_info.value)
session.close()
@patch("subprocess.Popen")
def test_test_teams_connection_exception(self, mock_popen):
"""Test test_teams_connection when an exception occurs"""
mock_process = MagicMock()
mock_popen.return_value = mock_process
credentials = M365Credentials(user="test@example.com", passwd="test_password")
identity = M365IdentityInfo(
identity_id="test_id",
identity_type="Application",
tenant_id="test_tenant",
tenant_domain="example.com",
tenant_domains=["example.com"],
location="test_location",
)
session = M365PowerShell(credentials, identity)
# Mock execute to raise an exception
session.execute = MagicMock(side_effect=Exception("Teams API error"))
with pytest.raises(M365TeamsConnectionError) as exc_info:
session.test_teams_connection()
assert "Failed to connect to Microsoft Teams API: Teams API error" in str(
exc_info.value
)
session.close()
@patch("subprocess.Popen")
def test_test_exchange_connection_success(self, mock_popen):
"""Test test_exchange_connection when token is valid"""
mock_process = MagicMock()
mock_popen.return_value = mock_process
credentials = M365Credentials(user="test@example.com", passwd="test_password")
identity = M365IdentityInfo(
identity_id="test_id",
identity_type="Application",
tenant_id="test_tenant",
tenant_domain="example.com",
tenant_domains=["example.com"],
location="test_location",
)
session = M365PowerShell(credentials, identity)
# Mock execute to return valid responses
def mock_execute(command, *args, **kwargs):
if "Write-Output $exchangeToken" in command:
return "valid_exchange_token"
return None
session.execute = MagicMock(side_effect=mock_execute)
result = session.test_exchange_connection()
assert result is True
# Verify all expected PowerShell commands were called
assert session.execute.call_count == 3
session.close()
@patch("subprocess.Popen")
def test_test_exchange_connection_empty_token(self, mock_popen):
"""Test test_exchange_connection when token is empty"""
mock_process = MagicMock()
mock_popen.return_value = mock_process
credentials = M365Credentials(user="test@example.com", passwd="test_password")
identity = M365IdentityInfo(
identity_id="test_id",
identity_type="Application",
tenant_id="test_tenant",
tenant_domain="example.com",
tenant_domains=["example.com"],
location="test_location",
)
session = M365PowerShell(credentials, identity)
# Mock execute to return empty token when checking
def mock_execute(command, *args, **kwargs):
if "Write-Output $exchangeToken" in command:
return ""
return None
session.execute = MagicMock(side_effect=mock_execute)
with pytest.raises(M365ExchangeConnectionError) as exc_info:
session.test_exchange_connection()
assert "Exchange Online token is empty or invalid" in str(exc_info.value)
session.close()
@patch("subprocess.Popen")
def test_test_exchange_connection_exception(self, mock_popen):
"""Test test_exchange_connection when an exception occurs"""
mock_process = MagicMock()
mock_popen.return_value = mock_process
credentials = M365Credentials(user="test@example.com", passwd="test_password")
identity = M365IdentityInfo(
identity_id="test_id",
identity_type="Application",
tenant_id="test_tenant",
tenant_domain="example.com",
tenant_domains=["example.com"],
location="test_location",
)
session = M365PowerShell(credentials, identity)
# Mock execute to raise an exception
session.execute = MagicMock(side_effect=Exception("Exchange API error"))
with pytest.raises(M365ExchangeConnectionError) as exc_info:
session.test_exchange_connection()
assert "Failed to connect to Exchange Online API: Exchange API error" in str(
exc_info.value
)
session.close()
@patch("subprocess.Popen")
def test_encrypt_password(self, mock_popen):
credentials = M365Credentials(user="test@example.com", passwd="test_password")
+10 -43
View File
@@ -76,6 +76,16 @@ class TestM365Provider:
location=LOCATION,
),
),
patch(
"prowler.providers.m365.m365_provider.M365Provider.setup_powershell",
return_value=M365Credentials(
client_id=CLIENT_ID,
tenant_id=TENANT_ID,
client_secret=CLIENT_SECRET,
user="",
passwd="",
),
),
):
m365_provider = M365Provider(
sp_env_auth=True,
@@ -490,27 +500,6 @@ class TestM365Provider:
assert result.user == credentials_dict["user"]
assert result.passwd == credentials_dict["password"]
def test_setup_powershell_invalid_env_credentials(self):
credentials = None
with patch(
"prowler.providers.m365.lib.powershell.m365_powershell.M365PowerShell"
) as mock_powershell:
mock_session = MagicMock()
mock_session.test_credentials.return_value = False
mock_powershell.return_value = mock_session
with pytest.raises(M365MissingEnvironmentCredentialsError) as exc_info:
M365Provider.setup_powershell(
env_auth=True, m365_credentials=credentials
)
assert (
"Missing M365_USER or M365_PASSWORD environment variables required for credentials authentication"
in str(exc_info.value)
)
mock_session.test_credentials.assert_not_called()
def test_test_connection_user_not_belonging_to_tenant(
self,
):
@@ -572,28 +561,6 @@ class TestM365Provider:
)
assert "The provided Client Secret is not valid." in str(exception.value)
def test_validate_static_credentials_missing_user(self):
with pytest.raises(M365NotValidUserError) as exception:
M365Provider.validate_static_credentials(
tenant_id="12345678-1234-5678-1234-567812345678",
client_id="12345678-1234-5678-1234-567812345678",
client_secret="test_secret",
user="",
password="test_password",
)
assert "The provided User is not valid." in str(exception.value)
def test_validate_static_credentials_missing_password(self):
with pytest.raises(M365NotValidPasswordError) as exception:
M365Provider.validate_static_credentials(
tenant_id="12345678-1234-5678-1234-567812345678",
client_id="12345678-1234-5678-1234-567812345678",
client_secret="test_secret",
user="test@example.com",
password="",
)
assert "The provided Password is not valid." in str(exception.value)
def test_validate_arguments_missing_env_credentials(self):
with pytest.raises(M365MissingEnvironmentCredentialsError) as exception:
M365Provider.validate_arguments(
+15 -4
View File
@@ -2,7 +2,15 @@
All notable changes to the **Prowler UI** are documented in this file.
## [v1.8.0] (Prowler v5.8.0) – Not released
## [v1.9.0] (Prowler v5.9.0) – UNRELEASED
### 🚀 Added
### 🔄 Changed
### 🐞 Fixed
---
## [v1.8.0] (Prowler v5.8.0)
### 🚀 Added
@@ -15,13 +23,13 @@ All notable changes to the **Prowler UI** are documented in this file.
- Compliance detail view: CIS [(#7913)](https://github.com/prowler-cloud/prowler/pull/7913)
- Compliance detail view: AWS Well-Architected Framework [(#7925)](https://github.com/prowler-cloud/prowler/pull/7925)
- Compliance detail view: KISA [(#7965)](https://github.com/prowler-cloud/prowler/pull/7965)
- Compliance detail view: ProwlerThreatScore [(#7966)](https://github.com/prowler-cloud/prowler/pull/7966)
- Compliance detail view: ProwlerThreatScore [(#7979)](https://github.com/prowler-cloud/prowler/pull/7979)
- Compliance detail view: Generic (rest of the compliances) [(#7990)](https://github.com/prowler-cloud/prowler/pull/7990)
- Compliance detail view: MITRE ATTACK [(#8002)](https://github.com/prowler-cloud/prowler/pull/8002)
- Improve `Scan ID` filter by adding more context and enhancing the UI/UX [(#7979)](https://github.com/prowler-cloud/prowler/pull/7979)
- Improve `Scan ID` filter by adding more context and enhancing the UI/UX [(#8046)](https://github.com/prowler-cloud/prowler/pull/8046)
- Lighthouse chat interface [(#7878)](https://github.com/prowler-cloud/prowler/pull/7878)
- Google Tag Manager integration [(#8058)](https://github.com/prowler-cloud/prowler/pull/8058)
- SAML login integration [(#8094)](https://github.com/prowler-cloud/prowler/pull/8094)
<!-- - SAML login integration [(#8094)](https://github.com/prowler-cloud/prowler/pull/8094) -->
### 🔄 Changed
@@ -29,8 +37,11 @@ All notable changes to the **Prowler UI** are documented in this file.
- Aligned Next.js version to `v14.2.29` across Prowler and Cloud environments for consistency and improved maintainability [(#7962)](https://github.com/prowler-cloud/prowler/pull/7962)
- Refactor credentials forms with reusable components and error handling [(#7988)](https://github.com/prowler-cloud/prowler/pull/7988)
- Updated the provider details section in Scan and Findings detail pages [(#7968)](https://github.com/prowler-cloud/prowler/pull/7968)
- Make user and password fields optional but mutually required for M365 cloud provider [(#8044)](https://github.com/prowler-cloud/prowler/pull/8044)
- Improve filter behaviour and relationships between filters in findings page [(#8046)](https://github.com/prowler-cloud/prowler/pull/8046)
- Set filters panel to be always open by default [(#8085)](https://github.com/prowler-cloud/prowler/pull/8085)
- Updated "Sign in"/"Sign up" capitalization for consistency [(#8136)](https://github.com/prowler-cloud/prowler/pull/8136)
- Duplicate API base URL as an env var to make it accessible in client components [(#8131)](https://github.com/prowler-cloud/prowler/pull/8131)
### 🐞 Fixed
+2
View File
@@ -30,6 +30,8 @@ ARG NEXT_PUBLIC_PROWLER_RELEASE_VERSION
ENV NEXT_PUBLIC_PROWLER_RELEASE_VERSION=${NEXT_PUBLIC_PROWLER_RELEASE_VERSION}
ARG NEXT_PUBLIC_GOOGLE_TAG_MANAGER_ID
ENV NEXT_PUBLIC_GOOGLE_TAG_MANAGER_ID=${NEXT_PUBLIC_GOOGLE_TAG_MANAGER_ID}
ARG NEXT_PUBLIC_API_BASE_URL
ENV NEXT_PUBLIC_API_BASE_URL=${NEXT_PUBLIC_API_BASE_URL}
RUN \
if [ -f package-lock.json ]; then npm run build; \
+34 -12
View File
@@ -1,20 +1,9 @@
"use server";
import { revalidatePath } from "next/cache";
import { z } from "zod";
import { apiBaseUrl, getAuthHeaders, parseStringify } from "@/lib/helper";
const samlConfigFormSchema = z.object({
email_domain: z
.string()
.trim()
.min(1, { message: "Email domain is required" }),
metadata_xml: z
.string()
.trim()
.min(1, { message: "Metadata XML is required" }),
});
import { samlConfigFormSchema } from "@/types/formSchemas";
export const createSamlConfig = async (_prevState: any, formData: FormData) => {
const headers = await getAuthHeaders({ contentType: true });
@@ -156,6 +145,39 @@ export const getSamlConfig = async () => {
}
};
export const deleteSamlConfig = async (id: string) => {
const headers = await getAuthHeaders({ contentType: true });
try {
const url = new URL(`${apiBaseUrl}/saml-config/${id}`);
const response = await fetch(url.toString(), {
method: "DELETE",
headers,
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(
errorData.errors?.[0]?.detail ||
`Failed to delete SAML config: ${response.statusText}`,
);
}
revalidatePath("/integrations");
return { success: "SAML configuration deleted successfully!" };
} catch (error) {
console.error("Error deleting SAML config:", error);
return {
errors: {
general:
error instanceof Error
? error.message
: "Error deleting SAML configuration. Please try again.",
},
};
}
};
export const initiateSamlAuth = async (email: string) => {
try {
const response = await fetch(`${apiBaseUrl}/auth/saml/initiate/`, {
+8
View File
@@ -16,6 +16,8 @@ export const getScans = async ({
sort = "",
filters = {},
pageSize = 10,
fields = {},
include = "",
}) => {
const headers = await getAuthHeaders({ contentType: false });
@@ -27,6 +29,12 @@ export const getScans = async ({
if (pageSize) url.searchParams.append("page[size]", pageSize.toString());
if (query) url.searchParams.append("filter[search]", query);
if (sort) url.searchParams.append("sort", sort);
if (include) url.searchParams.append("include", include);
// Handle fields parameters
Object.entries(fields).forEach(([key, value]) => {
url.searchParams.append(`fields[${key}]`, String(value));
});
// Handle multiple filters
Object.entries(filters).forEach(([key, value]) => {
@@ -115,7 +115,9 @@ export default async function ComplianceDetail({
>
{selectedScanId && selectedScan && (
<div className="flex max-w-[328px] flex-col items-start">
<ComplianceScanInfo scan={selectedScan} />
<div className="rounded-lg bg-gray-50 p-2 dark:bg-gray-800">
<ComplianceScanInfo scan={selectedScan} />
</div>
<Spacer y={8} />
</div>
)}
+27 -21
View File
@@ -3,7 +3,6 @@ import { Suspense } from "react";
import { getCompliancesOverview } from "@/actions/compliances";
import { getComplianceOverviewMetadataInfo } from "@/actions/compliances";
import { getProvider } from "@/actions/providers";
import { getScans } from "@/actions/scans";
import {
ComplianceCard,
@@ -36,34 +35,41 @@ export default async function Compliance({
"filter[state]": "completed",
},
pageSize: 50,
fields: {
scans: "name,completed_at,provider",
},
include: "provider",
});
if (!scansData?.data) {
return <NoScansAvailable />;
}
// Expand scans with provider information - only include scans with valid provider
const expandedScansData: ExpandedScanData[] = await Promise.all(
scansData.data
.filter((scan: ScanProps) => scan.relationships?.provider?.data?.id)
.map(async (scan: ScanProps) => {
const providerId = scan.relationships!.provider!.data!.id;
// Process scans with provider information from included data
const expandedScansData: ExpandedScanData[] = scansData.data
.filter((scan: ScanProps) => scan.relationships?.provider?.data?.id)
.map((scan: ScanProps) => {
const providerId = scan.relationships!.provider!.data!.id;
const formData = new FormData();
formData.append("id", providerId);
// Find the provider data in the included array
const providerData = scansData.included?.find(
(item: any) => item.type === "providers" && item.id === providerId,
);
const providerData = await getProvider(formData);
if (!providerData) {
return null;
}
return {
...scan,
providerInfo: {
provider: providerData.data.attributes.provider,
uid: providerData.data.attributes.uid,
alias: providerData.data.attributes.alias,
},
};
}),
);
return {
...scan,
providerInfo: {
provider: providerData.attributes.provider,
uid: providerData.attributes.uid,
alias: providerData.attributes.alias,
},
};
})
.filter(Boolean) as ExpandedScanData[];
const selectedScanId =
searchParams.scanId || expandedScansData[0]?.id || null;
@@ -140,7 +146,7 @@ const SSRComplianceGrid = async ({
query,
});
const type = compliancesData?.data?.[0]?.type;
const type = compliancesData?.data?.type;
// Check if the response contains no data
if (
+7 -8
View File
@@ -1,10 +1,10 @@
import React, { Suspense } from "react";
import { getSamlConfig } from "@/actions/integrations/saml";
// import { getSamlConfig } from "@/actions/integrations/saml";
import { getAllTenants } from "@/actions/users/tenants";
import { getUserInfo } from "@/actions/users/users";
import { getUserMemberships } from "@/actions/users/users";
import { SamlIntegrationCard } from "@/components/integrations/saml-integration-card";
// import { SamlIntegrationCard } from "@/components/integrations/saml-integration-card";
import { ContentLayout } from "@/components/ui";
import { UserBasicInfoCard } from "@/components/users/profile";
import { MembershipsCard } from "@/components/users/profile/memberships-card";
@@ -24,7 +24,7 @@ export default async function Profile() {
}
const SSRDataUser = async () => {
const samlConfig = await getSamlConfig();
// const samlConfig = await getSamlConfig();
const userProfile = await getUserInfo();
if (!userProfile?.data) {
return null;
@@ -84,11 +84,10 @@ const SSRDataUser = async () => {
/>
</div>
</div>
<div className="w-full pr-0 lg:w-2/3 xl:w-1/2 xl:pr-3">
{samlConfig.data?.length > 0 && (
<SamlIntegrationCard id={samlConfig.data[0]?.id} />
)}
</div>
{/* TODO after v5.8: Add SAML SSO back in */}
{/* <div className="w-full pr-0 lg:w-2/3 xl:w-1/2 xl:pr-3">
<SamlIntegrationCard samlConfig={samlConfig?.data?.[0]} />
</div> */}
</div>
);
};
+30 -25
View File
@@ -1,7 +1,7 @@
import { Spacer } from "@nextui-org/react";
import { Suspense } from "react";
import { getProvider, getProviders } from "@/actions/providers";
import { getProviders } from "@/actions/providers";
import { getScans, getScansByState } from "@/actions/scans";
import {
AutoRefresh,
@@ -45,13 +45,9 @@ export default async function Scans({
connected: provider.attributes.connection.connected,
})) || [];
const providersCountConnected = await getProviders({
filters: { "filter[connected]": true },
pageSize: 50,
});
const thereIsNoProviders = !providersCountConnected?.data;
const thereIsNoProviders = !providersData?.data;
const thereIsNoProvidersConnected = providersCountConnected?.data?.every(
const thereIsNoProvidersConnected = providersData?.data?.every(
(provider: ProviderProps) => !provider.attributes.connection.connected,
);
@@ -123,34 +119,43 @@ const SSRDataTableScans = async ({
// Extract query from filters
const query = (filters["filter[search]"] as string) || "";
// Fetch scans data
const scansData = await getScans({ query, page, sort, filters, pageSize });
// Fetch scans data with provider information included
const scansData = await getScans({
query,
page,
sort,
filters,
pageSize,
include: "provider",
});
// Handle expanded scans data
const expandedScansData = await Promise.all(
scansData?.data?.map(async (scan: any) => {
// Process scans with provider information from included data
const expandedScansData =
scansData?.data?.map((scan: any) => {
const providerId = scan.relationships?.provider?.data?.id;
if (!providerId) {
return { ...scan, providerInfo: null };
}
const formData = new FormData();
formData.append("id", providerId);
// Find the provider data in the included array
const providerData = scansData.included?.find(
(item: any) => item.type === "providers" && item.id === providerId,
);
const providerData = await getProvider(formData);
if (providerData?.data) {
const { provider, uid, alias } = providerData.data.attributes;
return {
...scan,
providerInfo: { provider, uid, alias },
};
if (!providerData) {
return { ...scan, providerInfo: null };
}
return { ...scan, providerInfo: null };
}) || [],
);
return {
...scan,
providerInfo: {
provider: providerData.attributes.provider,
uid: providerData.attributes.uid,
alias: providerData.attributes.alias,
},
};
}) || [];
return (
<DataTable
+11 -10
View File
@@ -176,9 +176,9 @@ export const AuthForm = ({
<p className="pb-2 text-xl font-medium">
{type === "sign-in"
? isSamlMode
? "Sign In with SAML SSO"
: "Sign In"
: "Sign Up"}
? "Sign in with SAML SSO"
: "Sign in"
: "Sign up"}
</p>
<ThemeSwitch aria-label="Toggle theme" />
</div>
@@ -218,7 +218,7 @@ export const AuthForm = ({
isInvalid={!!form.formState.errors.email}
showFormMessage={type !== "sign-in"}
/>
{!isSamlMode && type === "sign-in" && (
{!isSamlMode && (
<CustomInput
control={form.control}
name="password"
@@ -300,7 +300,7 @@ export const AuthForm = ({
)}
<CustomButton
type="submit"
ariaLabel={type === "sign-in" ? "Log In" : "Sign Up"}
ariaLabel={type === "sign-in" ? "Log in" : "Sign up"}
ariaDisabled={isLoading}
className="w-full"
variant="solid"
@@ -313,7 +313,7 @@ export const AuthForm = ({
{isLoading ? (
<span>Loading</span>
) : (
<span>{type === "sign-in" ? "Log In" : "Sign Up"}</span>
<span>{type === "sign-in" ? "Log in" : "Sign up"}</span>
)}
</CustomButton>
</form>
@@ -401,7 +401,8 @@ export const AuthForm = ({
</Tooltip>
</>
)}
<Button
{/* TODO after v5.8: Add SAML SSO back in */}
{/* <Button
startContent={
!isSamlMode && (
<Icon
@@ -418,19 +419,19 @@ export const AuthForm = ({
}}
>
{isSamlMode ? "Back" : "Continue with SAML SSO"}
</Button>
</Button> */}
</div>
</>
)}
{type === "sign-in" ? (
<p className="text-center text-small">
Need to create an account?&nbsp;
<Link href="/sign-up">Sign Up</Link>
<Link href="/sign-up">Sign up</Link>
</p>
) : (
<p className="text-center text-small">
Already have an account?&nbsp;
<Link href="/sign-in">Log In</Link>
<Link href="/sign-in">Log in</Link>
</p>
)}
</div>
@@ -44,7 +44,7 @@ interface FailedSectionsListProps {
const title = (
<h3 className="mb-2 whitespace-nowrap text-xs font-semibold uppercase tracking-wide">
Failed Sections (Top 5)
Top Failed Sections
</h3>
);
@@ -1,7 +1,9 @@
"use client";
import Link from "next/link";
import { Dispatch, SetStateAction, useEffect, useRef, useState } from "react";
import { useFormState } from "react-dom";
import { z } from "zod";
import { createSamlConfig, updateSamlConfig } from "@/actions/integrations";
import { AddIcon } from "@/components/icons";
@@ -9,26 +11,56 @@ import { useToast } from "@/components/ui";
import { CustomButton, CustomServerInput } from "@/components/ui/custom";
import { SnippetChip } from "@/components/ui/entities";
import { FormButtons } from "@/components/ui/form";
import { apiBaseUrl } from "@/lib";
export const SamlConfigForm = ({
setIsOpen,
id,
samlConfig,
}: {
setIsOpen: Dispatch<SetStateAction<boolean>>;
id: string;
samlConfig?: any;
}) => {
const [state, formAction, isPending] = useFormState(
id ? updateSamlConfig : createSamlConfig,
samlConfig?.id ? updateSamlConfig : createSamlConfig,
null,
);
const [emailDomain, setEmailDomain] = useState("");
const [uploadedFile, setUploadedFile] = useState<{
name: string;
uploaded: boolean;
}>({ name: "", uploaded: false });
const [emailDomain, setEmailDomain] = useState(
samlConfig?.attributes?.email_domain || "",
);
const [uploadedFile, setUploadedFile] = useState<File | null>(null);
const [clientErrors, setClientErrors] = useState<{
email_domain?: string | null;
metadata_xml?: string | null;
}>({});
const formRef = useRef<HTMLFormElement>(null);
const { toast } = useToast();
// Client-side validation function
const validateFields = (email: string, hasFile: boolean) => {
// Validar cada campo por separado para poder limpiarlos individualmente
const emailValidation = z
.string()
.trim()
.min(1, { message: "Email domain is required" })
.safeParse(email);
const metadataValidation = z
.string()
.trim()
.min(1, { message: "Metadata XML is required" })
.safeParse(hasFile ? "dummy_xml_content" : "");
const newErrors = {
email_domain: emailValidation.success
? null
: emailValidation.error.issues[0]?.message,
metadata_xml: metadataValidation.success
? null
: metadataValidation.error.issues[0]?.message,
};
setClientErrors(newErrors);
};
useEffect(() => {
if (state?.success) {
toast({
@@ -48,7 +80,8 @@ export const SamlConfigForm = ({
const handleFileUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (!file) {
setUploadedFile({ name: "", uploaded: false });
setUploadedFile(null);
validateFields(emailDomain, false);
return;
}
@@ -66,7 +99,8 @@ export const SamlConfigForm = ({
});
// Clear the file input
event.target.value = "";
setUploadedFile({ name: "", uploaded: false });
setUploadedFile(null);
validateFields(emailDomain, false);
return;
}
@@ -84,7 +118,8 @@ export const SamlConfigForm = ({
});
// Clear the file input
event.target.value = "";
setUploadedFile({ name: "", uploaded: false });
setUploadedFile(null);
validateFields(emailDomain, false);
return;
}
@@ -96,8 +131,8 @@ export const SamlConfigForm = ({
xmlInput.value = content;
}
// Update file state
setUploadedFile({ name: file.name, uploaded: true });
setUploadedFile(file);
validateFields(emailDomain, true);
toast({
title: "File uploaded successfully",
@@ -113,89 +148,44 @@ export const SamlConfigForm = ({
});
// Clear the file input
event.target.value = "";
setUploadedFile({ name: "", uploaded: false });
setUploadedFile(null);
validateFields(emailDomain, false);
};
reader.readAsText(file);
};
const acsUrl = emailDomain
? `https://app.prowler.pro/saml/sp/consume/${emailDomain}`
: "https://app.prowler.pro/saml/sp/consume/your-domain.com";
? `${apiBaseUrl}/accounts/saml/${emailDomain}/acs/`
: `${apiBaseUrl}/accounts/saml/your-domain.com/acs/`;
return (
<form ref={formRef} action={formAction} className="flex flex-col space-y-6">
<input type="hidden" name="id" value={id} />
<div className="space-y-4">
<CustomServerInput
name="email_domain"
label="Email Domain"
placeholder="Enter your email domain (e.g., company.com)"
labelPlacement="outside"
variant="bordered"
isRequired={true}
isInvalid={!!state?.errors?.email_domain}
errorMessage={state?.errors?.email_domain}
value={emailDomain}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
setEmailDomain(e.target.value);
}}
/>
<div className="flex flex-col items-start space-y-2">
<span className="text-xs text-default-500">
Metadata XML File <span className="text-red-500">*</span>
</span>
<CustomButton
type="button"
ariaLabel="Select Metadata XML File"
isDisabled={isPending}
onPress={() => {
const fileInput = document.getElementById(
"metadata_xml_file",
) as HTMLInputElement;
if (fileInput) {
fileInput.click();
}
}}
startContent={<AddIcon size={20} />}
className={`h-10 justify-start rounded-medium border-2 text-default-500 ${
state?.errors?.metadata_xml
? "border-red-500"
: uploadedFile.uploaded
? "border-green-500 bg-green-50 dark:bg-green-900/20"
: "border-default-200"
}`}
>
<span className="text-small">
{uploadedFile.uploaded ? (
<span className="flex items-center space-x-2">
<span className="max-w-36 truncate">{uploadedFile.name}</span>
</span>
) : (
"Choose File"
)}
</span>
</CustomButton>
<input
type="file"
id="metadata_xml_file"
name="metadata_xml_file"
accept=".xml,application/xml,text/xml"
className="hidden"
disabled={isPending}
onChange={handleFileUpload}
/>
<input type="hidden" id="metadata_xml" name="metadata_xml" />
<p className="text-xs text-gray-500">
Upload your Identity Provider&apos;s SAML metadata XML file
</p>
<span className="text-xs text-red-500">
{state?.errors?.metadata_xml}
</span>
</div>
</div>
<form ref={formRef} action={formAction} className="flex flex-col space-y-2">
<input type="hidden" name="id" value={samlConfig?.id || ""} />
<CustomServerInput
name="email_domain"
label="Email Domain"
placeholder="Enter your email domain (e.g., company.com)"
labelPlacement="outside"
variant="bordered"
isRequired={true}
isInvalid={
!!(clientErrors.email_domain === null
? undefined
: clientErrors.email_domain || state?.errors?.email_domain)
}
errorMessage={
clientErrors.email_domain === null
? undefined
: clientErrors.email_domain || state?.errors?.email_domain
}
value={emailDomain}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
const newValue = e.target.value;
setEmailDomain(newValue);
validateFields(newValue, !!uploadedFile);
}}
/>
<div className="space-y-4 rounded-lg bg-gray-50 p-4 dark:bg-gray-800">
<h3 className="text-lg font-semibold">
@@ -229,11 +219,9 @@ export const SamlConfigForm = ({
<span className="mb-2 block text-sm font-medium text-default-500">
Name ID Format:
</span>
<SnippetChip
value="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"
ariaLabel="Copy Name ID Format to clipboard"
className="w-full"
/>
<span className="w-full text-sm text-default-600">
urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress
</span>
</div>
<div>
@@ -250,13 +238,82 @@ export const SamlConfigForm = ({
<strong>Note:</strong> The userType attribute will be used to
assign the user&apos;s role. If the role does not exist, one will
be created with minimal permissions. You can assign permissions to
roles on the Roles page.
roles on the{" "}
<Link href="/roles">
<span className="underline">Roles</span>
</Link>{" "}
page.
</p>
</div>
</div>
</div>
<div className="flex flex-col items-start space-y-2">
<span className="text-xs text-default-500">
Metadata XML File <span className="text-red-500">*</span>
</span>
<CustomButton
type="button"
ariaLabel="Select Metadata XML File"
isDisabled={isPending}
onPress={() => {
const fileInput = document.getElementById(
"metadata_xml_file",
) as HTMLInputElement;
if (fileInput) {
fileInput.click();
}
}}
startContent={<AddIcon size={20} />}
className={`h-10 justify-start rounded-medium border-2 text-default-500 ${
(
clientErrors.metadata_xml === null
? undefined
: clientErrors.metadata_xml || state?.errors?.metadata_xml
)
? "border-red-500"
: uploadedFile
? "border-green-500 bg-green-50 dark:bg-green-900/20"
: "border-default-200"
}`}
>
<span className="text-small">
{uploadedFile ? (
<span className="flex items-center space-x-2">
<span className="max-w-36 truncate">{uploadedFile.name}</span>
</span>
) : (
"Choose File"
)}
</span>
</CustomButton>
<FormButtons setIsOpen={setIsOpen} submitText={id ? "Update" : "Save"} />
<input
type="file"
id="metadata_xml_file"
name="metadata_xml_file"
accept=".xml,application/xml,text/xml"
className="hidden"
disabled={isPending}
onChange={handleFileUpload}
/>
<input type="hidden" id="metadata_xml" name="metadata_xml" />
<p className="text-xs text-gray-500">
Upload your Identity Provider&apos;s SAML metadata XML file
</p>
<span className="text-xs text-red-500">
{(() => {
const finalError =
clientErrors.metadata_xml === null
? undefined
: clientErrors.metadata_xml || state?.errors?.metadata_xml;
return finalError;
})()}
</span>
</div>
<FormButtons
setIsOpen={setIsOpen}
submitText={samlConfig?.id ? "Update" : "Save"}
/>
</form>
);
};
@@ -1,15 +1,51 @@
"use client";
import { Card, CardBody, CardHeader } from "@nextui-org/react";
import { CheckIcon } from "lucide-react";
import { Link } from "@nextui-org/react";
import { CheckIcon, Trash2Icon } from "lucide-react";
import { useState } from "react";
import { deleteSamlConfig } from "@/actions/integrations";
import { useToast } from "@/components/ui";
import { CustomAlertModal, CustomButton } from "@/components/ui/custom";
import { SamlConfigForm } from "./forms";
export const SamlIntegrationCard = ({ id }: { id: string }) => {
export const SamlIntegrationCard = ({ samlConfig }: { samlConfig?: any }) => {
const [isSamlModalOpen, setIsSamlModalOpen] = useState(false);
const [isDeleting, setIsDeleting] = useState(false);
const { toast } = useToast();
const id = samlConfig?.id;
const handleRemoveSaml = async () => {
if (!id) return;
setIsDeleting(true);
try {
const result = await deleteSamlConfig(id);
if (result.success) {
toast({
title: "SAML configuration removed",
description: result.success,
});
} else if (result.errors?.general) {
toast({
variant: "destructive",
title: "Error removing SAML configuration",
description: result.errors.general,
});
}
} catch (error) {
toast({
variant: "destructive",
title: "Error",
description: "Failed to remove SAML configuration. Please try again.",
});
} finally {
setIsDeleting(false);
}
};
return (
<>
@@ -18,7 +54,10 @@ export const SamlIntegrationCard = ({ id }: { id: string }) => {
onOpenChange={setIsSamlModalOpen}
title="Configure SAML SSO"
>
<SamlConfigForm setIsOpen={setIsSamlModalOpen} id={id} />
<SamlConfigForm
setIsOpen={setIsSamlModalOpen}
samlConfig={samlConfig}
/>
</CustomAlertModal>
<Card className="dark:bg-prowler-blue-400">
@@ -29,9 +68,21 @@ export const SamlIntegrationCard = ({ id }: { id: string }) => {
{id && <CheckIcon className="text-prowler-green" size={20} />}
</div>
<p className="text-xs text-gray-500">
{id
? "SAML Single Sign-On is enabled for this organization"
: "Configure SAML Single Sign-On for secure authentication"}
{id ? (
"SAML Single Sign-On is enabled for this organization"
) : (
<>
Configure SAML Single Sign-On for secure authentication.{" "}
<Link
target="_blank"
href="https://docs.prowler.com/projects/prowler-open-source/en/latest/tutorials/prowler-app-sso"
rel="noopener noreferrer"
className="text-xs font-medium text-primary"
>
Read the docs
</Link>
</>
)}
</p>
</div>
</CardHeader>
@@ -43,14 +94,29 @@ export const SamlIntegrationCard = ({ id }: { id: string }) => {
{id ? "Enabled" : "Disabled"}
</span>
</div>
<CustomButton
size="sm"
ariaLabel="Add SAML SSO"
color="action"
onPress={() => setIsSamlModalOpen(true)}
>
{id ? "Update" : "Enable"}
</CustomButton>
<div className="flex gap-2">
<CustomButton
size="sm"
ariaLabel="Configure SAML SSO"
color="action"
onPress={() => setIsSamlModalOpen(true)}
>
{id ? "Update" : "Enable"}
</CustomButton>
{id && (
<CustomButton
size="sm"
ariaLabel="Remove SAML SSO"
color="danger"
variant="bordered"
isLoading={isDeleting}
startContent={!isDeleting ? <Trash2Icon size={16} /> : null}
onPress={handleRemoveSaml}
>
Remove
</CustomButton>
)}
</div>
</div>
</CardBody>
</Card>
@@ -1,5 +1,7 @@
import Link from "next/link";
import { Control } from "react-hook-form";
import { InfoIcon } from "@/components/icons";
import { CustomInput } from "@/components/ui/custom";
import { M365Credentials } from "@/types";
@@ -51,6 +53,39 @@ export const M365CredentialsForm = ({
isRequired
isInvalid={!!control._formState.errors.tenant_id}
/>
<p className="text-sm text-default-500">
{" "}
User and password authentication is being deprecated due to
Microsoft&apos;s on-going MFA enforcement across all tenants (see{" "}
<Link
href="https://azure.microsoft.com/en-us/blog/announcing-mandatory-multi-factor-authentication-for-azure-sign-in/"
target="_blank"
rel="noopener noreferrer"
className="text-sm text-primary hover:underline"
>
Microsoft docs
</Link>
).
</p>
<div className="flex items-center rounded-lg border border-system-warning bg-system-warning-medium p-2 text-sm dark:text-default-300">
<InfoIcon className="mr-2 inline h-4 w-4 flex-shrink-0" />
<p className="text-xs font-extrabold">
By September 2025, MFA will be mandatory.
</p>
</div>
<p className="text-sm text-default-500">
Due to that change, you must only{" "}
<Link
href="https://docs.prowler.com/projects/prowler-open-source/en/latest/tutorials/microsoft365/getting-started-m365/#step-3-configure-your-m365-account"
target="_blank"
rel="noopener noreferrer"
className="text-sm text-primary hover:underline"
>
use application authentication
</Link>{" "}
to maintain all Prowler M365 scan capabilities.
</p>
<CustomInput
control={control}
name="user"
+33 -33
View File
@@ -121,44 +121,44 @@ export const useRelatedFilters = ({
if (shouldDeselectScan) {
updateFilter(FilterType.SCAN, null);
} else {
// Add provider if not already selected
if (scanProviderId && !currentProviders.includes(scanProviderId)) {
updateFilter(FilterType.PROVIDER_UID, [
...currentProviders,
scanProviderId,
]);
}
// } else {
// // Add provider if not already selected
// if (scanProviderId && !currentProviders.includes(scanProviderId)) {
// updateFilter(FilterType.PROVIDER_UID, [
// ...currentProviders,
// scanProviderId,
// ]);
// }
// Only add provider type if there are none selected
if (
scanProviderType &&
currentProviderTypes.length === 0 &&
!isManualDeselection.current
) {
updateFilter(FilterType.PROVIDER_TYPE, [scanProviderType]);
}
// // Only add provider type if there are none selected
// if (
// scanProviderType &&
// currentProviderTypes.length === 0 &&
// !isManualDeselection.current
// ) {
// updateFilter(FilterType.PROVIDER_TYPE, [scanProviderType]);
// }
}
}
// Handle provider selection logic
if (
currentProviders.length > 0 &&
deselectedProviders.length === 0 &&
!isManualDeselection.current
) {
const providerTypes = currentProviders
.map(getProviderType)
.filter((type): type is ProviderType => type !== null);
const selectedProviderTypes = Array.from(new Set(providerTypes));
// // Handle provider selection logic
// if (
// currentProviders.length > 0 &&
// deselectedProviders.length === 0 &&
// !isManualDeselection.current
// ) {
// const providerTypes = currentProviders
// .map(getProviderType)
// .filter((type): type is ProviderType => type !== null);
// const selectedProviderTypes = Array.from(new Set(providerTypes));
if (
selectedProviderTypes.length > 0 &&
currentProviderTypes.length === 0
) {
updateFilter(FilterType.PROVIDER_TYPE, selectedProviderTypes);
}
}
// if (
// selectedProviderTypes.length > 0 &&
// currentProviderTypes.length === 0
// ) {
// updateFilter(FilterType.PROVIDER_TYPE, selectedProviderTypes);
// }
// }
// Update available providers
if (currentProviderTypes.length > 0) {
+1 -1
View File
@@ -5,7 +5,7 @@ import { useToast } from "@/components/ui";
import { AuthSocialProvider, MetaDataProps, PermissionInfo } from "@/types";
export const baseUrl = process.env.AUTH_URL || "http://localhost:3000";
export const apiBaseUrl = process.env.API_BASE_URL;
export const apiBaseUrl = process.env.NEXT_PUBLIC_API_BASE_URL;
/**
* Extracts a form value from a FormData object
@@ -192,17 +192,8 @@ export const buildUpdateSecretConfig = (
formData: FormData,
providerType: ProviderType,
) => {
// Reuse the same secret building logic as add, but only return the secret
// Reuse the same secret building logic as add
const { secret } = buildSecretConfig(formData, providerType);
// Handle special case for M365 password field inconsistency
if (providerType === "m365") {
return {
...secret,
password: formData.get(ProviderCredentialFields.PASSWORD),
};
}
return secret;
};
+27 -27
View File
@@ -394,9 +394,9 @@
}
},
"node_modules/@eslint/eslintrc/node_modules/brace-expansion": {
"version": "1.1.11",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz",
"integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==",
"version": "1.1.12",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz",
"integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==",
"dev": true,
"dependencies": {
"balanced-match": "^1.0.0",
@@ -526,9 +526,9 @@
}
},
"node_modules/@humanwhocodes/config-array/node_modules/brace-expansion": {
"version": "1.1.11",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz",
"integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==",
"version": "1.1.12",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz",
"integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==",
"dev": true,
"dependencies": {
"balanced-match": "^1.0.0",
@@ -8732,9 +8732,9 @@
}
},
"node_modules/brace-expansion": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz",
"integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==",
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz",
"integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==",
"dependencies": {
"balanced-match": "^1.0.0"
}
@@ -10567,9 +10567,9 @@
}
},
"node_modules/eslint-plugin-import/node_modules/brace-expansion": {
"version": "1.1.11",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz",
"integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==",
"version": "1.1.12",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz",
"integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==",
"dev": true,
"dependencies": {
"balanced-match": "^1.0.0",
@@ -10649,9 +10649,9 @@
}
},
"node_modules/eslint-plugin-jsx-a11y/node_modules/brace-expansion": {
"version": "1.1.11",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz",
"integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==",
"version": "1.1.12",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz",
"integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==",
"dev": true,
"dependencies": {
"balanced-match": "^1.0.0",
@@ -10691,9 +10691,9 @@
}
},
"node_modules/eslint-plugin-node/node_modules/brace-expansion": {
"version": "1.1.11",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz",
"integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==",
"version": "1.1.12",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz",
"integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==",
"dev": true,
"dependencies": {
"balanced-match": "^1.0.0",
@@ -10796,9 +10796,9 @@
}
},
"node_modules/eslint-plugin-react/node_modules/brace-expansion": {
"version": "1.1.11",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz",
"integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==",
"version": "1.1.12",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz",
"integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==",
"dev": true,
"dependencies": {
"balanced-match": "^1.0.0",
@@ -10962,9 +10962,9 @@
}
},
"node_modules/eslint/node_modules/brace-expansion": {
"version": "1.1.11",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz",
"integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==",
"version": "1.1.12",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz",
"integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==",
"dev": true,
"dependencies": {
"balanced-match": "^1.0.0",
@@ -15587,9 +15587,9 @@
}
},
"node_modules/rimraf/node_modules/brace-expansion": {
"version": "1.1.11",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz",
"integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==",
"version": "1.1.12",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz",
"integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==",
"dev": true,
"dependencies": {
"balanced-match": "^1.0.0",
+11
View File
@@ -309,3 +309,14 @@ export const editUserFormSchema = () =>
userId: z.string(),
role: z.string().optional(),
});
export const samlConfigFormSchema = z.object({
email_domain: z
.string()
.trim()
.min(1, { message: "Email domain is required" }),
metadata_xml: z
.string()
.trim()
.min(1, { message: "Metadata XML is required" }),
});
+24
View File
@@ -67,3 +67,27 @@ export interface ExpandedScanData extends ScanProps {
alias: string;
};
}
export interface ScansApiResponse {
links: {
first: string;
last: string;
next: string | null;
prev: string | null;
};
data: ScanProps[];
included?: Array<{
type: string;
id: string;
attributes: any;
relationships?: any;
}>;
meta: {
pagination: {
page: number;
pages: number;
count: number;
};
version: string;
};
}