audit-labs/audit-tools

A collection of scripts, queries, and other goodies you can use in an audit. audit automation compliance evidence scripts

Commit bcb80b56c5

bcb80b56c57eca7219df35abdb0d3d1d926ab753

parent: 06c579b35c

Unsigned

Christian Cleberg <156287552+ccleberg@users.noreply.github.com> · 2024-10-28 19:50 UTC
committer: <noreply@github.com>

add github branch protections script

Layout: unified · split

github/github_branch_protections.py added +78
@@ -0,0 +1,78 @@
1"""
2Gathers branch protection rules for a repository.
3"""
4
5import requests
6
7GITHUB_TOKEN = 'your_personal_access_token'
8ORGANIZATION = 'your_organization'
9REPOSITORY = 'your_repository'
10TIMEOUT = 30
11
12headers = {
13 'Authorization': f'token {GITHUB_TOKEN}',
14 'Accept': 'application/vnd.github.v3+json'
15}
16
17def get_all_branches(org, repo):
18 """
19 Get all branches in a repository
20 """
21 all_branches = []
22 page = 1
23 while True:
24 url = f'https://api.github.com/repos/{org}/{repo}/branches?page={page}&per_page=100'
25 response = requests.get(url, headers=headers, timeout=TIMEOUT)
26 response.raise_for_status()
27 page_branches = response.json()
28 if not page_branches:
29 break
30 all_branches.extend(page_branches)
31 page += 1
32 return all_branches
33
34def get_branch_protection(org, repo, repo_branch):
35 """
36 Get branch protection settings
37 """
38 url = f'https://api.github.com/repos/{org}/{repo}/branches/{repo_branch}/protection'
39 response = requests.get(url, headers=headers, timeout=TIMEOUT)
40 if response.status_code == 404:
41 return None # No protection settings for this branch
42 response.raise_for_status()
43 return response.json()
44
45def get_repository_rulesets(org, repo):
46 """
47 Get repository rulesets
48 """
49 url = f'https://api.github.com/repos/{org}/{repo}/rulesets'
50 response = requests.get(url, headers=headers, timeout=TIMEOUT)
51 response.raise_for_status()
52 return response.json()
53
54if __name__ == '__main__':
55 try:
56 # Get all branches in the repository
57 branches = get_all_branches(ORGANIZATION, REPOSITORY)
58 print(f"Total branches in the repository '{REPOSITORY}': {len(branches)}")
59
60 # Get protection settings for each branch
61 for branch in branches:
62 branch_name = branch['name']
63 protection_settings = get_branch_protection(ORGANIZATION, REPOSITORY, branch_name)
64 print(f"\nBranch: {branch_name}")
65 if protection_settings:
66 print(f"Protection settings: {protection_settings}")
67 else:
68 print("No protection settings")
69
70 # Get repository rulesets
71 rulesets = get_repository_rulesets(ORGANIZATION, REPOSITORY)
72 print(f"\nRepository rulesets for '{REPOSITORY}':")
73 print(rulesets)
74
75 except requests.exceptions.Timeout:
76 print("The request timed out")
77 except requests.exceptions.RequestException as e:
78 print(f"An error occurred: {e}")