Last active
February 3, 2022 18:13
-
-
Save jjorissen52/a54c801d5b04111cb5cccc4790526ec9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/local/bin/python3 | |
""" | |
This script makes it slightly easier to discover and inspect GCP IAM roles via CLI. | |
MIT License | |
Copyright (c) 2022 JP Jorissen | |
Permission is hereby granted, free of charge, to any person obtaining a copy | |
of this software and associated documentation files (the "Software"), to deal | |
in the Software without restriction, including without limitation the rights | |
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
copies of the Software, and to permit persons to whom the Software is | |
furnished to do so, subject to the following conditions: | |
The above copyright notice and this permission notice shall be included in all | |
copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
SOFTWARE. | |
""" | |
import os | |
import sys | |
import json | |
import pickle | |
import shutil | |
import logging | |
import functools | |
logger = logging.getLogger(__name__) | |
logger.setLevel(logging.DEBUG) | |
logger.addHandler(logging.StreamHandler()) | |
from pathlib import Path | |
CACHE_DIR = Path('/tmp/groles') | |
def install(requirements): | |
import pip | |
input(f"Would you like to install {requirements}? [y/N]>").lower() in ["y", "yes"] or sys.exit(1) | |
pip.main(["install", *requirements]) | |
try: | |
import fire | |
from googleapiclient import discovery | |
from oauth2client.client import GoogleCredentials | |
except ImportError: | |
install(["google-api-python-client", "oauth2client", "fire"]) | |
sys.exit(1) | |
def cache(dest): | |
dest = Path(dest) | |
def deco(func): | |
@functools.wraps(func) | |
def wrapper(*args, **kwargs): | |
if dest.exists(): | |
with open(dest, 'rb') as pickle_rb: | |
return pickle.load(pickle_rb) | |
result = func(*args, **kwargs) | |
os.makedirs(dest.parent, exist_ok=True) | |
with open(dest, 'wb') as pickle_wb: | |
pickle.dump(result, pickle_wb) | |
return result | |
return wrapper | |
return deco | |
def stream_json(func): | |
@functools.wraps(func) | |
def wrapper(*args, **kwargs): | |
res = func(*args, **kwargs) | |
if isinstance(res, list): | |
for item in res: | |
print(json.dumps(item)) | |
return | |
print(json.dumps(res)) | |
return wrapper | |
@cache(CACHE_DIR / 'fetch.pickle') | |
def fetch_roles(): | |
logger.info("We need to fetch the roles. This could take quite some time.") | |
credentials = GoogleCredentials.get_application_default() | |
service = discovery.build('iam', 'v1', credentials=credentials) | |
roles = [] | |
request = service.roles().list() | |
while True: | |
response = request.execute() | |
current_roles = response.get('roles', []) | |
for role in current_roles: | |
logger.debug(role['name']) | |
request_2 = service.roles().get(name=role['name']) | |
response_2 = request_2.execute() | |
role['permissions'] = response_2.get('includedPermissions', []) | |
roles.extend(current_roles) | |
request = service.projects().roles().list_next(previous_request=request, previous_response=response) | |
if request is None: | |
break | |
return roles | |
class IAM: | |
class cache: | |
@staticmethod | |
def clear(): | |
shutil.rmtree(str(CACHE_DIR), ignore_errors=True) | |
@staticmethod | |
def show(): | |
roles = fetch_roles() | |
return json.dumps(roles, indent=2) | |
class roles: | |
@staticmethod | |
def show(): | |
return IAM.show() | |
@staticmethod | |
@stream_json | |
def get(*args, by='name', hide_perms=False): | |
args = set(args) | |
by_ok = {'name', 'perms', 'permissions', 'title'} | |
roles = fetch_roles() | |
if 'perms' in by: | |
permission_map = {} | |
for role in roles: | |
perms = getattr(role, 'pop' if hide_perms else 'get')("permissions", []) | |
for perm in perms: | |
if perm in permission_map: | |
permission_map[perm].append(role) | |
else: | |
permission_map[perm] = [role] | |
results = [] | |
for arg in args: | |
results.extend(permission_map.get(arg, None)) | |
return results | |
if by not in by_ok: | |
return print(f"Expected by to be one of {by_ok}, got {by}", file=sys.stderr) | |
return [role for role in roles if role[by] in args] | |
@staticmethod | |
@stream_json | |
def search(*args, by='name', hide_perms=False): | |
args = set(args) | |
by_ok = {'name', 'perms', 'permissions', 'title'} | |
roles = fetch_roles() | |
if 'perms' in by: | |
permission_map = {} | |
for role in roles: | |
perms = getattr(role, 'pop' if hide_perms else 'get')("permissions", []) | |
for perm in perms: | |
if perm in permission_map: | |
permission_map[perm].append(role) | |
else: | |
permission_map[perm] = [role] | |
candidate_perms = [] | |
for arg in args: | |
candidate_perms.extend([perm for perm in permission_map if arg.lower() in perm.lower()]) | |
results = [] | |
for p in candidate_perms: | |
results.extend(permission_map.get(p, [])) | |
return results | |
if by not in by_ok: | |
return print(f"Expected by to be one of {by_ok}, got {by}", file=sys.stderr) | |
candidate_roles = [] | |
for arg in args: | |
candidate_roles.extend([role for role in roles if arg.lower() in role[by].lower()]) | |
return candidate_roles | |
if __name__ == '__main__': | |
fire.Fire(IAM) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment