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 df2b76a
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 5 deletions.
13 changes: 8 additions & 5 deletions lib/kamal/utils.rb
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,13 @@ 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)
# Doublequotes are treated literally in docker env files
# so remove leading and trailing ones and unescape any others
value.to_s.dump[1..-2].gsub(/\\"/, "\"")
end

# Abbreviate a git revhash for concise display
def abbreviate_version(version)
if version
Expand All @@ -109,10 +116,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 df2b76a

Please sign in to comment.