Skip to content

Commit

Permalink
Hashids can blow up with null chars in alphabet
Browse files Browse the repository at this point in the history
  • Loading branch information
stevegeek committed Oct 17, 2023
1 parent 04d3152 commit aa55bcf
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
2 changes: 1 addition & 1 deletion lib/encoded_id/alphabet.rb
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ def unique_character_alphabet(characters)
end

def valid_characters?
unique_characters.size > 0 && unique_characters.grep(/\s/).size == 0
unique_characters.size > 0 && unique_characters.grep(/\s|\0/).size == 0
end

def sufficient_characters?
Expand Down
16 changes: 15 additions & 1 deletion test/encoded_id/test_alphabet.rb
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@ def test_initialize_with_valid_alphabet_array
assert_nil alphabet.equivalences
end

def test_it_allows_non_ascii_chars
alphabet = EncodedId::Alphabet.new("9$�+OmlϏ횲_F123456789")
assert_equal ["9", "$", "�", "+", "O", "m", "l", "Ϗ", "횲", "_", "F", "1", "2", "3", "4", "5", "6", "7", "8"], alphabet.unique_characters
end

def test_initialize_with_invalid_alphabet
assert_raises EncodedId::InvalidAlphabetError do
EncodedId::Alphabet.new("abc")
Expand Down Expand Up @@ -78,6 +83,15 @@ def test_it_raises_with_small_alphabet
end
end

# hashids can blow up if a resulting hashed value is the string "\0" as it uses #ord of that to the do a division
# (and "\0".ord == 0)
def test_it_raises_with_null_char_in_alphabet
assert_raises EncodedId::InvalidAlphabetError do
EncodedId::Alphabet.new("abcdefghijklmnopqr\0stuvwxyz0123456789")
end
end

# Spaces are not allowed in hashids, but we also restrict other whitespace characters
def test_it_raises_with_spaces_in_alphabet
assert_raises EncodedId::InvalidAlphabetError do
EncodedId::Alphabet.new("abcdefghijklmnopqr stuvwxyz0123456789")
Expand All @@ -86,7 +100,7 @@ def test_it_raises_with_spaces_in_alphabet

def test_it_raises_with_spaces_in_alphabet_with_non_printable_chars
assert_raises EncodedId::InvalidAlphabetError do
EncodedId::Alphabet.new(Base64.strict_decode64("erSO3fbswG6Xy6WZgTOSdSBv"))
EncodedId::Alphabet.new(Base64.strict_decode64("OSTvv70r77+9T++/ve+/vW3vv73vv73vv70577+977+977+977+9K++/vWwkbe+/ve+/ve+/vc+P77+97ZqyK++/vTnvv71fRu+/vUZG77+9Rk9G77+9RjEyMzQ1NiA3ODk="))
end
end

Expand Down

0 comments on commit aa55bcf

Please sign in to comment.