Skip to content

Commit

Permalink
Move hide_sensitive_data to Shell
Browse files Browse the repository at this point in the history
  • Loading branch information
ahangarha committed Nov 30, 2023
1 parent ff44e38 commit f0a267a
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 15 deletions.
19 changes: 6 additions & 13 deletions lib/core/controlplane.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@ def profile_exists?(profile)
end

def profile_create(profile, token)
@sensitive_data_pattern = /(?<=--token )(\S+)/
sensitive_data_pattern = /(?<=--token )(\S+)/
cmd = "cpln profile create #{profile} --token #{token}"
cmd += " > /dev/null" if Shell.should_hide_output?
perform!(cmd)
perform!(cmd, sensitive_data_pattern: sensitive_data_pattern)
end

def profile_delete(profile)
Expand Down Expand Up @@ -342,19 +342,19 @@ def parse_apply_result(result) # rubocop:disable Metrics/CyclomaticComplexity, M
private

def perform(cmd)
Shell.debug("CMD", hide_sensitive_data(cmd))
Shell.debug("CMD", cmd)

system(cmd)
end

def perform!(cmd)
Shell.debug("CMD", hide_sensitive_data(cmd))
def perform!(cmd, sensitive_data_pattern: nil)
Shell.debug("CMD", cmd, sensitive_data_pattern: sensitive_data_pattern)

system(cmd) || exit(false)
end

def perform_yaml(cmd)
Shell.debug("CMD", hide_sensitive_data(cmd))
Shell.debug("CMD", cmd)

result = `#{cmd}`
$CHILD_STATUS.success? ? YAML.safe_load(result) : exit(false)
Expand All @@ -363,11 +363,4 @@ def perform_yaml(cmd)
def gvc_org
"--gvc #{gvc} --org #{org}"
end

def hide_sensitive_data(message)
pattern = @sensitive_data_pattern
return message unless pattern.is_a?(Regexp)

message.gsub(pattern, "XXXXXXX")
end
end
25 changes: 23 additions & 2 deletions lib/core/shell.rb
Original file line number Diff line number Diff line change
Expand Up @@ -55,11 +55,32 @@ def self.verbose_mode(verbose)
@verbose = verbose
end

def self.debug(prefix, message)
stderr.puts("\n[#{color(prefix, :red)}] #{message}") if verbose
def self.debug(prefix, message, sensitive_data_pattern: nil)
filtered_message = hide_sensitive_data(message, sensitive_data_pattern)

stderr.puts("\n[#{color(prefix, :red)}] #{filtered_message}") if verbose
end

def self.should_hide_output?
tmp_stderr && !verbose
end

#
# Hide sensitive data based on the passed pattern
#
# @param [String] message
# The message to get processed.
# @param [Regexp, nil] pattern
# The regular expression to be used. If not provided, no filter gets applied.
#
# @return [String]
# Filtered message.
#
# @example
# hide_sensitive_data("--token abcd", /(?<=--token )(\S+)/)
def self.hide_sensitive_data(message, pattern = nil)
return message unless pattern.is_a?(Regexp)

message.gsub(pattern, "XXXXXXX")
end
end

0 comments on commit f0a267a

Please sign in to comment.