|
| 1 | +import os |
| 2 | +import sys |
| 3 | +import requests |
| 4 | + |
| 5 | + |
| 6 | +def check_user_permission(): |
| 7 | + """ |
| 8 | + Checks if the user who triggered the workflow has the required permission level. |
| 9 | + """ |
| 10 | + # --- 1. Get required variables from the environment --- |
| 11 | + token = os.getenv("GITHUB_TOKEN") |
| 12 | + repo = os.getenv("GITHUB_REPOSITORY") |
| 13 | + actor = os.getenv("GITHUB_ACTOR") |
| 14 | + required_permission = os.getenv( |
| 15 | + "REQUIRED_PERMISSION", "write" |
| 16 | + ) # Default to 'write' |
| 17 | + |
| 18 | + if not all([token, repo, actor]): |
| 19 | + print("Error: Missing required environment variables.", file=sys.stderr) |
| 20 | + sys.exit(1) |
| 21 | + |
| 22 | + print( |
| 23 | + f"Checking if user '{actor}' has '{required_permission}' permission on repo '{repo}'..." |
| 24 | + ) |
| 25 | + |
| 26 | + # --- 2. Construct the API request --- |
| 27 | + api_url = f"https://api.github.com/repos/{repo}/collaborators/{actor}/permission" |
| 28 | + headers = { |
| 29 | + "Authorization": f"Bearer {token}", |
| 30 | + "Accept": "application/vnd.github.v3+json", |
| 31 | + } |
| 32 | + |
| 33 | + # --- 3. Make the API call --- |
| 34 | + try: |
| 35 | + response = requests.get(api_url, headers=headers) |
| 36 | + response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx) |
| 37 | + except requests.exceptions.RequestException as e: |
| 38 | + print(f"Error calling GitHub API: {e}", file=sys.stderr) |
| 39 | + sys.exit(1) |
| 40 | + |
| 41 | + # --- 4. Check the permission level --- |
| 42 | + data = response.json() |
| 43 | + user_permission = data.get("permission") |
| 44 | + |
| 45 | + print(f"User '{actor}' has permission level: '{user_permission}'") |
| 46 | + |
| 47 | + # The permission levels are ordered: read < write < admin |
| 48 | + permission_levels = { |
| 49 | + "read": 1, |
| 50 | + "write": 2, |
| 51 | + "admin": 3, |
| 52 | + } |
| 53 | + |
| 54 | + user_level = permission_levels.get(user_permission, 0) |
| 55 | + required_level = permission_levels.get(required_permission, 2) |
| 56 | + |
| 57 | + if user_level >= required_level: |
| 58 | + print("✅ Success: User has sufficient permissions.") |
| 59 | + sys.exit(0) |
| 60 | + else: |
| 61 | + print( |
| 62 | + f"❌ Failure: User does not have the required '{required_permission}' permission.", |
| 63 | + file=sys.stderr, |
| 64 | + ) |
| 65 | + sys.exit(1) |
| 66 | + |
| 67 | + |
| 68 | +if __name__ == "__main__": |
| 69 | + check_user_permission() |
0 commit comments