Skip to content

Commit

Permalink
Escape newlines in docker env files
Browse files Browse the repository at this point in the history
When env variables were passed via `-e` newlines were escaped. This
updates the env file to do the same thing.
  • Loading branch information
djmb committed Sep 12, 2023
1 parent 70a3c71 commit d595ee1
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 5 deletions.
12 changes: 7 additions & 5 deletions lib/kamal/utils.rb
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,12 @@ def escape_shell_value(value)
.gsub(DOLLAR_SIGN_WITHOUT_SHELL_EXPANSION_REGEX, '\$')
end

# Escape a value to make it safe to dump in a docker file.
def escape_docker_env_file_value(value)
# Remove leading and trailing `"` as docker env files don't parse them
value.to_s.dump[1..-2]
end

# Abbreviate a git revhash for concise display
def abbreviate_version(version)
if version
Expand All @@ -109,10 +115,6 @@ def uncommitted_changes
end

def docker_env_file_line(key, value)
if key.include?("\n") || value.to_s.include?("\n")
raise ArgumentError, "docker env file format does not support newlines in keys or values, key: #{key}"
end

"#{key.to_s}=#{value.to_s}\n"
"#{key.to_s}=#{escape_docker_env_file_value(value)}\n"
end
end
24 changes: 24 additions & 0 deletions test/utils_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,30 @@ class UtilsTest < ActiveSupport::TestCase
ENV.delete "PASSWORD"
end

test "env file secret escaped newline" do
ENV["PASSWORD"] = "hello\\nthere"
env = {
"secret" => [ "PASSWORD" ]
}

assert_equal "PASSWORD=hello\\\\nthere\n", \
Kamal::Utils.env_file_with_secrets(env)
ensure
ENV.delete "PASSWORD"
end

test "env file secret newline" do
ENV["PASSWORD"] = "hello\nthere"
env = {
"secret" => [ "PASSWORD" ]
}

assert_equal "PASSWORD=hello\\nthere\n", \
Kamal::Utils.env_file_with_secrets(env)
ensure
ENV.delete "PASSWORD"
end

test "env file missing secret" do
env = {
"secret" => [ "PASSWORD" ]
Expand Down

0 comments on commit d595ee1

Please sign in to comment.