Skip to content

Commit

Permalink
Merge pull request #12 from gcarrarom/feature/clean-token
Browse files Browse the repository at this point in the history
Feature/clean token
  • Loading branch information
gcarrarom authored Jun 10, 2019
2 parents 567e7a1 + 833a19c commit dd1faea
Show file tree
Hide file tree
Showing 6 changed files with 195 additions and 49 deletions.
1 change: 1 addition & 0 deletions azure-pipelines.yml
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ steps:
pip install pytest-cov
pip install .
pip install testfixtures
pip install mock
displayName: 'Install dependencies'

- script: |
Expand Down
63 changes: 50 additions & 13 deletions kcleaner.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ def update_file(filename, yamldoc):
logging.debug("Writing new yaml doc into the config file")
yaml.dump(yamldoc, stream)
except yaml.YAMLError as exc:
logging.exception("Exception occured while trying to write Yaml file")
logging.exception(f"Exception occured while trying to write Yaml file: {exc}")

def get_file(filename):
logging.debug(f'Trying to retrieve contents of file {filename}')
Expand All @@ -81,7 +81,8 @@ def get_file(filename):
try:
config_file = yaml.safe_load(stream)
except yaml.YAMLError as exc:
logging.exception("Exception occured while trying to load Yaml file")
logging.exception(f"Exception occured while trying to load Yaml file: {exc}")
exit(13)
logging.debug(f'File Contents\n{config_file}')
logging.debug(f'Type of the file contents: {type(config_file)}')
if config_file == None:
Expand Down Expand Up @@ -127,31 +128,67 @@ def get_backup(backup_path):


def remove_resource(config_file, removing_type):
if config_file == None:
logging.error(f'Config File cannot be "None"!')
exit(50)
if removing_type == None:
logging.error(f'Removing type cannot be "None"!')
exit(50)

if removing_type == "" or config_file == "":
logging.error(f'Parameters cannot be empty!')
exit(51)

if removing_type == 'token':
removing_type = 'users'
removing_token = True
else:
removing_token = False
logging.debug(f"Started removal of {removing_type}")
resources_name_list = []
logging.debug('gathering list of objects for the this resource type')
for resource in config_file[removing_type]:
resources_name_list.append(resource['name'])
if removing_token:
for resource in config_file[removing_type]:
try:
logging.debug(f"{resource['user']['auth-provider']['config']['access-token']}")
resources_name_list.append(resource['name'])
except:
continue
else:
for resource in config_file[removing_type]:
resources_name_list.append(resource['name'])

resources_to_remove = []
logging.debug('Prompting for selection')
resources_to_remove = (iterfzf(resources_name_list, multi=True))
logging.debug('List of resources selected: {resources_to_remove}')
if resources_to_remove == None:
if resources_to_remove == None or resources_to_remove == "":
logging.error("No resources to remove selected!")
exit()
exit(52)

logging.debug(f"{len(config_file[removing_type])} {removing_type} before the removal")

#TODO: Implement cross resource finding
#response = ask_yn("Remove Related Resources?")
#print(f"Your response = {response}")

try:
logging.debug('Removing resources...')
config_file[removing_type] = [item for item in config_file[removing_type] if item['name'] not in resources_to_remove]
except KeyError:
logging.exception(f"Something went wrong!!")
if removing_token:
logging.debug(f"Removing token information from the user(s) {resources_to_remove}")
for item in config_file[removing_type]:
if item['name'] in resources_to_remove:
logging.debug(f"removing tokens from user {item['name']}")
item['user']['auth-provider']['config'].pop('access-token', None)
item['user']['auth-provider']['config'].pop('expires-in', None)
item['user']['auth-provider']['config'].pop('expires-on', None)
item['user']['auth-provider']['config'].pop('refresh-token', None)
logging.debug(f'Token Removed successfully!')

else:
try:
logging.debug('Removing resources...')
config_file[removing_type] = [item for item in config_file[removing_type] if item['name'] not in resources_to_remove]
except KeyError:
logging.exception(f"Something went wrong!!")

logging.debug(f"{len(config_file[removing_type])} {removing_type} in the end")

Expand All @@ -164,7 +201,8 @@ def remove_resource(config_file, removing_type):
[
'users',
'clusters',
'contexts'
'contexts',
'token'
]
),
default='contexts'
Expand Down Expand Up @@ -216,7 +254,6 @@ def cli(resource, name, kubeconfig, undo, debug):
logging.debug(f'Name of the resource requested to remove: {name}')
config_file_after = remove_resource(config_file_before, resource)


logging.debug(f"New Config file content: \n{config_file_after}")
update_file(kubeconfig, config_file_after)

Expand Down
35 changes: 0 additions & 35 deletions kcleaner.rb
Original file line number Diff line number Diff line change
@@ -1,35 +0,0 @@
class kcleaner < Formula
include Language::Python::Virtualenv

desc " A little CLI tool to help keeping Config Files clean"
homepage "https://fancywhale.ca/"
url "https://files.pythonhosted.org/packages/ff/d2/c8ef2dc18777b1a01b58513db9a11a9d32173e99b66d4e096358a825bb9a/PyYAML-5.1b1.tar.gz#sha256=b21fadf0e343c3738cc956be9d24ee7a83d3260ff1a6805f860b4f5d4645b7b9"
sha256 "b21fadf0e343c3738cc956be9d24ee7a83d3260ff1a6805f860b4f5d4645b7b9"
head "https://github.com/gcarrarom/kubeconfig-cleaner-cli.git"

# TODO: If you're submitting an existing package, make sure you include your
# bottle block here.

depends_on :python3

resource "Click" do
url "https://files.pythonhosted.org/packages/fa/37/45185cb5abbc30d7257104c434fe0b07e5a195a6847506c074527aa599ec/Click-7.0-py2.py3-none-any.whl#sha256=2335065e6395b9e67ca716de5f7526736bfa6ceead690adf616d925bdc622b13"
sha256 "2335065e6395b9e67ca716de5f7526736bfa6ceead690adf616d925bdc622b13"
end

resource "setuptools" do
url "https://files.pythonhosted.org/packages/d1/6a/4b2fcefd2ea0868810e92d519dacac1ddc64a2e53ba9e3422c3b62b378a6/setuptools-40.8.0-py2.py3-none-any.whl#sha256=e8496c0079f3ac30052ffe69b679bd876c5265686127a3159cfa415669b7f9ab"
sha256 "e8496c0079f3ac30052ffe69b679bd876c5265686127a3159cfa415669b7f9ab"
end

resource "iterfzf" do
url "https://files.pythonhosted.org/packages/a1/7d/a4a5de90f3cdd825cf9bfcb6ea6270533ec8127b1e328eecf7b499084c59/iterfzf-0.4.0.17.3.tar.gz#sha256=d58497135ea417777e9f518356ca3613198ffa155667a7ac918495cab9c22abb"
sha256 "d58497135ea417777e9f518356ca3613198ffa155667a7ac918495cab9c22abb"
end

def install
virtualenv_install_with_resources
end

# TODO: Add your package's tests here
end
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

setup(
name='kcleaner',
version='0.2.1',
version='0.3.0',
author='Gui Martins',
url='https://fancywhale.ca/',
author_email='[email protected]',
Expand Down
139 changes: 139 additions & 0 deletions tests/kcleaner_remove_resource_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
from kcleaner import remove_resource, get_file
from testfixtures import log_capture
import click
from click.testing import CliRunner
import pytest
import yaml
from mock import patch

runner = CliRunner()
sample_yaml_no_token = """
apiVersion: v1
clusters:
- cluster:
server: https://super.coolcluster.fancywhale.ca
name: SuperCoolCluster
contexts:
- context:
cluster: SuperCoolCluster
user: SuperCoolUserName
name: SuperCoolContext1
current-context: SuperCoolContext
kind: Config
preferences: {}
users:
- name: SuperCoolUserName1
user:
auth-provider:
config:
apiserver-id: some-id-that-makes-sense
client-id: some-id-that-makes-sense
tenant-id: some-id-that-makes-sense
name: some-auth-provider
"""
sample_yaml_token = """
apiVersion: v1
clusters:
- cluster:
server: https://super.coolcluster.fancywhale.ca
name: SuperCoolCluster
contexts:
- context:
cluster: SuperCoolCluster
user: SuperCoolUserName
name: SuperCoolContext1
current-context: SuperCoolContext
kind: Config
preferences: {}
users:
- name: SuperCoolUserName1
user:
auth-provider:
config:
access-token: SomeRandomToken
apiserver-id: some-id-that-makes-sense
client-id: some-id-that-makes-sense
expires-in: '3600'
expires-on: '1559593884'
refresh-token: SomeRandomRefreshToken
tenant-id: some-id-that-makes-sense
name: some-auth-provider
"""

@log_capture()
def test_none_parameters(capture):

with pytest.raises(SystemExit) as pytest_wrapped_e:
remove_resource(None, None)

assert pytest_wrapped_e.value.code == 50
capture.check_present(
('root', 'ERROR', 'Config File cannot be "None"!'),
)

@log_capture()
def test_removing_type_none(capture):

with pytest.raises(SystemExit) as pytest_wrapped_e:
remove_resource("", None)

assert pytest_wrapped_e.value.code == 50
capture.check_present(
('root', 'ERROR', 'Removing type cannot be "None"!'),
)

@log_capture()
def test_config_file_empty(capture):

with pytest.raises(SystemExit) as pytest_wrapped_e:
remove_resource("", "")

assert pytest_wrapped_e.value.code == 51
capture.check_present(
('root', 'ERROR', 'Parameters cannot be empty!'),
)

@log_capture()
@patch('kcleaner.iterfzf')
def test_remove_token_not_available(test_patch, capture):
with runner.isolated_filesystem():

with open(f'./SampleConfigFile', 'w') as f:
f.write(sample_yaml_no_token)

config_file = get_file("./SampleConfigFile")

test_patch.return_value = ""

with pytest.raises(SystemExit) as pytest_wrapped_e:
new_config = remove_resource(config_file, "token")

assert pytest_wrapped_e.value.code == 52
capture.check_present(
('root', 'ERROR', 'No resources to remove selected!'),
)

@log_capture()
@patch('kcleaner.iterfzf')
def test_remove_token(test_patch, capture):
name_to_remove = "SuperCoolUserName1"
with runner.isolated_filesystem():

with open(f'./SampleConfigFile', 'w') as f:
f.write(sample_yaml_token)
with open(f'./SampleConfigFileToTest', 'w') as f:
f.write(sample_yaml_no_token)

config_file = get_file("./SampleConfigFile")
config_to_test = get_file("./SampleConfigFileToTest")

test_patch.return_value = f"{name_to_remove}"

new_config = remove_resource(config_file, "token")

assert new_config == config_to_test
capture.check_present(
('root', 'DEBUG', f'Removing token information from the user(s) {name_to_remove}'),
('root', 'DEBUG', f'removing tokens from user {name_to_remove}'),
('root', 'DEBUG', 'Token Removed successfully!'),
)
4 changes: 4 additions & 0 deletions tests/sampleConfig
Original file line number Diff line number Diff line change
Expand Up @@ -109,8 +109,12 @@ users:
user:
auth-provider:
config:
access-token: SomeRandomToken
apiserver-id: some-id-that-makes-sense
client-id: some-id-that-makes-sense
expires-in: '3600'
expires-on: '1559593884'
refresh-token: SomeRandomRefreshToken
tenant-id: some-id-that-makes-sense
name: some-auth-provider
- name: SuperCoolUserName8
Expand Down

0 comments on commit dd1faea

Please sign in to comment.