Skip to content

Commit

Permalink
FIX:Equality check crashes for empty Texts (#39)
Browse files Browse the repository at this point in the history
The logic was not taking into account the possibility of arguments being
empty Texts hence was crashing on nil pointer error.

To fix the issue, firstly we expanded the example tests to cover all
possible cases and then improved logic to satisfy the tests.
  • Loading branch information
rsjethani authored Aug 16, 2024
1 parent 1de7a7e commit 6c90e62
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 6 deletions.
18 changes: 13 additions & 5 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,13 +69,21 @@ func ExampleText_UnmarshalText() {
}

func ExampleEqual() {
tx1 := secret.New("hello")
tx2 := secret.New("hello", secret.RedactAs(secret.Redacted))
tx3 := secret.New("world")
fmt.Println(secret.Equal(tx1, tx2))
fmt.Println(secret.Equal(tx1, tx3))
// Empty Texts are equal.
fmt.Println(secret.Equal(secret.Text{}, secret.Text{}))

// Initialsed Text is not equal to an empty one.
fmt.Println(secret.Equal(secret.New("hello"), secret.Text{}))

// Texts with different secret strings are not equal.
fmt.Println(secret.Equal(secret.New("hello"), secret.New("world")))

// Texts with different redact strings but same secret string are equal.
fmt.Println(secret.Equal(secret.New("hello"), secret.New("hello", secret.RedactAs(secret.FiveX))))

// Output:
// true
// false
// false
// true
}
14 changes: 13 additions & 1 deletion secret.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,19 @@ func (tx *Text) UnmarshalText(b []byte) error {
return nil
}

// Equal returns true if both arguments have the same secret. The redact strings are not considered.
// Equal returns true if both arguments have the same secret regardless of the redact strings.
func Equal(tx1, tx2 Text) bool {
// If both pointers are equal then it means either both are nil or point to same value.
if tx1.secret == tx2.secret {
return true
}

// If we are here then it means the two pointers have different values hence return false
// if any one of them is nil.
if tx1.secret == nil || tx2.secret == nil {
return false
}

// If we are here then it means both pointers are not nil hence compare the values pointed by them.
return *tx1.secret == *tx2.secret
}

0 comments on commit 6c90e62

Please sign in to comment.