Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Escape newlines in docker env files #459

Merged
merged 1 commit into from
Sep 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading