Skip to content
Open
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
21 changes: 6 additions & 15 deletions lib/kamal/env_file.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,22 +23,13 @@ def to_io

private
def docker_env_file_line(key, value)
"#{key}=#{escape_docker_env_file_value(value)}\n"
end
value = value.to_s

# Escape a value to make it safe to dump in a docker file.
def escape_docker_env_file_value(value)
# keep non-ascii(UTF-8) characters as it is
value.to_s.scan(/[\x00-\x7F]+|[^\x00-\x7F]+/).map do |part|
part.ascii_only? ? escape_docker_env_file_ascii_value(part) : part
end.join
end
# Docker env files don't support escape sequences, so newlines and null
# bytes cannot be represented. Raise an error rather than silently corrupt.
raise ArgumentError, "Env file values cannot contain newlines" if value.include?("\n")
raise ArgumentError, "Env file values cannot contain null bytes" if value.include?("\0")

def escape_docker_env_file_ascii_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(/\\"/, "\"")
.gsub(/\\#/, "#")
"#{key}=#{value}\n"
end
end
10 changes: 5 additions & 5 deletions test/env_file_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -57,21 +57,21 @@ class EnvFileTest < ActiveSupport::TestCase
"foo" => "hello\\nthere"
}

assert_equal "foo=hello\\\\nthere\n", \
# Literal backslash-n should be preserved, not double-escaped
assert_equal "foo=hello\\nthere\n", \
Kamal::EnvFile.new(env).to_s
ensure
ENV.delete "PASSWORD"
end

test "to_s newline" do
test "to_s newline raises" do
env = {
"foo" => "hello\nthere"
}

assert_equal "foo=hello\\nthere\n", \
assert_raises ArgumentError do
Kamal::EnvFile.new(env).to_s
ensure
ENV.delete "PASSWORD"
end
end

test "stringIO conversion" do
Expand Down