Skip to content

Commit

Permalink
Merge pull request #249 from UffizziCloud/feature/243_handle-error-wh…
Browse files Browse the repository at this point in the history
…en-kubeconfig-file-is-another-file

[243] Handle error when kubeconfig file is another file
  • Loading branch information
moklidia authored Jul 24, 2023
2 parents 68eebf9 + fcaf94c commit acd4a58
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
22 changes: 22 additions & 0 deletions lib/uffizzi/services/kubeconfig_service.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,16 @@
require 'psych'

class KubeconfigService
class InvalidKubeconfigError < StandardError
def initialize(file_path)
msg = "Invalid kubeconfig at path '#{file_path}'"

super(msg)
end
end

DEFAULT_KUBECONFIG_PATH = '~/.kube/config'
KUBECONFIG_GENERAL_KEYS = ['apiVersion', 'clusters', 'contexts', 'current-context', 'kind', 'users'].freeze

class << self
include ApiClient
Expand Down Expand Up @@ -35,6 +44,11 @@ def update_current_context(kubeconfig, current_context)
def save_to_filepath(filepath, kubeconfig)
real_file_path = File.expand_path(filepath)
target_kubeconfig = File.exist?(real_file_path) ? Psych.safe_load(File.read(real_file_path)) : nil

if target_kubeconfig.present? && !valid_kubeconfig?(target_kubeconfig)
raise InvalidKubeconfigError.new(filepath)
end

new_kubeconfig = block_given? ? yield(target_kubeconfig) : merge(target_kubeconfig, kubeconfig)

dir_path = File.dirname(real_file_path)
Expand Down Expand Up @@ -85,5 +99,13 @@ def kubeconfig_env_path

file_paths.split(':').first
end

def valid_kubeconfig?(data)
return false unless data.is_a?(Hash)

data_keys = data.keys.map(&:to_s)

KUBECONFIG_GENERAL_KEYS.all? { |k| data_keys.include?(k) }
end
end
end
17 changes: 17 additions & 0 deletions test/uffizzi/cli/cluster_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,23 @@ def test_update_kubeconfig_if_kubeconfig_is_empty_and_cluster_is_failed
assert_match('is empty', error.message)
end

def test_update_kubeconfig_if_kubeconfig_path_has_invalid_file
@cluster.options = command_options(name: 'uffizzi-test-cluster', kubeconfig: @kubeconfig_path)

cluster_get_body = json_fixture('files/uffizzi/uffizzi_cluster_deployed.json')
stubbed_uffizzi_cluster_get_request = stub_get_cluster_request(cluster_get_body, @project_slug)
kubeconfig_from_filesystem = 'some data'

File.write(@kubeconfig_path, kubeconfig_from_filesystem)

error = assert_raises(KubeconfigService::InvalidKubeconfigError) do
@cluster.update_kubeconfig
end

assert_requested(stubbed_uffizzi_cluster_get_request)
assert_match('Invalid kubeconfig', error.message)
end

def test_describe_cluster
clusters_get_body = json_fixture('files/uffizzi/uffizzi_cluster_describe.json')
stubbed_uffizzi_cluster_get_request = stub_get_cluster_request(clusters_get_body, @project_slug)
Expand Down

0 comments on commit acd4a58

Please sign in to comment.