Skip to content

Commit

Permalink
Check nil values in SHA256.equal/2
Browse files Browse the repository at this point in the history
- See #53
- Check for nil values in `equal?/2` to avoid call `String.valid/1` on
  nil
  • Loading branch information
SimonLab committed Apr 12, 2024
1 parent 05ea920 commit 5cc7b30
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 0 deletions.
4 changes: 4 additions & 0 deletions lib/cloak_ecto/types/sha_256.ex
Expand Up @@ -77,6 +77,10 @@ defmodule Cloak.Ecto.SHA256 do

@doc false
@impl Ecto.Type
def equal?(nil, nil), do: true
def equal?(nil, _value), do: false
def equal?(_value, nil), do: false

def equal?(value1, value2) do
hash_string(value1) == hash_string(value2)
end
Expand Down
3 changes: 3 additions & 0 deletions test/cloak_ecto/types/sha256_test.exs
Expand Up @@ -32,6 +32,7 @@ defmodule Cloak.Ecto.SHA256Test do

describe ".equal?/2" do
test "return true on same values and hashed values" do
assert Field.equal?(nil, nil)
assert Field.equal?("value", "value")
assert Field.equal?(:crypto.hash(:sha256, "value"), :crypto.hash(:sha256, "value"))
assert Field.equal?("value", :crypto.hash(:sha256, "value"))
Expand All @@ -41,6 +42,8 @@ defmodule Cloak.Ecto.SHA256Test do
test "return false on different values" do
refute Field.equal?("value", "not equal")
refute Field.equal?(:crypto.hash(:sha256, "value"), :crypto.hash(:sha256, "not equal"))
refute Field.equal?(nil, "not equal")
refute Field.equal?("not equal", nil)
end
end
end

0 comments on commit 5cc7b30

Please sign in to comment.