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

sanitize_null_bytes should add the unicode replacement character #81

Open
collimarco opened this issue Nov 25, 2023 · 2 comments
Open

Comments

@collimarco
Copy link

Thanks for this useful gem. Currently if you use the default :replace strategy, invalid characters are replaced with �, but the null byte is replace with nothing.

This behavior seems unexpected and inconsistent.

Expected: "Hello \x00 world" => "Hello � world"
Actual: "Hello \x00 world" => "Hello world"

@collimarco
Copy link
Author

The fix would be straightforward, we just need to change this line:

input = input.gsub(NULL_BYTE_REGEX, "")

Even the test looks strange (it suggests a replacement, but it actually removes null bytes):

it "optionally sanitizes null bytes with the replace strategy" do

If this choice is by design (is it good? is it bad?), it should be clarified in the documentation in any case, because this is definitely not what you expect from reading the docs.

@geoffharcourt
Copy link
Contributor

Hi @collimarco this is achievable with a custom strategy without too much code:

# config/application.rb

replace_null_byte = lambda do |input, sanitize_null_bytes: true|
   input.
     force_encoding(Encoding::ASCII_8BIT).
     encode!(Encoding::UTF_8,
             invalid: :replace,
             undef:   :replace)

  if sanitize_null_bytes && input =~ Rack::UTF8Sanitizer::NULL_BYTE_REGEX
    input = input.gsub(Rack::UTF8Sanitizer::NULL_BYTE_REGEX, "")
  end

  input
end

config.middleware.insert 0, Rack::UTF8Sanitizer, sanitize_null_bytes: true, strategy: replace_null_byte

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants