Skip to content

Commit

Permalink
Treat secrets as binary
Browse files Browse the repository at this point in the history
Until Rails 5.1.1 secrets was treated as binary inside Rails.
https://github.com/rails/rails/blob/v5.1.1/railties/lib/rails/secrets.rb#L59
https://github.com/rails/rails/blob/v5.1.1/railties/lib/rails/secrets.rb#L63

However, it is treated as String in Rails 5.1.2(changed by 157db87).
https://github.com/rails/rails/blob/v5.1.2/railties/lib/rails/secrets.rb#L104
https://github.com/rails/rails/blob/v5.1.2/railties/lib/rails/secrets.rb#L108

As a result, when upgrading from Rails 5.1.1 to 5.1.2, to write the value
treated as binary using `File.write`, causing an error.

In order to avoid `UndefinedConversionError`, fixed it to treat it as
binary like 5.1.1.
Fixes #29696
  • Loading branch information
y-yagi committed Jul 9, 2017
1 parent 650ea5e commit be4ebc4
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
4 changes: 2 additions & 2 deletions railties/lib/rails/secrets.rb
Original file line number Diff line number Diff line change
Expand Up @@ -101,11 +101,11 @@ def preprocess(path)

def writing(contents)
tmp_path = File.join(Dir.tmpdir, File.basename(path))
File.write(tmp_path, contents)
IO.binwrite(tmp_path, contents)

yield tmp_path

updated_contents = File.read(tmp_path)
updated_contents = IO.binread(tmp_path)

write(updated_contents) if updated_contents != contents
ensure
Expand Down
34 changes: 34 additions & 0 deletions railties/test/secrets_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,40 @@ def teardown
end
end

test "can read secrets written in binary" do
run_secrets_generator do
secrets = <<-end_of_secrets
production:
api_key: 00112233445566778899aabbccddeeff…
end_of_secrets

Rails::Secrets.write(secrets.force_encoding(Encoding::ASCII_8BIT))

Rails::Secrets.read_for_editing do |tmp_path|
assert_match(/production:\n\s*api_key: 00112233445566778899aabbccddeeff…\n/, File.read(tmp_path))
end

assert_equal "00112233445566778899aabbccddeeff…\n", `bin/rails runner -e production "puts Rails.application.secrets.api_key"`
end
end

test "can read secrets written in non-binary" do
run_secrets_generator do
secrets = <<-end_of_secrets
production:
api_key: 00112233445566778899aabbccddeeff…
end_of_secrets

Rails::Secrets.write(secrets)

Rails::Secrets.read_for_editing do |tmp_path|
assert_equal(secrets.force_encoding(Encoding::ASCII_8BIT), IO.binread(tmp_path))
end

assert_equal "00112233445566778899aabbccddeeff…\n", `bin/rails runner -e production "puts Rails.application.secrets.api_key"`
end
end

private
def run_secrets_generator
Dir.chdir(app_path) do
Expand Down

0 comments on commit be4ebc4

Please sign in to comment.