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

ENV#[]=: Disallow null bytes in key and value #5216

Merged
merged 1 commit into from
Nov 1, 2017
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
20 changes: 20 additions & 0 deletions spec/std/env_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,26 @@ describe "ENV" do
[1, 2].each { |i| ENV.values.should contain("SOMEVALUE_#{i}") }
end

describe "[]=" do
it "disallows NUL-bytes in key" do
expect_raises(ArgumentError, "Key contains null byte") do
ENV["FOO\0BAR"] = "something"
end
end

it "disallows NUL-bytes in key if value is nil" do
expect_raises(ArgumentError, "Key contains null byte") do
ENV["FOO\0BAR"] = nil
end
end

it "disallows NUL-bytes in value" do
expect_raises(ArgumentError, "Value contains null byte") do
ENV["FOO"] = "BAR\0BAZ"
end
end
end

describe "fetch" do
it "fetches with one argument" do
ENV["1"] = "2"
Expand Down
8 changes: 7 additions & 1 deletion src/env.cr
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,16 @@ module ENV
# Overwrites existing environment variable if already present.
# Returns *value* if successful, otherwise raises an exception.
# If *value* is `nil`, the environment variable is deleted.
#
# If *key* or *value* contains a null-byte an `ArgumentError` is raised.
def self.[]=(key : String, value : String?)
raise ArgumentError.new("Key contains null byte") if key.byte_index(0)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can simply do key.check_no_null_byte

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same applies to value, of course

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes I had that at first, but then chose to tell if the key or the value is the culprit

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ooooh... makes sense!


if value
raise ArgumentError.new("Value contains null byte") if value.byte_index(0)

if LibC.setenv(key, value, 1) != 0
raise Errno.new("Error setting environment variable \"#{key}\"")
raise Errno.new("Error setting environment variable #{key.inspect}")
end
else
LibC.unsetenv(key)
Expand Down