Compare commits

...

65 Commits

Author SHA1 Message Date
HugoPBrito
cc0e63ee88 feat: added testing 2024-12-30 15:40:42 +00:00
HugoPBrito
f6552d16d5 feat: added check logic and metadata 2024-12-30 15:40:26 +00:00
HugoPBrito
6e3e827069 fix: oauth auth env var 2024-12-18 18:09:47 +00:00
HugoPBrito
d3be64dd58 Merge branch 'PRWLR-5534-ensure-all-open-comments-are-resolved-before-allowing-code-change-merging' into PRWLR-5531-ensure-inactive-branches-are-periodically-reviewed-and-removed 2024-12-18 11:39:05 +00:00
HugoPBrito
62e7e6eb72 Merge branch 'PRWLR-5536-ensure-branch-protection-rules-are-enforced-for-administrators' into PRWLR-5534-ensure-all-open-comments-are-resolved-before-allowing-code-change-merging 2024-12-18 11:38:21 +00:00
HugoPBrito
67c1b0eb7c Merge branch 'PRWLR-5532-ensure-all-checks-have-passed-before-merging-new-code' into PRWLR-5536-ensure-branch-protection-rules-are-enforced-for-administrators 2024-12-18 11:37:45 +00:00
HugoPBrito
b06832be1a Merge branch 'PRWLR-5538-ensure-branch-deletions-are-denied' into PRWLR-5532-ensure-all-checks-have-passed-before-merging-new-code 2024-12-18 11:37:13 +00:00
HugoPBrito
1854c8e0b5 fix: metadata CheckTitle 2024-12-18 11:36:41 +00:00
HugoPBrito
71d24d7985 Merge branch 'PRWLR-5537-ensure-force-push-code-to-branches-is-denied' into PRWLR-5538-ensure-branch-deletions-are-denied 2024-12-18 11:35:05 +00:00
HugoPBrito
a28f70e1f7 Merge branch 'PRWLR-5535-ensure-linear-history-required' into PRWLR-5537-ensure-force-push-code-to-branches-is-denied 2024-12-18 11:33:51 +00:00
HugoPBrito
204d8232f7 Merge branch 'PRWLR-5516-ensure-branch-protection-enforced-on-the-default-branch' into PRWLR-5535-ensure-linear-history-required 2024-12-18 11:30:07 +00:00
HugoPBrito
047efcf49f Merge branch 'PRWLR-5513-enforce-multi-approval-requirement-for-code-changes-in-git-hub-repositories' into PRWLR-5516-ensure-branch-protection-enforced-on-the-default-branch 2024-12-18 11:27:44 +00:00
HugoPBrito
b853cf7d9a Merge branch 'github-poc' into PRWLR-5513-enforce-multi-approval-requirement-for-code-changes-in-git-hub-repositories 2024-12-18 11:27:13 +00:00
HugoPBrito
0f38389124 chore: generate lock 2024-12-18 11:24:39 +00:00
HugoPBrito
c40ec4be32 feat: change github-app-key param to a key-path 2024-12-18 11:19:21 +00:00
MrCloudSec
8c5c5f7f3b chore: revision 2024-12-17 11:25:00 -05:00
Sergio Garcia
6cef2e8988 Merge branch 'master' into github-poc 2024-12-17 10:46:48 -05:00
HugoPBrito
ca80adc221 fix: docstrings 2024-12-16 14:20:43 +00:00
HugoPBrito
6d9bf8046e fix: docstrings 2024-12-16 14:15:45 +00:00
HugoPBrito
5a6bcec9aa feat: added testing 2024-12-16 14:05:57 +00:00
HugoPBrito
db1adc67b9 feat: added check logic and metadata 2024-12-16 14:05:35 +00:00
HugoPBrito
17c4b58099 fix: test_get_client 2024-12-16 13:25:21 +00:00
HugoPBrito
15d7e107ee feat: added testing 2024-12-16 13:18:23 +00:00
HugoPBrito
bcb8c7d3f8 feat: added check logic and metadata 2024-12-16 13:17:56 +00:00
HugoPBrito
6575680f01 feat: added testing 2024-12-16 12:10:04 +00:00
HugoPBrito
1d01fa8a08 feat: added check logic and metadata 2024-12-16 12:09:33 +00:00
HugoPBrito
7561ab0320 feat: added testing 2024-12-16 11:31:55 +00:00
HugoPBrito
5ecf2e9b33 feat: added check logic and metadata 2024-12-16 11:31:29 +00:00
HugoPBrito
856b6d782b feat: added testing 2024-12-13 23:04:58 +00:00
HugoPBrito
8bf59e5ca6 feat: added check logic and metadata 2024-12-13 23:04:40 +00:00
HugoPBrito
112a716c88 feat: added testing 2024-12-13 21:38:23 +00:00
HugoPBrito
077cdeabaf feat: added check logic and metadata 2024-12-13 21:37:38 +00:00
HugoPBrito
e907abb929 feat: add new check 2024-12-12 13:44:13 +01:00
HugoPBrito
705f577412 feat: add new check 2024-12-12 13:41:15 +01:00
HugoPBrito
ab1239cc93 feat: add new check 2024-12-12 13:19:29 +01:00
HugoPBrito
69b0b7f1cb Merge branch 'master' of https://github.com/prowler-cloud/prowler into github-poc 2024-12-03 17:03:34 +01:00
HugoPBrito
0ea3a202c4 chore: remove log print 2024-12-02 13:13:35 +01:00
HugoPBrito
0b8bf9851a chore: enhance format_rsa_key logic 2024-11-27 17:15:12 +01:00
HugoPBrito
27a8bb03d3 chore: enhanced logic of rsa format 2024-11-27 17:10:20 +01:00
HugoPBrito
6b7fa9ac4e feat: enhance print_credentials 2024-11-27 13:54:58 +01:00
HugoPBrito
b50ac49a7e feat: enhance authentication logic flow 2024-11-27 13:23:38 +01:00
HugoPBrito
93ea60cc86 feat: add testing for new auth methods 2024-11-26 17:18:57 +01:00
HugoPBrito
9fe50eb264 feat: resolved comment
Removed CIS compliance from check metadata
2024-11-26 14:21:15 +01:00
HugoPBrito
6f961139a1 feat: complete github app login 2024-11-26 14:10:02 +01:00
HugoPBrito
7001789997 feat: add github app login
Removed deprecated user-passwd login and replaced it with github app
2024-11-25 17:51:47 +01:00
HugoPBrito
aa0d82f500 feat: pat and oauth authentication with and without flags 2024-11-25 17:00:33 +01:00
HugoPBrito
b94a535aba feat: oauth login with flag 2024-11-25 16:05:11 +01:00
HugoPBrito
9c9526af80 fix: minor correction 2024-11-25 13:55:25 +01:00
HugoPBrito
1d0243652e feat: revert poetry lock 2024-11-25 13:51:01 +01:00
HugoPBrito
4e64a26ece feat: enhanced logic 2024-11-25 13:30:15 +01:00
HugoPBrito
b2e58c3045 feat: add default env PAT login
Added env PAT login by default and --pat flag retrieval
2024-11-25 13:07:52 +01:00
HugoPBrito
45668eb53a feat: added custom exceptions
Added custom exceptions for provider initialization like bad credentials or non existent env variables.
2024-11-25 11:06:07 +01:00
HugoPBrito
cac7c42f13 fix: logic of security.md retrieval 2024-11-22 11:48:14 +01:00
HugoPBrito
5ee960e13d feat: added testing
Added testing classes for provider, new service and check and corrected minor issues.
2024-11-20 18:09:10 +01:00
HugoPBrito
c11e6449f9 fix: reverted name 2024-11-20 11:42:31 +01:00
HugoPBrito
fa8a7f44de fix: reverted name 2024-11-20 11:33:38 +01:00
HugoPBrito
f028e41652 feat: renamed first check 2024-11-20 11:14:15 +01:00
MrCloudSec
b815eeb7ab Merge branch 'master' into github-poc 2024-11-19 12:35:50 -04:00
MrCloudSec
d0701ad0ce chore: revision 2024-11-19 12:34:49 -04:00
HugoPBrito
d4e5b7c7c7 feat: add new check to service 2024-11-19 17:14:34 +01:00
HugoPBrito
d27c5b7190 feat: first service implementation 2024-11-19 13:18:30 +01:00
MrCloudSec
5ce7aa33ad chore: revision 2024-11-18 13:15:46 -04:00
HugoPBrito
2628a4e506 fix: arguments parser 2024-11-18 15:04:12 +01:00
HugoPBrito
27b628152d feat: provider structural resemblance 2024-11-15 14:03:56 +01:00
HugoPBrito
f8f1e6c076 feat: basic PoC script
basic repo info retrieval
2024-11-12 15:03:36 +01:00
72 changed files with 3188 additions and 7 deletions

54
poetry.lock generated
View File

@@ -1,4 +1,4 @@
# This file is automatically @generated by Poetry 1.8.5 and should not be changed by hand.
# This file is automatically @generated by Poetry 1.8.4 and should not be changed by hand.
[[package]]
name = "about-time"
@@ -3760,6 +3760,25 @@ files = [
{file = "pyflakes-3.2.0.tar.gz", hash = "sha256:1c61603ff154621fb2a9172037d84dca3500def8c8b630657d1701f026f8af3f"},
]
[[package]]
name = "pygithub"
version = "2.5.0"
description = "Use the full Github API v3"
optional = false
python-versions = ">=3.8"
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.18.0"
@@ -3842,6 +3861,32 @@ pyyaml = "*"
[package.extras]
extra = ["pygments (>=2.12)"]
[[package]]
name = "pynacl"
version = "1.5.0"
description = "Python binding to the Networking and Cryptography (NaCl) library"
optional = false
python-versions = ">=3.6"
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.0"
@@ -4458,7 +4503,6 @@ files = [
{file = "ruamel.yaml.clib-0.2.12-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f66efbc1caa63c088dead1c4170d148eabc9b80d95fb75b6c92ac0aad2437d76"},
{file = "ruamel.yaml.clib-0.2.12-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:22353049ba4181685023b25b5b51a574bce33e7f51c759371a7422dcae5402a6"},
{file = "ruamel.yaml.clib-0.2.12-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:932205970b9f9991b34f55136be327501903f7c66830e9760a8ffb15b07f05cd"},
{file = "ruamel.yaml.clib-0.2.12-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:a52d48f4e7bf9005e8f0a89209bf9a73f7190ddf0489eee5eb51377385f59f2a"},
{file = "ruamel.yaml.clib-0.2.12-cp310-cp310-win32.whl", hash = "sha256:3eac5a91891ceb88138c113f9db04f3cebdae277f5d44eaa3651a4f573e6a5da"},
{file = "ruamel.yaml.clib-0.2.12-cp310-cp310-win_amd64.whl", hash = "sha256:ab007f2f5a87bd08ab1499bdf96f3d5c6ad4dcfa364884cb4549aa0154b13a28"},
{file = "ruamel.yaml.clib-0.2.12-cp311-cp311-macosx_13_0_arm64.whl", hash = "sha256:4a6679521a58256a90b0d89e03992c15144c5f3858f40d7c18886023d7943db6"},
@@ -4467,7 +4511,6 @@ files = [
{file = "ruamel.yaml.clib-0.2.12-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:811ea1594b8a0fb466172c384267a4e5e367298af6b228931f273b111f17ef52"},
{file = "ruamel.yaml.clib-0.2.12-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:cf12567a7b565cbf65d438dec6cfbe2917d3c1bdddfce84a9930b7d35ea59642"},
{file = "ruamel.yaml.clib-0.2.12-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:7dd5adc8b930b12c8fc5b99e2d535a09889941aa0d0bd06f4749e9a9397c71d2"},
{file = "ruamel.yaml.clib-0.2.12-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:1492a6051dab8d912fc2adeef0e8c72216b24d57bd896ea607cb90bb0c4981d3"},
{file = "ruamel.yaml.clib-0.2.12-cp311-cp311-win32.whl", hash = "sha256:bd0a08f0bab19093c54e18a14a10b4322e1eacc5217056f3c063bd2f59853ce4"},
{file = "ruamel.yaml.clib-0.2.12-cp311-cp311-win_amd64.whl", hash = "sha256:a274fb2cb086c7a3dea4322ec27f4cb5cc4b6298adb583ab0e211a4682f241eb"},
{file = "ruamel.yaml.clib-0.2.12-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:20b0f8dc160ba83b6dcc0e256846e1a02d044e13f7ea74a3d1d56ede4e48c632"},
@@ -4476,7 +4519,6 @@ files = [
{file = "ruamel.yaml.clib-0.2.12-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:749c16fcc4a2b09f28843cda5a193e0283e47454b63ec4b81eaa2242f50e4ccd"},
{file = "ruamel.yaml.clib-0.2.12-cp312-cp312-musllinux_1_1_i686.whl", hash = "sha256:bf165fef1f223beae7333275156ab2022cffe255dcc51c27f066b4370da81e31"},
{file = "ruamel.yaml.clib-0.2.12-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:32621c177bbf782ca5a18ba4d7af0f1082a3f6e517ac2a18b3974d4edf349680"},
{file = "ruamel.yaml.clib-0.2.12-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:b82a7c94a498853aa0b272fd5bc67f29008da798d4f93a2f9f289feb8426a58d"},
{file = "ruamel.yaml.clib-0.2.12-cp312-cp312-win32.whl", hash = "sha256:e8c4ebfcfd57177b572e2040777b8abc537cdef58a2120e830124946aa9b42c5"},
{file = "ruamel.yaml.clib-0.2.12-cp312-cp312-win_amd64.whl", hash = "sha256:0467c5965282c62203273b838ae77c0d29d7638c8a4e3a1c8bdd3602c10904e4"},
{file = "ruamel.yaml.clib-0.2.12-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:4c8c5d82f50bb53986a5e02d1b3092b03622c02c2eb78e29bec33fd9593bae1a"},
@@ -4485,7 +4527,6 @@ files = [
{file = "ruamel.yaml.clib-0.2.12-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:96777d473c05ee3e5e3c3e999f5d23c6f4ec5b0c38c098b3a5229085f74236c6"},
{file = "ruamel.yaml.clib-0.2.12-cp313-cp313-musllinux_1_1_i686.whl", hash = "sha256:3bc2a80e6420ca8b7d3590791e2dfc709c88ab9152c00eeb511c9875ce5778bf"},
{file = "ruamel.yaml.clib-0.2.12-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:e188d2699864c11c36cdfdada94d781fd5d6b0071cd9c427bceb08ad3d7c70e1"},
{file = "ruamel.yaml.clib-0.2.12-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:4f6f3eac23941b32afccc23081e1f50612bdbe4e982012ef4f5797986828cd01"},
{file = "ruamel.yaml.clib-0.2.12-cp313-cp313-win32.whl", hash = "sha256:6442cb36270b3afb1b4951f060eccca1ce49f3d087ca1ca4563a6eb479cb3de6"},
{file = "ruamel.yaml.clib-0.2.12-cp313-cp313-win_amd64.whl", hash = "sha256:e5b8daf27af0b90da7bb903a876477a9e6d7270be6146906b276605997c7e9a3"},
{file = "ruamel.yaml.clib-0.2.12-cp39-cp39-macosx_12_0_arm64.whl", hash = "sha256:fc4b630cd3fa2cf7fce38afa91d7cfe844a9f75d7f0f36393fa98815e911d987"},
@@ -4494,7 +4535,6 @@ files = [
{file = "ruamel.yaml.clib-0.2.12-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e2f1c3765db32be59d18ab3953f43ab62a761327aafc1594a2a1fbe038b8b8a7"},
{file = "ruamel.yaml.clib-0.2.12-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:d85252669dc32f98ebcd5d36768f5d4faeaeaa2d655ac0473be490ecdae3c285"},
{file = "ruamel.yaml.clib-0.2.12-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:e143ada795c341b56de9418c58d028989093ee611aa27ffb9b7f609c00d813ed"},
{file = "ruamel.yaml.clib-0.2.12-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:2c59aa6170b990d8d2719323e628aaf36f3bfbc1c26279c0eeeb24d05d2d11c7"},
{file = "ruamel.yaml.clib-0.2.12-cp39-cp39-win32.whl", hash = "sha256:beffaed67936fbbeffd10966a4eb53c402fafd3d6833770516bf7314bc6ffa12"},
{file = "ruamel.yaml.clib-0.2.12-cp39-cp39-win_amd64.whl", hash = "sha256:040ae85536960525ea62868b642bdb0c2cc6021c9f9d507810c0c604e66f5a7b"},
{file = "ruamel.yaml.clib-0.2.12.tar.gz", hash = "sha256:6c8fbb13ec503f99a91901ab46e0b07ae7941cd527393187039aec586fdfd36f"},
@@ -5199,4 +5239,4 @@ type = ["pytest-mypy"]
[metadata]
lock-version = "2.0"
python-versions = ">=3.9,<3.13"
content-hash = "b55f659c24e26a60942906d7a3773f65bbb8fba0c8d207decb671d1f35c20028"
content-hash = "4d06c5623e0b4b2e0f499d8c603b0f06d8b8eb8097b70caa78c866bdc759d8d9"

View File

@@ -77,6 +77,7 @@ from prowler.providers.azure.models import AzureOutputOptions
from prowler.providers.common.provider import Provider
from prowler.providers.common.quick_inventory import run_provider_quick_inventory
from prowler.providers.gcp.models import GCPOutputOptions
from prowler.providers.github.models import GithubOutputOptions
from prowler.providers.kubernetes.models import KubernetesOutputOptions
@@ -259,6 +260,10 @@ def prowler():
output_options = KubernetesOutputOptions(
args, bulk_checks_metadata, global_provider.identity
)
elif provider == "github":
output_options = GithubOutputOptions(
args, bulk_checks_metadata, global_provider.identity
)
# Run the quick inventory for the provider if available
if hasattr(args, "quick_inventory") and args.quick_inventory:

View File

View File

@@ -0,0 +1,7 @@
{
"Framework": "CIS",
"Version": "1.0",
"Provider": "Github",
"Description": "This CIS Benchmark provides prescriptive guidance for establishing a secure configuration posture for securing the Software Supply Chain.",
"Requirements": []
}

View File

@@ -483,6 +483,20 @@ class Check_Report_Kubernetes(Check_Report):
self.namespace = ""
@dataclass
class Check_Report_Github(Check_Report):
# TODO change class name to CheckReportGitHub
"""Contains the GitHub Check's finding information."""
resource_name: str
resource_id: str
def __init__(self, metadata):
super().__init__(metadata)
self.resource_name = ""
self.resource_id = ""
# Testing Pending
def load_check_metadata(metadata_file: str) -> CheckMetadata:
"""

View File

@@ -232,6 +232,14 @@ class Finding(BaseModel):
)
output_data["region"] = f"namespace: {check_output.namespace}"
elif provider.type == "github":
output_data["auth_method"] = provider.auth_method
output_data["resource_name"] = check_output.resource_name
output_data["resource_uid"] = check_output.resource_id
output_data["account_name"] = provider.identity.account_name
output_data["account_uid"] = provider.identity.account_id
output_data["region"] = "global"
# check_output Unique ID
# TODO: move this to a function
# TODO: in Azure, GCP and K8s there are fidings without resource_name

View File

@@ -538,6 +538,51 @@ class HTML(Output):
)
return ""
@staticmethod
def get_github_assessment_summary(provider: Provider) -> str:
"""
get_github_assessment_summary gets the HTML assessment summary for the provider
Args:
provider (Provider): the provider object
Returns:
str: the HTML assessment summary
"""
try:
return f"""
<div class="col-md-2">
<div class="card">
<div class="card-header">
GitHub Assessment Summary
</div>
<ul class="list-group
list-group-flush">
<li class="list-group-item">
<b>GitHub account:</b> {provider.identity.account_name}
</li>
</ul>
</div>
</div>
<div class="col-md-4">
<div class="card">
<div class="card-header">
GitHub Credentials
</div>
<ul class="list-group
list-group-flush">
<li class="list-group-item">
<b>GitHub authentication method:</b> {provider.auth_method}
</li>
</ul>
</div>
</div>"""
except Exception as error:
logger.error(
f"{error.__class__.__name__}[{error.__traceback__.tb_lineno}] -- {error}"
)
return ""
@staticmethod
def get_assessment_summary(provider: Provider) -> str:
"""

View File

@@ -13,6 +13,8 @@ def stdout_report(finding, color, verbose, status, fix):
details = finding.location.lower()
if finding.check_metadata.Provider == "kubernetes":
details = finding.namespace.lower()
if finding.check_metadata.Provider == "github":
details = ""
if (verbose or fix) and (not status or finding.status in status):
if finding.muted:

View File

@@ -11,6 +11,7 @@ from prowler.config.config import (
orange_color,
)
from prowler.lib.logger import logger
from prowler.providers.github.models import GithubAppIdentityInfo, GithubIdentityInfo
def display_summary_table(
@@ -40,6 +41,13 @@ def display_summary_table(
elif provider.type == "kubernetes":
entity_type = "Context"
audited_entities = provider.identity.context
elif provider.type == "github":
if isinstance(provider.identity, GithubIdentityInfo):
entity_type = "User Name"
audited_entities = provider.identity.account_name
elif isinstance(provider.identity, GithubAppIdentityInfo):
entity_type = "App ID"
audited_entities = provider.identity.app_id
# Check if there are findings and that they are not all MANUAL
if findings and not all(finding.status == "MANUAL" for finding in findings):

View File

@@ -211,6 +211,14 @@ class Provider(ABC):
mutelist_path=arguments.mutelist_file,
fixer_config=fixer_config,
)
elif "github" in provider_class_name.lower():
provider_class(
personal_access_token=arguments.personal_access_token,
oauth_app_token=arguments.oauth_app_token,
github_app_key=arguments.github_app_key,
github_app_id=arguments.github_app_id,
config_path=arguments.config_file,
)
except TypeError as error:
logger.critical(

View File

View File

@@ -0,0 +1,95 @@
from prowler.exceptions.exceptions import ProwlerException
# Exceptions codes from 5000 to 5999 are reserved for Github exceptions
class GithubBaseException(ProwlerException):
"""Base class for Github Errors."""
GITHUB_ERROR_CODES = {
(5000, "GithubEnvironmentVariableError"): {
"message": "Github environment variable error",
"remediation": "Check the Github environment variables and ensure they are properly set.",
},
(5001, "GithubNonExistentTokenError"): {
"message": "A Github token is required to authenticate against Github",
"remediation": "Check the Github token and ensure it is properly set up.",
},
(5002, "GithubInvalidTokenError"): {
"message": "Github token provided is not valid",
"remediation": "Check the Github token and ensure it is valid.",
},
(5003, "GithubSetUpSessionError"): {
"message": "Error setting up session",
"remediation": "Check the session setup and ensure it is properly set up.",
},
(5004, "GithubSetUpIdentityError"): {
"message": "Github identity setup error due to bad credentials",
"remediation": "Check credentials and ensure they are properly set up for Github and the identity provider.",
},
(5005, "GithubInvalidCredentialsError"): {
"message": "Github invalid App Key or App ID for GitHub APP login",
"remediation": "Check user and password and ensure they are properly set up as in your Github account.",
},
}
def __init__(self, code, file=None, original_exception=None, message=None):
provider = "Github"
error_info = self.GITHUB_ERROR_CODES.get((code, self.__class__.__name__))
if message:
error_info["message"] = message
super().__init__(
code=code,
source=provider,
file=file,
original_exception=original_exception,
error_info=error_info,
)
class GithubCredentialsError(GithubBaseException):
"""Base class for Github credentials errors."""
def __init__(self, code, file=None, original_exception=None, message=None):
super().__init__(code, file, original_exception, message)
class GithubEnvironmentVariableError(GithubCredentialsError):
def __init__(self, file=None, original_exception=None, message=None):
super().__init__(
5000, file=file, original_exception=original_exception, message=message
)
class GithubNonExistentTokenError(GithubCredentialsError):
def __init__(self, file=None, original_exception=None, message=None):
super().__init__(
5001, file=file, original_exception=original_exception, message=message
)
class GithubInvalidTokenError(GithubCredentialsError):
def __init__(self, file=None, original_exception=None, message=None):
super().__init__(
5002, file=file, original_exception=original_exception, message=message
)
class GithubSetUpSessionError(GithubCredentialsError):
def __init__(self, file=None, original_exception=None, message=None):
super().__init__(
5003, file=file, original_exception=original_exception, message=message
)
class GithubSetUpIdentityError(GithubCredentialsError):
def __init__(self, file=None, original_exception=None, message=None):
super().__init__(
5004, file=file, original_exception=original_exception, message=message
)
class GithubInvalidCredentialsError(GithubCredentialsError):
def __init__(self, file=None, original_exception=None, message=None):
super().__init__(
5005, file=file, original_exception=original_exception, message=message
)

View File

@@ -0,0 +1,359 @@
import os
from os import environ
from colorama import Fore, Style
from github import Auth, Github, GithubIntegration
from prowler.config.config import (
default_config_file_path,
get_default_mute_file_path,
load_and_validate_config_file,
)
from prowler.lib.logger import logger
from prowler.lib.mutelist.mutelist import Mutelist
from prowler.lib.utils.utils import print_boxes
from prowler.providers.common.models import Audit_Metadata
from prowler.providers.common.provider import Provider
from prowler.providers.github.exceptions.exceptions import (
GithubEnvironmentVariableError,
GithubInvalidCredentialsError,
GithubInvalidTokenError,
GithubSetUpIdentityError,
GithubSetUpSessionError,
)
from prowler.providers.github.lib.mutelist.mutelist import GithubMutelist
from prowler.providers.github.models import (
GithubAppIdentityInfo,
GithubIdentityInfo,
GithubSession,
)
def format_rsa_key(key: str) -> str:
"""
Format an RSA private key by adding line breaks to the key body.
This function takes an RSA private key in PEM format as input and formats it by inserting line breaks every 64 characters in the key body. This formatting is necessary for the GitHub SDK Parser to correctly process the key.
Args:
key (str): The RSA private key in PEM format as a string. The key should start with "-----BEGIN RSA PRIVATE KEY-----" and end with "-----END RSA PRIVATE KEY-----".
Returns:
str: The formatted RSA private key with line breaks added to the key body. If the input key does not have the correct headers, it is returned unchanged.
Example:
>>> key = "-----BEGIN RSA PRIVATE KEY-----XXXXXXXXXXXXX...-----END RSA PRIVATE KEY-----"
>>> formatted_key = format_rsa_key(key)
>>> print(formatted_key)
-----BEGIN RSA PRIVATE KEY-----
XXXXXXXXXXXXX...
-----END RSA PRIVATE KEY-----
"""
if (
key.startswith("-----BEGIN RSA PRIVATE KEY-----")
and key.endswith("-----END RSA PRIVATE KEY-----")
and "\n" not in key
):
# Extract the key body (excluding the headers)
key_body = key[
len("-----BEGIN RSA PRIVATE KEY-----") : len(key)
- len("-----END RSA PRIVATE KEY-----")
].strip()
# Add line breaks to the body
formatted_key_body = "\n".join(
[key_body[i : i + 64] for i in range(0, len(key_body), 64)]
)
# Reconstruct the key with headers and formatted body
return f"-----BEGIN RSA PRIVATE KEY-----\n{formatted_key_body}\n-----END RSA PRIVATE KEY-----"
return key
class GithubProvider(Provider):
"""
GitHub Provider class
This class is responsible for setting up the GitHub provider, including the session, identity, audit configuration, fixer configuration, and mutelist.
Attributes:
_type (str): The type of the provider.
_auth_method (str): The authentication method used by the provider.
_session (GithubSession): The session object for the provider.
_identity (GithubIdentityInfo): The identity information for the provider.
_audit_config (dict): The audit configuration for the provider.
_fixer_config (dict): The fixer configuration for the provider.
_mutelist (Mutelist): The mutelist for the provider.
audit_metadata (Audit_Metadata): The audit metadata for the provider.
"""
_type: str = "github"
_auth_method: str = None
_session: GithubSession
_identity: GithubIdentityInfo
_audit_config: dict
_mutelist: Mutelist
audit_metadata: Audit_Metadata
def __init__(
self,
# Authentication credentials
personal_access_token: str = "",
oauth_app_token: str = "",
github_app_key: str = "",
github_app_id: int = 0,
# Provider configuration
config_path: str = None,
config_content: dict = None,
fixer_config: dict = {},
mutelist_path: str = None,
mutelist_content: dict = None,
):
"""
GitHub Provider constructor
Args:
personal_access_token (str): GitHub personal access token.
oauth_app_token (str): GitHub OAuth App token.
github_app_key (str): GitHub App key.
github_app_id (int): GitHub App ID.
config_path (str): Path to the audit configuration file.
config_content (dict): Audit configuration content.
fixer_config (dict): Fixer configuration content.
mutelist_path (str): Path to the mutelist file.
mutelist_content (dict): Mutelist content.
"""
logger.info("Instantiating GitHub Provider...")
self._session = self.setup_session(
personal_access_token,
oauth_app_token,
github_app_id,
github_app_key,
)
self._identity = self.setup_identity()
# Audit Config
if config_content:
self._audit_config = config_content
else:
if not config_path:
config_path = default_config_file_path
self._audit_config = load_and_validate_config_file(self._type, config_path)
# Fixer Config
self._fixer_config = fixer_config
# Mutelist
if mutelist_content:
self._mutelist = GithubMutelist(
mutelist_content=mutelist_content,
)
else:
if not mutelist_path:
mutelist_path = get_default_mute_file_path(self.type)
self._mutelist = GithubMutelist(
mutelist_path=mutelist_path,
)
Provider.set_global_provider(self)
@property
def auth_method(self):
"""Returns the authentication method for the GitHub provider."""
return self._auth_method
@property
def pat(self):
"""Returns the personal access token for the GitHub provider."""
return self._pat
@property
def session(self):
"""Returns the session object for the GitHub provider."""
return self._session
@property
def identity(self):
"""Returns the identity information for the GitHub provider."""
return self._identity
@property
def type(self):
"""Returns the type of the GitHub provider."""
return self._type
@property
def audit_config(self):
return self._audit_config
@property
def fixer_config(self):
return self._fixer_config
@property
def mutelist(self) -> GithubMutelist:
"""
mutelist method returns the provider's mutelist.
"""
return self._mutelist
def setup_session(
self,
personal_access_token: str = None,
oauth_app_token: str = None,
github_app_id: int = 0,
github_app_key: str = None,
) -> GithubSession:
"""
Returns the GitHub headers responsible authenticating API calls.
Args:
personal_access_token (str): GitHub personal access token.
oauth_app_token (str): GitHub OAuth App token.
github_app_id (int): GitHub App ID.
github_app_key (str): GitHub App key.
Returns:
GithubSession: Authenticated session token for API requests.
"""
session_token = ""
app_key = ""
app_id = 0
try:
# Ensure that at least one authentication method is selected. Default to environment variable for PAT if none is provided.
if personal_access_token:
session_token = personal_access_token
self._auth_method = "Personal Access Token"
elif oauth_app_token:
session_token = oauth_app_token
self._auth_method = "OAuth App Token"
elif github_app_id and github_app_key:
app_id = github_app_id
with open(github_app_key, "r") as rsa_key:
app_key = rsa_key.read()
self._auth_method = "GitHub App Token"
else:
# PAT
logger.info(
"Looking for GITHUB_PERSONAL_ACCESS_TOKEN environment variable as user has not provided any token...."
)
session_token = environ.get("GITHUB_PERSONAL_ACCESS_TOKEN", "")
if session_token:
self._auth_method = "Environment Variable for Personal Access Token"
if not session_token:
# OAUTH
logger.info(
"Looking for GITHUB_OAUTH_APP_TOKEN environment variable as user has not provided any token...."
)
session_token = environ.get("GITHUB_OAUTH_APP_TOKEN", "")
if session_token:
self._auth_method = "Environment Variable for OAuth App Token"
if not session_token:
# APP
logger.info(
"Looking for GITHUB_APP_ID and GITHUB_APP_KEY environment variables as user has not provided any token...."
)
app_id = environ.get("GITHUB_APP_ID", "")
app_key = format_rsa_key(environ.get(r"GITHUB_APP_KEY", ""))
if app_id and app_key:
self._auth_method = (
"Environment Variables for GitHub App Key and ID"
)
if not self._auth_method:
raise GithubEnvironmentVariableError(
file=os.path.basename(__file__),
message="No authentication method selected and not environment variables were found.",
)
credentials = GithubSession(
token=session_token,
key=app_key,
id=app_id,
)
return credentials
except Exception as error:
logger.critical(
f"{error.__class__.__name__}[{error.__traceback__.tb_lineno}] -- {error}"
)
raise GithubSetUpSessionError(
original_exception=error,
)
def setup_identity(
self,
) -> GithubIdentityInfo | GithubAppIdentityInfo:
"""
Returns the GitHub identity information
Returns:
GithubIdentityInfo | GithubAppIdentityInfo: An instance of GithubIdentityInfo or GithubAppIdentityInfo containing the identity information.
"""
credentials = self.session
try:
if credentials.token:
auth = Auth.Token(credentials.token)
g = Github(auth=auth)
try:
identity = GithubIdentityInfo(
account_id=g.get_user().id,
account_name=g.get_user().login,
account_url=g.get_user().url,
)
return identity
except Exception as error:
raise GithubInvalidTokenError(
original_exception=error,
)
elif credentials.id != 0 and credentials.key:
auth = Auth.AppAuth(credentials.id, credentials.key)
gi = GithubIntegration(auth=auth)
try:
identity = GithubAppIdentityInfo(app_id=gi.get_app().id)
return identity
except Exception as error:
raise GithubInvalidCredentialsError(
original_exception=error,
)
except Exception as error:
logger.critical(
f"{error.__class__.__name__}[{error.__traceback__.tb_lineno}] -- {error}"
)
raise GithubSetUpIdentityError(
original_exception=error,
)
def print_credentials(self):
"""
Prints the GitHub credentials.
Usage:
>>> self.print_credentials()
"""
if isinstance(self.identity, GithubIdentityInfo):
report_lines = [
f"GitHub Account: {Fore.YELLOW}{self.identity.account_name}{Style.RESET_ALL}",
f"GitHub Account ID: {Fore.YELLOW}{self.identity.account_id}{Style.RESET_ALL}",
f"Authentication Method: {Fore.YELLOW}{self.auth_method}{Style.RESET_ALL}",
]
elif isinstance(self.identity, GithubAppIdentityInfo):
report_lines = [
f"GitHub App ID: {Fore.YELLOW}{self.identity.app_id}{Style.RESET_ALL}",
f"Authentication Method: {Fore.YELLOW}{self.auth_method}{Style.RESET_ALL}",
]
report_title = (
f"{Style.BRIGHT}Using the GitHub credentials below:{Style.RESET_ALL}"
)
print_boxes(report_lines, report_title)

View File

@@ -0,0 +1,34 @@
def init_parser(self):
"""Init the Github Provider CLI parser"""
github_parser = self.subparsers.add_parser(
"github", parents=[self.common_providers_parser], help="GitHub Provider"
)
github_auth_subparser = github_parser.add_argument_group("Authentication Modes")
# Authentication Modes
github_auth_subparser.add_argument(
"--personal-access-token",
nargs="?",
help="Personal Access Token to log in against GitHub",
default=None,
)
github_auth_subparser.add_argument(
"--oauth-app-token",
nargs="?",
help="OAuth App Token to log in against GitHub",
default=None,
)
# GitHub App Authentication
github_auth_subparser.add_argument(
"--github-app-id",
nargs="?",
help="GitHub App ID to log in against GitHub",
default=None,
)
github_auth_subparser.add_argument(
"--github-app-key",
nargs="?",
help="GitHub App Key Path to log in against GitHub",
default=None,
)

View File

@@ -0,0 +1,17 @@
from prowler.lib.check.models import Check_Report_Github
from prowler.lib.mutelist.mutelist import Mutelist
from prowler.lib.outputs.utils import unroll_dict, unroll_tags
class GithubMutelist(Mutelist):
def is_finding_muted(
self,
finding: Check_Report_Github,
) -> bool:
return self.is_muted(
finding.account_name,
finding.check_metadata.CheckID,
finding.location,
finding.resource_name,
unroll_dict(unroll_tags(finding.resource_tags)),
)

View File

@@ -0,0 +1,41 @@
from github import Auth, Github, GithubIntegration
from prowler.lib.logger import logger
from prowler.providers.github.github_provider import GithubProvider
class GithubService:
def __init__(
self,
service: str,
provider: GithubProvider,
):
self.clients = self.__set_clients__(
provider.session,
)
self.audit_config = provider.audit_config
self.fixer_config = provider.fixer_config
def __set_clients__(self, session):
clients = []
try:
if session.token:
auth = Auth.Token(session.token)
clients = [Github(auth=auth)]
elif session.key and session.id:
auth = Auth.AppAuth(
session.id,
session.key,
)
gi = GithubIntegration(auth=auth)
for installation in gi.get_installations():
clients.append(installation.get_github_for_installation())
except Exception as error:
logger.error(
f"{error.__class__.__name__}[{error.__traceback__.tb_lineno}]: {error}"
)
return clients

View File

@@ -0,0 +1,42 @@
from pydantic import BaseModel
from prowler.config.config import output_file_timestamp
from prowler.providers.common.models import ProviderOutputOptions
class GithubSession(BaseModel):
token: str
key: str
id: str
class GithubIdentityInfo(BaseModel):
account_id: str
account_name: str
account_url: str
class GithubAppIdentityInfo(BaseModel):
app_id: str
class GithubOutputOptions(ProviderOutputOptions):
def __init__(self, arguments, bulk_checks_metadata, identity):
# First call ProviderOutputOptions init
super().__init__(arguments, bulk_checks_metadata)
# TODO move the below if to ProviderOutputOptions
# Check if custom output filename was input, if not, set the default
if (
not hasattr(arguments, "output_filename")
or arguments.output_filename is None
):
if isinstance(identity, GithubIdentityInfo):
self.output_filename = (
f"prowler-output-{identity.account_name}-{output_file_timestamp}"
)
elif isinstance(identity, GithubAppIdentityInfo):
self.output_filename = (
f"prowler-output-{identity.app_id}-{output_file_timestamp}"
)
else:
self.output_filename = arguments.output_filename

View File

@@ -0,0 +1,4 @@
from prowler.providers.common.provider import Provider
from prowler.providers.github.services.repository.repository_service import Repository
repository_client = Repository(Provider.get_global_provider())

View File

@@ -0,0 +1,30 @@
{
"Provider": "github",
"CheckID": "repository_code_changes_multi_approval_requirement",
"CheckTitle": "Check if repositories require at least 2 code changes approvals",
"CheckType": [],
"ServiceName": "repository",
"SubServiceName": "",
"ResourceIdTemplate": "github:user-id:repository/repository-name",
"Severity": "high",
"ResourceType": "Other",
"Description": "Ensure that repositories require at least 2 code changes approvals before merging a pull request.",
"Risk": "If repositories do not require at least 2 code changes approvals before merging a pull request, it is possible that code changes are not being reviewed by multiple people, which could lead to the introduction of bugs or security vulnerabilities.",
"RelatedUrl": "https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/reviewing-changes-in-pull-requests/approving-a-pull-request-with-required-reviews",
"Remediation": {
"Code": {
"CLI": "",
"NativeIaC": "",
"Other": "",
"Terraform": ""
},
"Recommendation": {
"Text": "To require at least 2 code changes approvals before merging a pull request, navigate to the repository settings, click on 'Branches', and then 'Add rule'.",
"Url": "https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-protected-branches/about-protected-branches#require-pull-request-reviews-before-merging"
}
},
"Categories": [],
"DependsOn": [],
"RelatedTo": [],
"Notes": ""
}

View File

@@ -0,0 +1,40 @@
from typing import List
from prowler.lib.check.models import Check, Check_Report_Github
from prowler.providers.github.services.repository.repository_client import (
repository_client,
)
class repository_code_changes_multi_approval_requirement(Check):
"""Check if a repository enforces at least 2 approvals for code changes
This class verifies whether each repository enforces at least 2 approvals for code changes.
"""
def execute(self) -> List[Check_Report_Github]:
"""Execute the Github Repository code changes enforce multi approval requirement check
Iterates over each repository and checks if the repository enforces at least 2 approvals for code changes.
Returns:
List[Check_Report_Github]: A list of reports for each repository
"""
findings = []
for repo in repository_client.repositories.values():
report = Check_Report_Github(self.metadata())
report.resource_id = repo.id
report.resource_name = repo.name
report.status = "FAIL"
report.status_extended = f"Repository {repo.name} does not enforce at least 2 approvals for code changes."
if (
repo.default_branch_protection
and repo.default_branch_protection.approval_count >= 2
):
report.status = "PASS"
report.status_extended = f"Repository {repo.name} does enforce at least 2 approvals for code changes."
findings.append(report)
return findings

View File

@@ -0,0 +1,30 @@
{
"Provider": "github",
"CheckID": "repository_deletes_branch_on_merge",
"CheckTitle": "Check if a repository deletes the branch after merging",
"CheckType": [],
"ServiceName": "repository",
"SubServiceName": "",
"ResourceIdTemplate": "",
"Severity": "medium",
"ResourceType": "Other",
"Description": "Ensure that the repository deletes the branch after merging.",
"Risk": "Inactive branches pose a security risk as they can accumulate outdated code, dependencies, and potential vulnerabilities over time. Malicious actors may exploit these branches, and they can clutter the repository, making it harder to manage and track the active code. Additionally, stale branches may unintentionally be accessed or used inappropriately, leading to potential security breaches.",
"RelatedUrl": "https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-protected-branches/about-protected-branches",
"Remediation": {
"Code": {
"CLI": "",
"NativeIaC": "",
"Other": "",
"Terraform": ""
},
"Recommendation": {
"Text": "Regularly review and remove inactive branches from your repositories. This helps reduce the risk of malicious code injection, sensitive data leaks, and unnecessary clutter in the repository. By keeping branches active and up to date, you ensure that your codebase remains secure and manageable.",
"Url": "https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/configuring-pull-request-merges/managing-the-automatic-deletion-of-branches"
}
},
"Categories": [],
"DependsOn": [],
"RelatedTo": [],
"Notes": ""
}

View File

@@ -0,0 +1,41 @@
from typing import List
from prowler.lib.check.models import Check, Check_Report_Github
from prowler.providers.github.services.repository.repository_client import (
repository_client,
)
class repository_deletes_branch_on_merge(Check):
"""Check if a repository deletes branches on merge
This class verifies whether each repository deletes branches on merge.
"""
def execute(self) -> List[Check_Report_Github]:
"""Execute the Github Repository Deletes Branch On Merge check
Iterates over all repositories and checks if they delete branches on merge.
Returns:
List[Check_Report_Github]: A list of reports for each repository
"""
findings = []
for repo in repository_client.repositories.values():
report = Check_Report_Github(self.metadata())
report.resource_id = repo.id
report.resource_name = repo.name
report.status = "FAIL"
report.status_extended = (
f"Repository {repo.name} does not delete branches on merge."
)
if repo.delete_branch_on_merge:
report.status = "PASS"
report.status_extended = (
f"Repository {repo.name} does delete branches on merge."
)
findings.append(report)
return findings

View File

@@ -0,0 +1,30 @@
{
"Provider": "github",
"CheckID": "repository_denies_branch_deletion",
"CheckTitle": "Check if a repository denies branch deletion",
"CheckType": [],
"ServiceName": "repository",
"SubServiceName": "",
"ResourceIdTemplate": "",
"Severity": "high",
"ResourceType": "Other",
"Description": "Ensure that the repository denies branch deletion.",
"Risk": "Allowing the deletion of protected branches by users with push access increases the risk of accidental or intentional branch removal, potentially resulting in significant data loss or disruption to the development process.",
"RelatedUrl": "https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-protected-branches/about-protected-branches#allow-deletions",
"Remediation": {
"Code": {
"CLI": "",
"NativeIaC": "",
"Other": "",
"Terraform": ""
},
"Recommendation": {
"Text": "Deny the ability to delete protected branches to ensure the preservation of critical branch data. This prevents accidental or malicious deletions and helps maintain the integrity and stability of the repository.",
"Url": "https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-protected-branches/managing-a-branch-protection-rule"
}
},
"Categories": [],
"DependsOn": [],
"RelatedTo": [],
"Notes": ""
}

View File

@@ -0,0 +1,44 @@
from typing import List
from prowler.lib.check.models import Check, Check_Report_Github
from prowler.providers.github.services.repository.repository_client import (
repository_client,
)
class repository_denies_branch_deletion(Check):
"""Check if a repository denies branch deletion
This class verifies whether each repository denies branch deletion.
"""
def execute(self) -> List[Check_Report_Github]:
"""Execute the Github Repository Denies Branch Deletion check
Iterates over all repositories and checks if they deny branch deletion.
Returns:
List[Check_Report_Github]: A list of reports for each repository
"""
findings = []
for repo in repository_client.repositories.values():
report = Check_Report_Github(self.metadata())
report.resource_id = repo.id
report.resource_name = repo.name
report.status = "FAIL"
report.status_extended = (
f"Repository {repo.name} does allow branch deletion."
)
if (
repo.default_branch_protection
and not repo.default_branch_protection.allow_branch_deletion
):
report.status = "PASS"
report.status_extended = (
f"Repository {repo.name} does deny branch deletion."
)
findings.append(report)
return findings

View File

@@ -0,0 +1,30 @@
{
"Provider": "github",
"CheckID": "repository_denies_force_push",
"CheckTitle": "Check if repository denies force push",
"CheckType": [],
"ServiceName": "repository",
"SubServiceName": "",
"ResourceIdTemplate": "",
"Severity": "high",
"ResourceType": "Other",
"Description": "Ensure that the repository denies force push to protected branches.",
"Risk": "Permitting force pushes to branches can lead to accidental or intentional overwrites of the commit history, resulting in potential data loss, code inconsistencies, or the introduction of malicious changes. This compromises the stability and security of the repository.",
"RelatedUrl": "https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-protected-branches/about-protected-branches#allow-force-pushes",
"Remediation": {
"Code": {
"CLI": "",
"NativeIaC": "",
"Other": "",
"Terraform": ""
},
"Recommendation": {
"Text": "Disable force pushes on protected branches to preserve the commit history and ensure the integrity of the repository. This measure helps prevent unintentional data loss and protects the repository from malicious changes.",
"Url": "https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-protected-branches/managing-a-branch-protection-rule"
}
},
"Categories": [],
"DependsOn": [],
"RelatedTo": [],
"Notes": ""
}

View File

@@ -0,0 +1,40 @@
from typing import List
from prowler.lib.check.models import Check, Check_Report_Github
from prowler.providers.github.services.repository.repository_client import (
repository_client,
)
class repository_denies_force_push(Check):
"""Check if a repository denies force push
This class verifies whether each repository denies force push.
"""
def execute(self) -> List[Check_Report_Github]:
"""Execute the Github Repository Denies Force Push check
Iterates over all repositories and checks if they deny force push.
Returns:
List[Check_Report_Github]: A list of reports for each repository
"""
findings = []
for repo in repository_client.repositories.values():
report = Check_Report_Github(self.metadata())
report.resource_id = repo.id
report.resource_name = repo.name
report.status = "FAIL"
report.status_extended = f"Repository {repo.name} does allow force push."
if (
repo.default_branch_protection
and not repo.default_branch_protection.allow_force_push
):
report.status = "PASS"
report.status_extended = f"Repository {repo.name} does deny force push."
findings.append(report)
return findings

View File

@@ -0,0 +1,30 @@
{
"Provider": "github",
"CheckID": "repository_enforces_admin_branch_protection",
"CheckTitle": "Check if repository enforces admin branch protection",
"CheckType": [],
"ServiceName": "repository",
"SubServiceName": "",
"ResourceIdTemplate": "",
"Severity": "high",
"ResourceType": "Other",
"Description": "Ensure that the repository enforces branch protection rules for administrators.",
"Risk": "Excluding administrators from branch protection rules introduces a significant risk of unauthorized or unreviewed changes being pushed to protected branches. This can lead to vulnerabilities, including the potential insertion of malicious code, especially if an administrator account is compromised.",
"RelatedUrl": "https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-protected-branches/about-protected-branches#do-not-allow-bypassing-the-above-settings",
"Remediation": {
"Code": {
"CLI": "",
"NativeIaC": "",
"Other": "",
"Terraform": ""
},
"Recommendation": {
"Text": "Enforce branch protection rules for administrators to ensure they adhere to the same security and quality standards as other users. This mitigates the risk of unreviewed or untrusted code being introduced, enhancing the overall integrity of the codebase.",
"Url": "https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-protected-branches/managing-a-branch-protection-rule"
}
},
"Categories": [],
"DependsOn": [],
"RelatedTo": [],
"Notes": ""
}

View File

@@ -0,0 +1,40 @@
from typing import List
from prowler.lib.check.models import Check, Check_Report_Github
from prowler.providers.github.services.repository.repository_client import (
repository_client,
)
class repository_enforces_admin_branch_protection(Check):
"""Check if a repository enforces administrators to be subject to the same branch protection rules as other users
This class verifies whether each repository enforces administrators to be subject to the same branch protection rules as other users.
"""
def execute(self) -> List[Check_Report_Github]:
"""Execute the Github Repository Enforces Admin Branch Protection check
Iterates over all repositories and checks if they enforce administrators to be subject to the same branch protection rules as other users.
Returns:
List[Check_Report_Github]: A list of reports for each repository.
"""
findings = []
for repo in repository_client.repositories.values():
report = Check_Report_Github(self.metadata())
report.resource_id = repo.id
report.resource_name = repo.name
report.status = "FAIL"
report.status_extended = f"Repository {repo.name} does not enforce administrators to be subject to the same branch protection rules as other users."
if (
repo.default_branch_protection
and repo.default_branch_protection.enforce_admins
):
report.status = "PASS"
report.status_extended = f"Repository {repo.name} does enforce administrators to be subject to the same branch protection rules as other users."
findings.append(report)
return findings

View File

@@ -0,0 +1,30 @@
{
"Provider": "github",
"CheckID": "repository_enforces_default_branch_protection",
"CheckTitle": "Check if branch protection is enforced on the default branch ",
"CheckType": [],
"ServiceName": "repository",
"SubServiceName": "",
"ResourceIdTemplate": "github:user-id:repository/repository-name",
"Severity": "critical",
"ResourceType": "Other",
"Description": "Ensure branch protection is enforced on the default branch",
"Risk": "The absence of branch protection on the default branch increases the risk of unauthorized, unreviewed, or untested changes being merged. This can compromise the stability, security, and reliability of the codebase, which is especially critical for production deployments.",
"RelatedUrl": "https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-protected-branches/about-protected-branches",
"Remediation": {
"Code": {
"CLI": "",
"NativeIaC": "",
"Other": "",
"Terraform": ""
},
"Recommendation": {
"Text": "Apply branch protection rules to the default branch to ensure it is safeguarded against unauthorized or improper modifications. This helps maintain code quality, enforces proper review and testing procedures, and reduces the risk of accidental or malicious changes.",
"Url": "https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-protected-branches/managing-a-branch-protection-rule#creating-a-branch-protection-rule"
}
},
"Categories": [],
"DependsOn": [],
"RelatedTo": [],
"Notes": ""
}

View File

@@ -0,0 +1,37 @@
from typing import List
from prowler.lib.check.models import Check, Check_Report_Github
from prowler.providers.github.services.repository.repository_client import (
repository_client,
)
class repository_enforces_default_branch_protection(Check):
"""Check if a repository enforces default branch protection
This class verifies whether each repository enforces default branch protection.
"""
def execute(self) -> List[Check_Report_Github]:
"""Execute the Github Repository Enforces Default Branch Protection check
Iterates over all repositories and checks if they enforce default branch protection.
Returns:
List[Check_Report_Github]: A list of reports for each repository
"""
findings = []
for repo in repository_client.repositories.values():
report = Check_Report_Github(self.metadata())
report.resource_id = repo.id
report.resource_name = repo.name
report.status = "FAIL"
report.status_extended = f"Repository {repo.name} does not enforce branch protection on default branch ({repo.default_branch})."
if repo.default_branch_protection:
report.status = "PASS"
report.status_extended = f"Repository {repo.name} does enforce branch protection on default branch ({repo.default_branch})."
findings.append(report)
return findings

View File

@@ -0,0 +1,30 @@
{
"Provider": "github",
"CheckID": "repository_enforces_status_checks",
"CheckTitle": "Check if repository enforces status checks to pass",
"CheckType": [],
"ServiceName": "repository",
"SubServiceName": "",
"ResourceIdTemplate": "",
"Severity": "high",
"ResourceType": "Other",
"Description": "Ensure that the repository enforces status checks to pass before merging code into the main branch.",
"Risk": "Merging code without requiring all checks to pass increases the risk of introducing bugs, vulnerabilities, or unstable changes into the codebase. This can compromise the quality, security, and functionality of the application.",
"RelatedUrl": "https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-protected-branches/about-protected-branches#require-status-checks-before-merging",
"Remediation": {
"Code": {
"CLI": "",
"NativeIaC": "",
"Other": "",
"Terraform": ""
},
"Recommendation": {
"Text": "Require all predefined status checks to pass successfully before allowing code changes to be merged. This ensures that all quality, stability, and security conditions are met, reducing the likelihood of errors or vulnerabilities being introduced into the project.",
"Url": "https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-protected-branches/managing-a-branch-protection-rule"
}
},
"Categories": [],
"DependsOn": [],
"RelatedTo": [],
"Notes": ""
}

View File

@@ -0,0 +1,44 @@
from typing import List
from prowler.lib.check.models import Check, Check_Report_Github
from prowler.providers.github.services.repository.repository_client import (
repository_client,
)
class repository_enforces_status_checks(Check):
"""Check if a repository enforces status checks.
This class verifies whether each repository enforces status checks.
"""
def execute(self) -> List[Check_Report_Github]:
"""Execute the Github Repository
Iterates over all repositories and checks if they enforce status checks.
Returns:
List[Check_Report_Github]: A list of reports for each repository.
"""
findings = []
for repo in repository_client.repositories.values():
report = Check_Report_Github(self.metadata())
report.resource_id = repo.id
report.resource_name = repo.name
report.status = "FAIL"
report.status_extended = (
f"Repository {repo.name} does not enforce status checks."
)
if (
repo.default_branch_protection
and repo.default_branch_protection.enforce_status_checks
):
report.status = "PASS"
report.status_extended = (
f"Repository {repo.name} does enforce status checks."
)
findings.append(report)
return findings

View File

@@ -0,0 +1,30 @@
{
"Provider": "github",
"CheckID": "repository_merging_requires_conversation_resolution",
"CheckTitle": "Check if repository requires conversation resolution before merging",
"CheckType": [],
"ServiceName": "repository",
"SubServiceName": "",
"ResourceIdTemplate": "",
"Severity": "medium",
"ResourceType": "Other",
"Description": "Ensure that the repository requires conversation resolution before merging.",
"Risk": "Leaving comments unresolved before merging code can lead to overlooked issues, including potential bugs or security vulnerabilities, that might affect the quality and security of the codebase. Unaddressed concerns could result in a lower quality of code, increasing the risk of production failures or breaches.",
"RelatedUrl": "https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-protected-branches/about-protected-branches#require-conversation-resolution-before-merging",
"Remediation": {
"Code": {
"CLI": "",
"NativeIaC": "",
"Other": "",
"Terraform": ""
},
"Recommendation": {
"Text": "Ensure that all comments in a code change proposal are resolved before merging. This guarantees that every reviewers concern is addressed, improving code quality and security by preventing issues from being ignored or overlooked.",
"Url": "https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-protected-branches/managing-a-branch-protection-rule"
}
},
"Categories": [],
"DependsOn": [],
"RelatedTo": [],
"Notes": ""
}

View File

@@ -0,0 +1,44 @@
from typing import List
from prowler.lib.check.models import Check, Check_Report_Github
from prowler.providers.github.services.repository.repository_client import (
repository_client,
)
class repository_merging_requires_conversation_resolution(Check):
"""Check if a repository requires conversation resolution
This class verifies whether each repository requires conversation resolution.
"""
def execute(self) -> List[Check_Report_Github]:
"""Execute the Github Repository Merging Requires Conversation Resolution check
Iterates over all repositories and checks if they require conversation resolution.
Returns:
List[Check_Report_Github]: A list of reports for each repository
"""
findings = []
for repo in repository_client.repositories.values():
report = Check_Report_Github(self.metadata())
report.resource_id = repo.id
report.resource_name = repo.name
report.status = "FAIL"
report.status_extended = (
f"Repository {repo.name} does not require conversation resolution."
)
if (
repo.default_branch_protection
and repo.default_branch_protection.conversation_resolution
):
report.status = "PASS"
report.status_extended = (
f"Repository {repo.name} does require conversation resolution."
)
findings.append(report)
return findings

View File

@@ -0,0 +1,30 @@
{
"Provider": "github",
"CheckID": "repository_merging_requires_linear_history",
"CheckTitle": "Check if repository default branch requires linear history",
"CheckType": [],
"ServiceName": "repository",
"SubServiceName": "",
"ResourceIdTemplate": "",
"Severity": "medium",
"ResourceType": "Other",
"Description": "Ensure that the repository default branch requires linear history.",
"Risk": "Allowing non-linear history can result in a cluttered and difficult-to-trace Git history, making it harder to identify specific changes, debug issues, and understand the sequence of development. This increases the risk of errors, inconsistencies, and bugs, especially in production environments.",
"RelatedUrl": "https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-protected-branches/about-protected-branches#require-linear-history",
"Remediation": {
"Code": {
"CLI": "",
"NativeIaC": "",
"Other": "",
"Terraform": ""
},
"Recommendation": {
"Text": "Enforce a linear history by requiring rebase or squash merges for pull requests. This will create a clean, chronological commit history, making it easier to track changes, revert modifications, and troubleshoot any issues that arise.",
"Url": "https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-protected-branches/managing-a-branch-protection-rule"
}
},
"Categories": [],
"DependsOn": [],
"RelatedTo": [],
"Notes": ""
}

View File

@@ -0,0 +1,40 @@
from typing import List
from prowler.lib.check.models import Check, Check_Report_Github
from prowler.providers.github.services.repository.repository_client import (
repository_client,
)
class repository_merging_requires_linear_history(Check):
"""Check if a repository requires linear history on default branch
This class verifies whether each repository requires linear history on the default branch.
"""
def execute(self) -> List[Check_Report_Github]:
"""Execute the Github Repository Merging Requires Linear History check
Iterates over all repositories and checks if they require linear history on the default branch.
Returns:
List[Check_Report_Github]: A list of reports for each repository
"""
findings = []
for repo in repository_client.repositories.values():
report = Check_Report_Github(self.metadata())
report.resource_id = repo.id
report.resource_name = repo.name
report.status = "FAIL"
report.status_extended = f"Repository {repo.name} does not require linear history on default branch ({repo.default_branch})."
if (
repo.default_branch_protection
and repo.default_branch_protection.linear_history
):
report.status = "PASS"
report.status_extended = f"Repository {repo.name} does require linear history on default branch ({repo.default_branch})."
findings.append(report)
return findings

View File

@@ -0,0 +1,30 @@
{
"Provider": "github",
"CheckID": "repository_public_has_securitymd_file",
"CheckTitle": "Check if public repositories have a SECURITY.md file",
"CheckType": [],
"ServiceName": "repository",
"SubServiceName": "",
"ResourceIdTemplate": "github:user-id:repository/repository-name",
"Severity": "low",
"ResourceType": "Other",
"Description": "Ensure that public repositories have a SECURITY.md file.",
"Risk": "Not having a SECURITY.md file in a public repository may lead to security vulnerabilities being overlooked by users and contributors.",
"RelatedUrl": "https://docs.github.com/en/code-security/getting-started/quickstart-for-securing-your-repository",
"Remediation": {
"Code": {
"CLI": "",
"NativeIaC": "",
"Other": "",
"Terraform": ""
},
"Recommendation": {
"Text": "Add a SECURITY.md file to the root of the repository. The file should contain information on how to report a security vulnerability, the security policy of the repository, and any other relevant information.",
"Url": "https://docs.github.com/en/code-security/getting-started/adding-a-security-policy-to-your-repository"
}
},
"Categories": [],
"DependsOn": [],
"RelatedTo": [],
"Notes": ""
}

View File

@@ -0,0 +1,42 @@
from typing import List
from prowler.lib.check.models import Check, Check_Report_Github
from prowler.providers.github.services.repository.repository_client import (
repository_client,
)
class repository_public_has_securitymd_file(Check):
"""Check if a public repository has a SECURITY.md file
This class verifies whether each public repository has a SECURITY.md file.
"""
def execute(self) -> List[Check_Report_Github]:
"""Execute the Github Repository Public Has SECURITY.md File check
Iterates over all public repositories and checks if they have a SECURITY.md file.
Returns:
List[Check_Report_Github]: A list of reports for each repository
"""
findings = []
for repo in repository_client.repositories.values():
if not repo.private:
report = Check_Report_Github(self.metadata())
report.resource_id = repo.id
report.resource_name = repo.name
report.status = "PASS"
report.status_extended = (
f"Repository {repo.name} does have a SECURITY.md file."
)
if not repo.securitymd:
report.status = "FAIL"
report.status_extended = (
f"Repository {repo.name} does not have a SECURITY.md file."
)
findings.append(report)
return findings

View File

@@ -0,0 +1,30 @@
{
"Provider": "github",
"CheckID": "repository_scans_packages_vulnerabilities",
"CheckTitle": "Check if repositories scan packages for vulnerabilities",
"CheckType": [],
"ServiceName": "repository",
"SubServiceName": "",
"ResourceIdTemplate": "github:user-id:repository/repository-name",
"Severity": "high",
"ResourceType": "Other",
"Description": "Ensure that repositories scan packages for vulnerabilities to detect and remediate open-source vulnerabilities.",
"Risk": "Open-source vulnerabilities may exist in or be discovered for the packages an organization uses. These vulnerabilities can be exploited by attackers, potentially compromising the security of applications. Without proper monitoring, vulnerabilities affecting dependencies may go unnoticed, increasing the risk of breaches or failures in production environments.",
"RelatedUrl": "https://docs.github.com/en/code-security/dependabot/working-with-dependabot",
"Remediation": {
"Code": {
"CLI": "",
"NativeIaC": "",
"Other": "",
"Terraform": ""
},
"Recommendation": {
"Text": "Implement and enforce tools to detect, monitor, and remediate open-source vulnerabilities. Enable GitHub's Dependabot alerts to track known issues, and consider integrating additional solutions to ensure comprehensive identification of vulnerabilities. This proactive approach mitigates security risks and helps maintain application stability and integrity.",
"Url": "https://docs.github.com/en/code-security/getting-started/dependabot-quickstart-guide"
}
},
"Categories": [],
"DependsOn": [],
"RelatedTo": [],
"Notes": ""
}

View File

@@ -0,0 +1,37 @@
from typing import List
from prowler.lib.check.models import Check, Check_Report_Github
from prowler.providers.github.services.repository.repository_client import (
repository_client,
)
class repository_scans_packages_vulnerabilities(Check):
"""Check if a repository scans packages for vulnerabilities
This class verifies whether each public repository scans packages for vulnerabilities.
"""
def execute(self) -> List[Check_Report_Github]:
"""Execute the Github Repository Scans Packages Vulnerabilities check
Iterates over all repositories and checks if they scan packages for vulnerabilities.
Returns:
List[Check_Report_Github]: A list of reports for each repository
"""
findings = []
for repo in repository_client.repositories.values():
report = Check_Report_Github(self.metadata())
report.resource_id = repo.id
report.resource_name = repo.name
report.status = "FAIL"
report.status_extended = f"Repository {repo.name} does not scan vulnerabilities in used packages."
if repo.dependabot_enabled:
report.status = "PASS"
report.status_extended = f"Repository {repo.name} does scan vulnerabilities in used packages."
findings.append(report)
return findings

View File

@@ -0,0 +1,137 @@
from typing import Optional
from pydantic import BaseModel
from prowler.lib.logger import logger
from prowler.providers.github.lib.service.service import GithubService
class Repository(GithubService):
def __init__(self, provider):
super().__init__(__class__.__name__, provider)
self.repositories = self._list_repositories()
def _list_repositories(self):
logger.info("Repository - Listing Repositories...")
repos = {}
try:
for client in self.clients:
for repo in client.get_user().get_repos():
if not repo.private: # Only for testing purposes
default_branch = repo.default_branch
securitymd_exists = False
try:
securitymd_exists = (
repo.get_contents("SECURITY.md") is not None
)
except Exception as e:
logger.warning(
f"Could not find SECURITY.md for repo {repo.name}: {e}"
)
delete_branch_on_merge = (
repo.delete_branch_on_merge
if repo.delete_branch_on_merge is not None
else False
)
dependabot_status = False
try:
dependabot_status = (
repo.security_and_analysis.dependabot_security_updates.status
== "enabled"
)
except Exception as e:
logger.warning(
f"Could not determine dependabot status for repo {repo.name}: {e}"
)
branch_protection = None
try:
branch = repo.get_branch(default_branch)
if branch.protected:
protection = branch.get_protection()
if protection:
require_pr = (
protection.required_pull_request_reviews
is not None
)
approval_cnt = (
protection.required_pull_request_reviews.required_approving_review_count
if require_pr
else 0
)
linear_history = protection.required_linear_history
allow_force_push = protection.allow_force_pushes
allow_branch_deletion = protection.allow_deletions
enforce_status_checks = (
protection.required_status_checks.strict
if protection.required_status_checks
else False
)
enforce_admins = protection.enforce_admins
conversation_resolution = (
protection.required_conversation_resolution
)
branch_protection = Protection(
require_pull_request=require_pr,
approval_count=approval_cnt,
linear_history=linear_history,
allow_force_push=allow_force_push,
allow_branch_deletion=allow_branch_deletion,
enforce_status_checks=enforce_status_checks,
enforce_admins=enforce_admins,
conversation_resolution=conversation_resolution,
)
except Exception as e:
logger.warning(
f"Could not get branch protection for repo {repo.name}: {e}"
)
repos[repo.id] = Repo(
id=repo.id,
name=repo.name,
full_name=repo.full_name,
default_branch=repo.default_branch,
private=repo.private,
securitymd=securitymd_exists,
default_branch_protection=branch_protection,
delete_branch_on_merge=delete_branch_on_merge,
dependabot_enabled=dependabot_status,
)
except Exception as error:
logger.error(
f"{error.__class__.__name__}[{error.__traceback__.tb_lineno}]: {error}"
)
return repos
class Protection(BaseModel):
"""Model for Github Branch Protection"""
require_pull_request: bool = False
approval_count: int = 0
linear_history: bool = False
allow_force_push: bool = True
allow_branch_deletion: bool = True
enforce_status_checks: bool = False
enforce_admins: bool = False
conversation_resolution: bool = False
class Repo(BaseModel):
"""Model for Github Repository"""
id: int
name: str
full_name: str
private: bool
default_branch: str
default_branch_protection: Optional[Protection]
securitymd: bool = False
delete_branch_on_merge: bool = False
dependabot_enabled: bool = False

View File

@@ -65,6 +65,7 @@ numpy = "2.0.2"
pandas = "2.2.3"
py-ocsf-models = "0.2.0"
pydantic = "1.10.18"
pygithub = "2.5.0"
python = ">=3.9,<3.13"
python-dateutil = "^2.9.0.post0"
pytz = "2024.2"

View File

@@ -0,0 +1,37 @@
from mock import MagicMock
from prowler.providers.github.github_provider import GithubProvider
from prowler.providers.github.models import GithubIdentityInfo, GithubSession
# GitHub Identity
ACCOUNT_NAME = "account-name"
ACCOUNT_ID = "account-id"
ACCOUNT_URL = "/user"
# GitHub Credentials
PAT_TOKEN = "github-token"
OAUTH_TOKEN = "oauth-token"
APP_ID = "app-id"
APP_KEY = "app-key"
# Mocked GitHub Provider
def set_mocked_github_provider(
auth_method: str = "personal_access",
credentials: GithubSession = GithubSession(token=PAT_TOKEN, id=APP_ID, key=APP_KEY),
identity: GithubIdentityInfo = GithubIdentityInfo(
account_name=ACCOUNT_NAME,
account_id=ACCOUNT_ID,
account_url=ACCOUNT_URL,
),
audit_config: dict = None,
) -> GithubProvider:
provider = MagicMock()
provider.type = "github"
provider.auth_method = auth_method
provider.session = credentials
provider.identity = identity
provider.audit_config = audit_config
return provider

View File

@@ -0,0 +1,137 @@
from unittest.mock import patch
from prowler.config.config import (
default_fixer_config_file_path,
load_and_validate_config_file,
)
from prowler.providers.github.github_provider import GithubProvider
from prowler.providers.github.models import (
GithubAppIdentityInfo,
GithubIdentityInfo,
GithubSession,
)
from tests.providers.github.github_fixtures import (
ACCOUNT_ID,
ACCOUNT_NAME,
ACCOUNT_URL,
APP_ID,
APP_KEY,
OAUTH_TOKEN,
PAT_TOKEN,
)
class TestGitHubProvider:
def test_github_provider_PAT(self):
personal_access_token = PAT_TOKEN
oauth_app_token = None
github_app_id = None
github_app_key = None
fixer_config = load_and_validate_config_file(
"github", default_fixer_config_file_path
)
with (
patch(
"prowler.providers.github.github_provider.GithubProvider.setup_session",
return_value=GithubSession(token=PAT_TOKEN, id="", key=""),
),
patch(
"prowler.providers.github.github_provider.GithubProvider.setup_identity",
return_value=GithubIdentityInfo(
account_id=ACCOUNT_ID,
account_name=ACCOUNT_NAME,
account_url=ACCOUNT_URL,
),
),
):
provider = GithubProvider(
personal_access_token,
oauth_app_token,
github_app_id,
github_app_key,
)
assert provider._type == "github"
assert provider.session == GithubSession(token=PAT_TOKEN, id="", key="")
assert provider.identity == GithubIdentityInfo(
account_name=ACCOUNT_NAME,
account_id=ACCOUNT_ID,
account_url=ACCOUNT_URL,
)
assert provider._audit_config == {}
assert provider._fixer_config == fixer_config
def test_github_provider_OAuth(self):
personal_access_token = None
oauth_app_token = OAUTH_TOKEN
github_app_id = None
github_app_key = None
fixer_config = load_and_validate_config_file(
"github", default_fixer_config_file_path
)
with (
patch(
"prowler.providers.github.github_provider.GithubProvider.setup_session",
return_value=GithubSession(token=OAUTH_TOKEN, id="", key=""),
),
patch(
"prowler.providers.github.github_provider.GithubProvider.setup_identity",
return_value=GithubIdentityInfo(
account_id=ACCOUNT_ID,
account_name=ACCOUNT_NAME,
account_url=ACCOUNT_URL,
),
),
):
provider = GithubProvider(
personal_access_token,
oauth_app_token,
github_app_id,
github_app_key,
)
assert provider._type == "github"
assert provider.session == GithubSession(token=OAUTH_TOKEN, id="", key="")
assert provider.identity == GithubIdentityInfo(
account_name=ACCOUNT_NAME,
account_id=ACCOUNT_ID,
account_url=ACCOUNT_URL,
)
assert provider._audit_config == {}
assert provider._fixer_config == fixer_config
def test_github_provider_App(self):
personal_access_token = None
oauth_app_token = None
github_app_id = APP_ID
github_app_key = APP_KEY
fixer_config = load_and_validate_config_file(
"github", default_fixer_config_file_path
)
with (
patch(
"prowler.providers.github.github_provider.GithubProvider.setup_session",
return_value=GithubSession(token="", id=APP_ID, key=APP_KEY),
),
patch(
"prowler.providers.github.github_provider.GithubProvider.setup_identity",
return_value=GithubAppIdentityInfo(
app_id=APP_ID,
),
),
):
provider = GithubProvider(
personal_access_token,
oauth_app_token,
github_app_id,
github_app_key,
)
assert provider._type == "github"
assert provider.session == GithubSession(token="", id=APP_ID, key=APP_KEY)
assert provider.identity == GithubAppIdentityInfo(app_id=APP_ID)
assert provider._audit_config == {}
assert provider._fixer_config == fixer_config

View File

@@ -0,0 +1,157 @@
from unittest import mock
from prowler.providers.github.services.repository.repository_service import (
Protection,
Repo,
)
from tests.providers.github.github_fixtures import set_mocked_github_provider
class Test_repository_code_changes_multi_approval_requirement:
def test_no_repositories(self):
repository_client = mock.MagicMock
repository_client.repositories = {}
with (
mock.patch(
"prowler.providers.common.provider.Provider.get_global_provider",
return_value=set_mocked_github_provider(),
),
mock.patch(
"prowler.providers.github.services.repository.repository_code_changes_multi_approval_requirement.repository_code_changes_multi_approval_requirement.repository_client",
new=repository_client,
),
):
from prowler.providers.github.services.repository.repository_code_changes_multi_approval_requirement.repository_code_changes_multi_approval_requirement import (
repository_code_changes_multi_approval_requirement,
)
check = repository_code_changes_multi_approval_requirement()
result = check.execute()
assert len(result) == 0
def test_repository_no_require_pull_request(self):
repository_client = mock.MagicMock
repo_name = "repo1"
repository_client.repositories = {
1: Repo(
id=1,
name=repo_name,
full_name="account-name/repo1",
private=False,
default_branch="main",
default_branch_protection=Protection(
require_pull_request=False, approval_count=0
),
securitymd=False,
),
}
with (
mock.patch(
"prowler.providers.common.provider.Provider.get_global_provider",
return_value=set_mocked_github_provider(),
),
mock.patch(
"prowler.providers.github.services.repository.repository_code_changes_multi_approval_requirement.repository_code_changes_multi_approval_requirement.repository_client",
new=repository_client,
),
):
from prowler.providers.github.services.repository.repository_code_changes_multi_approval_requirement.repository_code_changes_multi_approval_requirement import (
repository_code_changes_multi_approval_requirement,
)
check = repository_code_changes_multi_approval_requirement()
result = check.execute()
assert len(result) == 1
assert result[0].resource_id == 1
assert result[0].resource_name == "repo1"
assert result[0].status == "FAIL"
assert (
result[0].status_extended
== f"Repository {repo_name} does not enforce at least 2 approvals for code changes."
)
def test_repository_no_approvals(self):
repository_client = mock.MagicMock
repo_name = "repo1"
repository_client.repositories = {
1: Repo(
id=1,
name=repo_name,
full_name="account-name/repo1",
private=False,
default_branch="master",
default_branch_protection=Protection(
require_pull_request=True, approval_count=0
),
securitymd=False,
),
}
with (
mock.patch(
"prowler.providers.common.provider.Provider.get_global_provider",
return_value=set_mocked_github_provider(),
),
mock.patch(
"prowler.providers.github.services.repository.repository_code_changes_multi_approval_requirement.repository_code_changes_multi_approval_requirement.repository_client",
new=repository_client,
),
):
from prowler.providers.github.services.repository.repository_code_changes_multi_approval_requirement.repository_code_changes_multi_approval_requirement import (
repository_code_changes_multi_approval_requirement,
)
check = repository_code_changes_multi_approval_requirement()
result = check.execute()
assert len(result) == 1
assert result[0].resource_id == 1
assert result[0].resource_name == "repo1"
assert result[0].status == "FAIL"
assert (
result[0].status_extended
== f"Repository {repo_name} does not enforce at least 2 approvals for code changes."
)
def test_repository_two_approvals(self):
repository_client = mock.MagicMock
repo_name = "repo1"
repository_client.repositories = {
1: Repo(
id=1,
name=repo_name,
full_name="account-name/repo1",
private=False,
default_branch="master",
default_branch_protection=Protection(
require_pull_request=True, approval_count=2
),
securitymd=True,
),
}
with (
mock.patch(
"prowler.providers.common.provider.Provider.get_global_provider",
return_value=set_mocked_github_provider(),
),
mock.patch(
"prowler.providers.github.services.repository.repository_code_changes_multi_approval_requirement.repository_code_changes_multi_approval_requirement.repository_client",
new=repository_client,
),
):
from prowler.providers.github.services.repository.repository_code_changes_multi_approval_requirement.repository_code_changes_multi_approval_requirement import (
repository_code_changes_multi_approval_requirement,
)
check = repository_code_changes_multi_approval_requirement()
result = check.execute()
assert len(result) == 1
assert result[0].resource_id == 1
assert result[0].resource_name == "repo1"
assert result[0].status == "PASS"
assert (
result[0].status_extended
== f"Repository {repo_name} does enforce at least 2 approvals for code changes."
)

View File

@@ -0,0 +1,99 @@
from unittest import mock
from prowler.providers.github.services.repository.repository_service import Repo
from tests.providers.github.github_fixtures import set_mocked_github_provider
class Test_repository_deletes_branch_on_merge_test:
def test_no_repositories(self):
repository_client = mock.MagicMock
repository_client.repositories = {}
with mock.patch(
"prowler.providers.common.provider.Provider.get_global_provider",
return_value=set_mocked_github_provider(),
), mock.patch(
"prowler.providers.github.services.repository.repository_deletes_branch_on_merge.repository_deletes_branch_on_merge.repository_client",
new=repository_client,
):
from prowler.providers.github.services.repository.repository_deletes_branch_on_merge.repository_deletes_branch_on_merge import (
repository_deletes_branch_on_merge,
)
check = repository_deletes_branch_on_merge()
result = check.execute()
assert len(result) == 0
def test_branch_deletion_disabled(self):
repository_client = mock.MagicMock
repo_name = "repo1"
repository_client.repositories = {
1: Repo(
id=1,
name=repo_name,
full_name="account-name/repo1",
default_branch="main",
private=False,
securitymd=False,
delete_branch_on_merge=False,
),
}
with mock.patch(
"prowler.providers.common.provider.Provider.get_global_provider",
return_value=set_mocked_github_provider(),
), mock.patch(
"prowler.providers.github.services.repository.repository_deletes_branch_on_merge.repository_deletes_branch_on_merge.repository_client",
new=repository_client,
):
from prowler.providers.github.services.repository.repository_deletes_branch_on_merge.repository_deletes_branch_on_merge import (
repository_deletes_branch_on_merge,
)
check = repository_deletes_branch_on_merge()
result = check.execute()
assert len(result) == 1
assert result[0].resource_id == 1
assert result[0].resource_name == "repo1"
assert result[0].status == "FAIL"
assert (
result[0].status_extended
== f"Repository {repo_name} does not delete branches on merge."
)
def test_branch_deletion_enabled(self):
repository_client = mock.MagicMock
repo_name = "repo1"
repository_client.repositories = {
1: Repo(
id=1,
name=repo_name,
full_name="account-name/repo1",
default_branch="main",
private=False,
securitymd=True,
delete_branch_on_merge=True,
),
}
with mock.patch(
"prowler.providers.common.provider.Provider.get_global_provider",
return_value=set_mocked_github_provider(),
), mock.patch(
"prowler.providers.github.services.repository.repository_deletes_branch_on_merge.repository_deletes_branch_on_merge.repository_client",
new=repository_client,
):
from prowler.providers.github.services.repository.repository_deletes_branch_on_merge.repository_deletes_branch_on_merge import (
repository_deletes_branch_on_merge,
)
check = repository_deletes_branch_on_merge()
result = check.execute()
assert len(result) == 1
assert result[0].resource_id == 1
assert result[0].resource_name == "repo1"
assert result[0].status == "PASS"
assert (
result[0].status_extended
== f"Repository {repo_name} does delete branches on merge."
)

View File

@@ -0,0 +1,123 @@
from unittest import mock
from prowler.providers.github.services.repository.repository_service import (
Protection,
Repo,
)
from tests.providers.github.github_fixtures import set_mocked_github_provider
class Test_repository_denies_branch_deletion_test:
def test_no_repositories(self):
repository_client = mock.MagicMock
repository_client.repositories = {}
with (
mock.patch(
"prowler.providers.common.provider.Provider.get_global_provider",
return_value=set_mocked_github_provider(),
),
mock.patch(
"prowler.providers.github.services.repository.repository_denies_branch_deletion.repository_denies_branch_deletion.repository_client",
new=repository_client,
),
):
from prowler.providers.github.services.repository.repository_denies_branch_deletion.repository_denies_branch_deletion import (
repository_denies_branch_deletion,
)
check = repository_denies_branch_deletion()
result = check.execute()
assert len(result) == 0
def test_allow_branch_deletion_enabled(self):
repository_client = mock.MagicMock
repo_name = "repo1"
default_branch = "main"
repository_client.repositories = {
1: Repo(
id=1,
name=repo_name,
full_name="account-name/repo1",
default_branch=default_branch,
default_branch_protection=Protection(
require_pull_request=True,
approval_count=2,
linear_history=False,
allow_branch_deletion=True,
),
private=False,
securitymd=False,
),
}
with (
mock.patch(
"prowler.providers.common.provider.Provider.get_global_provider",
return_value=set_mocked_github_provider(),
),
mock.patch(
"prowler.providers.github.services.repository.repository_denies_branch_deletion.repository_denies_branch_deletion.repository_client",
new=repository_client,
),
):
from prowler.providers.github.services.repository.repository_denies_branch_deletion.repository_denies_branch_deletion import (
repository_denies_branch_deletion,
)
check = repository_denies_branch_deletion()
result = check.execute()
assert len(result) == 1
assert result[0].resource_id == 1
assert result[0].resource_name == "repo1"
assert result[0].status == "FAIL"
assert (
result[0].status_extended
== f"Repository {repo_name} does allow branch deletion."
)
def test_allow_branch_deletion_disabled(self):
repository_client = mock.MagicMock
repo_name = "repo1"
default_branch = "main"
repository_client.repositories = {
1: Repo(
id=1,
name=repo_name,
full_name="account-name/repo1",
private=False,
default_branch=default_branch,
default_branch_protection=Protection(
require_pull_request=True,
approval_count=2,
linear_history=True,
allow_branch_deletion=False,
),
securitymd=True,
),
}
with (
mock.patch(
"prowler.providers.common.provider.Provider.get_global_provider",
return_value=set_mocked_github_provider(),
),
mock.patch(
"prowler.providers.github.services.repository.repository_denies_branch_deletion.repository_denies_branch_deletion.repository_client",
new=repository_client,
),
):
from prowler.providers.github.services.repository.repository_denies_branch_deletion.repository_denies_branch_deletion import (
repository_denies_branch_deletion,
)
check = repository_denies_branch_deletion()
result = check.execute()
assert len(result) == 1
assert result[0].resource_id == 1
assert result[0].resource_name == "repo1"
assert result[0].status == "PASS"
assert (
result[0].status_extended
== f"Repository {repo_name} does deny branch deletion."
)

View File

@@ -0,0 +1,123 @@
from unittest import mock
from prowler.providers.github.services.repository.repository_service import (
Protection,
Repo,
)
from tests.providers.github.github_fixtures import set_mocked_github_provider
class Test_repository_denies_force_push_test:
def test_no_repositories(self):
repository_client = mock.MagicMock
repository_client.repositories = {}
with (
mock.patch(
"prowler.providers.common.provider.Provider.get_global_provider",
return_value=set_mocked_github_provider(),
),
mock.patch(
"prowler.providers.github.services.repository.repository_denies_force_push.repository_denies_force_push.repository_client",
new=repository_client,
),
):
from prowler.providers.github.services.repository.repository_denies_force_push.repository_denies_force_push import (
repository_denies_force_push,
)
check = repository_denies_force_push()
result = check.execute()
assert len(result) == 0
def test_allow_force_push_enabled(self):
repository_client = mock.MagicMock
repo_name = "repo1"
default_branch = "main"
repository_client.repositories = {
1: Repo(
id=1,
name=repo_name,
full_name="account-name/repo1",
default_branch=default_branch,
default_branch_protection=Protection(
require_pull_request=True,
approval_count=2,
linear_history=False,
allow_force_push=True,
),
private=False,
securitymd=False,
),
}
with (
mock.patch(
"prowler.providers.common.provider.Provider.get_global_provider",
return_value=set_mocked_github_provider(),
),
mock.patch(
"prowler.providers.github.services.repository.repository_denies_force_push.repository_denies_force_push.repository_client",
new=repository_client,
),
):
from prowler.providers.github.services.repository.repository_denies_force_push.repository_denies_force_push import (
repository_denies_force_push,
)
check = repository_denies_force_push()
result = check.execute()
assert len(result) == 1
assert result[0].resource_id == 1
assert result[0].resource_name == "repo1"
assert result[0].status == "FAIL"
assert (
result[0].status_extended
== f"Repository {repo_name} does allow force push."
)
def test_allow_force_push_disabled(self):
repository_client = mock.MagicMock
repo_name = "repo1"
default_branch = "main"
repository_client.repositories = {
1: Repo(
id=1,
name=repo_name,
full_name="account-name/repo1",
private=False,
default_branch=default_branch,
default_branch_protection=Protection(
require_pull_request=True,
approval_count=2,
linear_history=True,
allow_force_push=False,
),
securitymd=True,
),
}
with (
mock.patch(
"prowler.providers.common.provider.Provider.get_global_provider",
return_value=set_mocked_github_provider(),
),
mock.patch(
"prowler.providers.github.services.repository.repository_denies_force_push.repository_denies_force_push.repository_client",
new=repository_client,
),
):
from prowler.providers.github.services.repository.repository_denies_force_push.repository_denies_force_push import (
repository_denies_force_push,
)
check = repository_denies_force_push()
result = check.execute()
assert len(result) == 1
assert result[0].resource_id == 1
assert result[0].resource_name == "repo1"
assert result[0].status == "PASS"
assert (
result[0].status_extended
== f"Repository {repo_name} does deny force push."
)

View File

@@ -0,0 +1,116 @@
from unittest import mock
from prowler.providers.github.services.repository.repository_service import (
Protection,
Repo,
)
from tests.providers.github.github_fixtures import set_mocked_github_provider
class Test_repository_enforces_admin_branch_protection_test:
def test_no_repositories(self):
repository_client = mock.MagicMock
repository_client.repositories = {}
with (
mock.patch(
"prowler.providers.common.provider.Provider.get_global_provider",
return_value=set_mocked_github_provider(),
),
mock.patch(
"prowler.providers.github.services.repository.repository_enforces_admin_branch_protection.repository_enforces_admin_branch_protection.repository_client",
new=repository_client,
),
):
from prowler.providers.github.services.repository.repository_enforces_admin_branch_protection.repository_enforces_admin_branch_protection import (
repository_enforces_admin_branch_protection,
)
check = repository_enforces_admin_branch_protection()
result = check.execute()
assert len(result) == 0
def test_enforce_status_checks_disabled(self):
repository_client = mock.MagicMock
repo_name = "repo1"
default_branch = "main"
repository_client.repositories = {
1: Repo(
id=1,
name=repo_name,
full_name="account-name/repo1",
default_branch=default_branch,
private=False,
securitymd=False,
),
}
with (
mock.patch(
"prowler.providers.common.provider.Provider.get_global_provider",
return_value=set_mocked_github_provider(),
),
mock.patch(
"prowler.providers.github.services.repository.repository_enforces_admin_branch_protection.repository_enforces_admin_branch_protection.repository_client",
new=repository_client,
),
):
from prowler.providers.github.services.repository.repository_enforces_admin_branch_protection.repository_enforces_admin_branch_protection import (
repository_enforces_admin_branch_protection,
)
check = repository_enforces_admin_branch_protection()
result = check.execute()
assert len(result) == 1
assert result[0].resource_id == 1
assert result[0].resource_name == "repo1"
assert result[0].status == "FAIL"
assert (
result[0].status_extended
== f"Repository {repo_name} does not enforce administrators to be subject to the same branch protection rules as other users."
)
def test_enforce_status_checks_enabled(self):
repository_client = mock.MagicMock
repo_name = "repo1"
default_branch = "main"
repository_client.repositories = {
1: Repo(
id=1,
name=repo_name,
full_name="account-name/repo1",
private=False,
default_branch=default_branch,
default_branch_protection=Protection(
require_pull_request=True,
approval_count=2,
enforce_admins=True,
),
securitymd=True,
),
}
with (
mock.patch(
"prowler.providers.common.provider.Provider.get_global_provider",
return_value=set_mocked_github_provider(),
),
mock.patch(
"prowler.providers.github.services.repository.repository_enforces_admin_branch_protection.repository_enforces_admin_branch_protection.repository_client",
new=repository_client,
),
):
from prowler.providers.github.services.repository.repository_enforces_admin_branch_protection.repository_enforces_admin_branch_protection import (
repository_enforces_admin_branch_protection,
)
check = repository_enforces_admin_branch_protection()
result = check.execute()
assert len(result) == 1
assert result[0].resource_id == 1
assert result[0].resource_name == "repo1"
assert result[0].status == "PASS"
assert (
result[0].status_extended
== f"Repository {repo_name} does enforce administrators to be subject to the same branch protection rules as other users."
)

View File

@@ -0,0 +1,114 @@
from unittest import mock
from prowler.providers.github.services.repository.repository_service import (
Protection,
Repo,
)
from tests.providers.github.github_fixtures import set_mocked_github_provider
class Test_repository_enforces_default_branch_protection_test:
def test_no_repositories(self):
repository_client = mock.MagicMock
repository_client.repositories = {}
with (
mock.patch(
"prowler.providers.common.provider.Provider.get_global_provider",
return_value=set_mocked_github_provider(),
),
mock.patch(
"prowler.providers.github.services.repository.repository_enforces_default_branch_protection.repository_enforces_default_branch_protection.repository_client",
new=repository_client,
),
):
from prowler.providers.github.services.repository.repository_enforces_default_branch_protection.repository_enforces_default_branch_protection import (
repository_enforces_default_branch_protection,
)
check = repository_enforces_default_branch_protection()
result = check.execute()
assert len(result) == 0
def test_without_default_branch_protection(self):
repository_client = mock.MagicMock
repo_name = "repo1"
default_branch = "main"
repository_client.repositories = {
1: Repo(
id=1,
name=repo_name,
full_name="account-name/repo1",
default_branch=default_branch,
private=False,
securitymd=False,
),
}
with (
mock.patch(
"prowler.providers.common.provider.Provider.get_global_provider",
return_value=set_mocked_github_provider(),
),
mock.patch(
"prowler.providers.github.services.repository.repository_enforces_default_branch_protection.repository_enforces_default_branch_protection.repository_client",
new=repository_client,
),
):
from prowler.providers.github.services.repository.repository_enforces_default_branch_protection.repository_enforces_default_branch_protection import (
repository_enforces_default_branch_protection,
)
check = repository_enforces_default_branch_protection()
result = check.execute()
assert len(result) == 1
assert result[0].resource_id == 1
assert result[0].resource_name == "repo1"
assert result[0].status == "FAIL"
assert (
result[0].status_extended
== f"Repository {repo_name} does not enforce branch protection on default branch ({default_branch})."
)
def test_default_branch_protection(self):
repository_client = mock.MagicMock
repo_name = "repo1"
default_branch = "main"
repository_client.repositories = {
1: Repo(
id=1,
name=repo_name,
full_name="account-name/repo1",
private=False,
default_branch=default_branch,
default_branch_protection=Protection(
require_pull_request=True, approval_count=2
),
securitymd=True,
),
}
with (
mock.patch(
"prowler.providers.common.provider.Provider.get_global_provider",
return_value=set_mocked_github_provider(),
),
mock.patch(
"prowler.providers.github.services.repository.repository_enforces_default_branch_protection.repository_enforces_default_branch_protection.repository_client",
new=repository_client,
),
):
from prowler.providers.github.services.repository.repository_enforces_default_branch_protection.repository_enforces_default_branch_protection import (
repository_enforces_default_branch_protection,
)
check = repository_enforces_default_branch_protection()
result = check.execute()
assert len(result) == 1
assert result[0].resource_id == 1
assert result[0].resource_name == "repo1"
assert result[0].status == "PASS"
assert (
result[0].status_extended
== f"Repository {repo_name} does enforce branch protection on default branch ({default_branch})."
)

View File

@@ -0,0 +1,116 @@
from unittest import mock
from prowler.providers.github.services.repository.repository_service import (
Protection,
Repo,
)
from tests.providers.github.github_fixtures import set_mocked_github_provider
class Test_repository_enforces_status_checks_test:
def test_no_repositories(self):
repository_client = mock.MagicMock
repository_client.repositories = {}
with (
mock.patch(
"prowler.providers.common.provider.Provider.get_global_provider",
return_value=set_mocked_github_provider(),
),
mock.patch(
"prowler.providers.github.services.repository.repository_enforces_status_checks.repository_enforces_status_checks.repository_client",
new=repository_client,
),
):
from prowler.providers.github.services.repository.repository_enforces_status_checks.repository_enforces_status_checks import (
repository_enforces_status_checks,
)
check = repository_enforces_status_checks()
result = check.execute()
assert len(result) == 0
def test_enforce_status_checks_disabled(self):
repository_client = mock.MagicMock
repo_name = "repo1"
default_branch = "main"
repository_client.repositories = {
1: Repo(
id=1,
name=repo_name,
full_name="account-name/repo1",
default_branch=default_branch,
private=False,
securitymd=False,
),
}
with (
mock.patch(
"prowler.providers.common.provider.Provider.get_global_provider",
return_value=set_mocked_github_provider(),
),
mock.patch(
"prowler.providers.github.services.repository.repository_enforces_status_checks.repository_enforces_status_checks.repository_client",
new=repository_client,
),
):
from prowler.providers.github.services.repository.repository_enforces_status_checks.repository_enforces_status_checks import (
repository_enforces_status_checks,
)
check = repository_enforces_status_checks()
result = check.execute()
assert len(result) == 1
assert result[0].resource_id == 1
assert result[0].resource_name == "repo1"
assert result[0].status == "FAIL"
assert (
result[0].status_extended
== f"Repository {repo_name} does not enforce status checks."
)
def test_enforce_status_checks_enabled(self):
repository_client = mock.MagicMock
repo_name = "repo1"
default_branch = "main"
repository_client.repositories = {
1: Repo(
id=1,
name=repo_name,
full_name="account-name/repo1",
private=False,
default_branch=default_branch,
default_branch_protection=Protection(
require_pull_request=True,
approval_count=2,
enforce_status_checks=True,
),
securitymd=True,
),
}
with (
mock.patch(
"prowler.providers.common.provider.Provider.get_global_provider",
return_value=set_mocked_github_provider(),
),
mock.patch(
"prowler.providers.github.services.repository.repository_enforces_status_checks.repository_enforces_status_checks.repository_client",
new=repository_client,
),
):
from prowler.providers.github.services.repository.repository_enforces_status_checks.repository_enforces_status_checks import (
repository_enforces_status_checks,
)
check = repository_enforces_status_checks()
result = check.execute()
assert len(result) == 1
assert result[0].resource_id == 1
assert result[0].resource_name == "repo1"
assert result[0].status == "PASS"
assert (
result[0].status_extended
== f"Repository {repo_name} does enforce status checks."
)

View File

@@ -0,0 +1,119 @@
from unittest import mock
from prowler.providers.github.services.repository.repository_service import (
Protection,
Repo,
)
from tests.providers.github.github_fixtures import set_mocked_github_provider
class Test_repository_merging_requires_conversation_resolution_test:
def test_no_repositories(self):
repository_client = mock.MagicMock
repository_client.repositories = {}
with (
mock.patch(
"prowler.providers.common.provider.Provider.get_global_provider",
return_value=set_mocked_github_provider(),
),
mock.patch(
"prowler.providers.github.services.repository.repository_merging_requires_conversation_resolution.repository_merging_requires_conversation_resolution.repository_client",
new=repository_client,
),
):
from prowler.providers.github.services.repository.repository_merging_requires_conversation_resolution.repository_merging_requires_conversation_resolution import (
repository_merging_requires_conversation_resolution,
)
check = repository_merging_requires_conversation_resolution()
result = check.execute()
assert len(result) == 0
def test_conversation_resolution_disabled(self):
repository_client = mock.MagicMock
repo_name = "repo1"
default_branch = "main"
repository_client.repositories = {
1: Repo(
id=1,
name=repo_name,
full_name="account-name/repo1",
default_branch=default_branch,
default_branch_protection=Protection(
require_pull_request=True, approval_count=2, linear_history=False
),
private=False,
securitymd=False,
),
}
with (
mock.patch(
"prowler.providers.common.provider.Provider.get_global_provider",
return_value=set_mocked_github_provider(),
),
mock.patch(
"prowler.providers.github.services.repository.repository_merging_requires_conversation_resolution.repository_merging_requires_conversation_resolution.repository_client",
new=repository_client,
),
):
from prowler.providers.github.services.repository.repository_merging_requires_conversation_resolution.repository_merging_requires_conversation_resolution import (
repository_merging_requires_conversation_resolution,
)
check = repository_merging_requires_conversation_resolution()
result = check.execute()
assert len(result) == 1
assert result[0].resource_id == 1
assert result[0].resource_name == "repo1"
assert result[0].status == "FAIL"
assert (
result[0].status_extended
== f"Repository {repo_name} does not require conversation resolution."
)
def test_conversation_resolution_enabled(self):
repository_client = mock.MagicMock
repo_name = "repo1"
default_branch = "main"
repository_client.repositories = {
1: Repo(
id=1,
name=repo_name,
full_name="account-name/repo1",
private=False,
default_branch=default_branch,
default_branch_protection=Protection(
require_pull_request=True,
approval_count=2,
conversation_resolution=True,
),
securitymd=True,
),
}
with (
mock.patch(
"prowler.providers.common.provider.Provider.get_global_provider",
return_value=set_mocked_github_provider(),
),
mock.patch(
"prowler.providers.github.services.repository.repository_merging_requires_conversation_resolution.repository_merging_requires_conversation_resolution.repository_client",
new=repository_client,
),
):
from prowler.providers.github.services.repository.repository_merging_requires_conversation_resolution.repository_merging_requires_conversation_resolution import (
repository_merging_requires_conversation_resolution,
)
check = repository_merging_requires_conversation_resolution()
result = check.execute()
assert len(result) == 1
assert result[0].resource_id == 1
assert result[0].resource_name == "repo1"
assert result[0].status == "PASS"
assert (
result[0].status_extended
== f"Repository {repo_name} does require conversation resolution."
)

View File

@@ -0,0 +1,117 @@
from unittest import mock
from prowler.providers.github.services.repository.repository_service import (
Protection,
Repo,
)
from tests.providers.github.github_fixtures import set_mocked_github_provider
class Test_repository_merging_requires_linear_history_test:
def test_no_repositories(self):
repository_client = mock.MagicMock
repository_client.repositories = {}
with (
mock.patch(
"prowler.providers.common.provider.Provider.get_global_provider",
return_value=set_mocked_github_provider(),
),
mock.patch(
"prowler.providers.github.services.repository.repository_merging_requires_linear_history.repository_merging_requires_linear_history.repository_client",
new=repository_client,
),
):
from prowler.providers.github.services.repository.repository_merging_requires_linear_history.repository_merging_requires_linear_history import (
repository_merging_requires_linear_history,
)
check = repository_merging_requires_linear_history()
result = check.execute()
assert len(result) == 0
def test_linear_history_disabled(self):
repository_client = mock.MagicMock
repo_name = "repo1"
default_branch = "main"
repository_client.repositories = {
1: Repo(
id=1,
name=repo_name,
full_name="account-name/repo1",
default_branch=default_branch,
default_branch_protection=Protection(
require_pull_request=True, approval_count=2, linear_history=False
),
private=False,
securitymd=False,
),
}
with (
mock.patch(
"prowler.providers.common.provider.Provider.get_global_provider",
return_value=set_mocked_github_provider(),
),
mock.patch(
"prowler.providers.github.services.repository.repository_merging_requires_linear_history.repository_merging_requires_linear_history.repository_client",
new=repository_client,
),
):
from prowler.providers.github.services.repository.repository_merging_requires_linear_history.repository_merging_requires_linear_history import (
repository_merging_requires_linear_history,
)
check = repository_merging_requires_linear_history()
result = check.execute()
assert len(result) == 1
assert result[0].resource_id == 1
assert result[0].resource_name == "repo1"
assert result[0].status == "FAIL"
assert (
result[0].status_extended
== f"Repository {repo_name} does not require linear history on default branch ({default_branch})."
)
def test_linear_history_enabled(self):
repository_client = mock.MagicMock
repo_name = "repo1"
default_branch = "main"
repository_client.repositories = {
1: Repo(
id=1,
name=repo_name,
full_name="account-name/repo1",
private=False,
default_branch=default_branch,
default_branch_protection=Protection(
require_pull_request=True, approval_count=2, linear_history=True
),
securitymd=True,
),
}
with (
mock.patch(
"prowler.providers.common.provider.Provider.get_global_provider",
return_value=set_mocked_github_provider(),
),
mock.patch(
"prowler.providers.github.services.repository.repository_merging_requires_linear_history.repository_merging_requires_linear_history.repository_client",
new=repository_client,
),
):
from prowler.providers.github.services.repository.repository_merging_requires_linear_history.repository_merging_requires_linear_history import (
repository_merging_requires_linear_history,
)
check = repository_merging_requires_linear_history()
result = check.execute()
assert len(result) == 1
assert result[0].resource_id == 1
assert result[0].resource_name == "repo1"
assert result[0].status == "PASS"
assert (
result[0].status_extended
== f"Repository {repo_name} does require linear history on default branch ({default_branch})."
)

View File

@@ -0,0 +1,97 @@
from unittest import mock
from prowler.providers.github.services.repository.repository_service import Repo
from tests.providers.github.github_fixtures import set_mocked_github_provider
class Test_repository_public_has_securitymd_file_test:
def test_no_repositories(self):
repository_client = mock.MagicMock
repository_client.repositories = {}
with mock.patch(
"prowler.providers.common.provider.Provider.get_global_provider",
return_value=set_mocked_github_provider(),
), mock.patch(
"prowler.providers.github.services.repository.repository_public_has_securitymd_file.repository_public_has_securitymd_file.repository_client",
new=repository_client,
):
from prowler.providers.github.services.repository.repository_public_has_securitymd_file.repository_public_has_securitymd_file import (
repository_public_has_securitymd_file,
)
check = repository_public_has_securitymd_file()
result = check.execute()
assert len(result) == 0
def test_one_repository_no_securitymd(self):
repository_client = mock.MagicMock
repo_name = "repo1"
repository_client.repositories = {
1: Repo(
id=1,
name=repo_name,
full_name="account-name/repo1",
default_branch="main",
private=False,
securitymd=False,
),
}
with mock.patch(
"prowler.providers.common.provider.Provider.get_global_provider",
return_value=set_mocked_github_provider(),
), mock.patch(
"prowler.providers.github.services.repository.repository_public_has_securitymd_file.repository_public_has_securitymd_file.repository_client",
new=repository_client,
):
from prowler.providers.github.services.repository.repository_public_has_securitymd_file.repository_public_has_securitymd_file import (
repository_public_has_securitymd_file,
)
check = repository_public_has_securitymd_file()
result = check.execute()
assert len(result) == 1
assert result[0].resource_id == 1
assert result[0].resource_name == "repo1"
assert result[0].status == "FAIL"
assert (
result[0].status_extended
== f"Repository {repo_name} does not have a SECURITY.md file."
)
def test_one_repository_securitymd(self):
repository_client = mock.MagicMock
repo_name = "repo1"
repository_client.repositories = {
1: Repo(
id=1,
name=repo_name,
full_name="account-name/repo1",
default_branch="main",
private=False,
securitymd=True,
),
}
with mock.patch(
"prowler.providers.common.provider.Provider.get_global_provider",
return_value=set_mocked_github_provider(),
), mock.patch(
"prowler.providers.github.services.repository.repository_public_has_securitymd_file.repository_public_has_securitymd_file.repository_client",
new=repository_client,
):
from prowler.providers.github.services.repository.repository_public_has_securitymd_file.repository_public_has_securitymd_file import (
repository_public_has_securitymd_file,
)
check = repository_public_has_securitymd_file()
result = check.execute()
assert len(result) == 1
assert result[0].resource_id == 1
assert result[0].resource_name == "repo1"
assert result[0].status == "PASS"
assert (
result[0].status_extended
== f"Repository {repo_name} does have a SECURITY.md file."
)

View File

@@ -0,0 +1,97 @@
from unittest import mock
from prowler.providers.github.services.repository.repository_service import Repo
from tests.providers.github.github_fixtures import set_mocked_github_provider
class Test_repository_scans_packages_vulnerabilities:
def test_no_repositories(self):
repository_client = mock.MagicMock
repository_client.repositories = {}
with mock.patch(
"prowler.providers.common.provider.Provider.get_global_provider",
return_value=set_mocked_github_provider(),
), mock.patch(
"prowler.providers.github.services.repository.repository_scans_packages_vulnerabilities.repository_scans_packages_vulnerabilities.repository_client",
new=repository_client,
):
from prowler.providers.github.services.repository.repository_scans_packages_vulnerabilities.repository_scans_packages_vulnerabilities import (
repository_scans_packages_vulnerabilities,
)
check = repository_scans_packages_vulnerabilities()
result = check.execute()
assert len(result) == 0
def test_one_repository_dependabot_disabled(self):
repository_client = mock.MagicMock
repo_name = "repo1"
repository_client.repositories = {
1: Repo(
id=1,
name=repo_name,
full_name="account-name/repo1",
default_branch="main",
private=False,
dependabot_enabled=False,
),
}
with mock.patch(
"prowler.providers.common.provider.Provider.get_global_provider",
return_value=set_mocked_github_provider(),
), mock.patch(
"prowler.providers.github.services.repository.repository_scans_packages_vulnerabilities.repository_scans_packages_vulnerabilities.repository_client",
new=repository_client,
):
from prowler.providers.github.services.repository.repository_scans_packages_vulnerabilities.repository_scans_packages_vulnerabilities import (
repository_scans_packages_vulnerabilities,
)
check = repository_scans_packages_vulnerabilities()
result = check.execute()
assert len(result) == 1
assert result[0].resource_id == 1
assert result[0].resource_name == "repo1"
assert result[0].status == "FAIL"
assert (
result[0].status_extended
== f"Repository {repo_name} does not scan vulnerabilities in used packages."
)
def test_one_repository_dependabot_enabled(self):
repository_client = mock.MagicMock
repo_name = "repo1"
repository_client.repositories = {
1: Repo(
id=1,
name=repo_name,
full_name="account-name/repo1",
default_branch="main",
private=False,
dependabot_enabled=True,
),
}
with mock.patch(
"prowler.providers.common.provider.Provider.get_global_provider",
return_value=set_mocked_github_provider(),
), mock.patch(
"prowler.providers.github.services.repository.repository_scans_packages_vulnerabilities.repository_scans_packages_vulnerabilities.repository_client",
new=repository_client,
):
from prowler.providers.github.services.repository.repository_scans_packages_vulnerabilities.repository_scans_packages_vulnerabilities import (
repository_scans_packages_vulnerabilities,
)
check = repository_scans_packages_vulnerabilities()
result = check.execute()
assert len(result) == 1
assert result[0].resource_id == 1
assert result[0].resource_name == "repo1"
assert result[0].status == "PASS"
assert (
result[0].status_extended
== f"Repository {repo_name} does scan vulnerabilities in used packages."
)

View File

@@ -0,0 +1,83 @@
from unittest.mock import patch
from prowler.providers.github.services.repository.repository_service import (
Protection,
Repo,
Repository,
)
from tests.providers.github.github_fixtures import set_mocked_github_provider
def mock_list_repositories(_):
return {
1: Repo(
id=1,
name="repo1",
full_name="account-name/repo1",
private=False,
default_branch="main",
default_branch_protection=Protection(
require_pull_request=True,
approval_count=2,
linear_history=True,
allow_force_push=False,
allow_branch_deletion=False,
enforce_status_checks=True,
enforce_admins=True,
conversation_resolution=True,
),
securitymd=True,
delete_branch_on_merge=True,
),
}
@patch(
"prowler.providers.github.services.repository.repository_service.Repository._list_repositories",
new=mock_list_repositories,
)
class Test_Repository_Service:
def test_get_client(self):
repository_service = Repository(set_mocked_github_provider())
assert repository_service.clients[0].__class__.__name__ == "Github"
def test_get_service(self):
repository_service = Repository(set_mocked_github_provider())
assert repository_service.__class__.__name__ == "Repository"
def test_list_repositories(self):
repository_service = Repository(set_mocked_github_provider())
assert len(repository_service.repositories) == 1
assert repository_service.repositories[1].name == "repo1"
assert repository_service.repositories[1].full_name == "account-name/repo1"
assert repository_service.repositories[1].private is False
assert repository_service.repositories[1].default_branch == "main"
# Default branch protection
assert repository_service.repositories[
1
].default_branch_protection.require_pull_request
assert (
repository_service.repositories[1].default_branch_protection.approval_count
== 2
)
assert repository_service.repositories[
1
].default_branch_protection.linear_history
assert not repository_service.repositories[
1
].default_branch_protection.allow_force_push
assert not repository_service.repositories[
1
].default_branch_protection.allow_branch_deletion
assert repository_service.repositories[
1
].default_branch_protection.enforce_status_checks
assert repository_service.repositories[
1
].default_branch_protection.enforce_admins
assert repository_service.repositories[
1
].default_branch_protection.conversation_resolution
# Repo
assert repository_service.repositories[1].securitymd
assert repository_service.repositories[1].delete_branch_on_merge