Files

434 lines
17 KiB
Go

package argon2id
import (
"bytes"
"context"
"encoding/base64"
"errors"
"fmt"
"log/slog"
"strings"
"testing"
"time"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
const testRawPassword = "correct horse battery staple"
// cheapParameters keep unit tests fast under the race detector. Tests that
// need the production cost use NewHasher.
var cheapParameters = parameters{memoryKiB: 64, iterations: 1, parallelism: 1}
func newCheapHasher(t *testing.T, concurrency int) *Hasher {
t.Helper()
hasher, err := newHasher(cheapParameters, concurrency)
if err != nil {
t.Fatalf("newHasher() error = %v", err)
}
return hasher
}
func newTestPassword(t *testing.T, raw string) domain.Password {
t.Helper()
password, err := domain.ParseLoginPassword(raw)
if err != nil {
t.Fatalf("ParseLoginPassword() error = %v", err)
}
return password
}
// holdBudget takes the whole memory budget so that any derivation blocks,
// and returns the release function.
func holdBudget(t *testing.T, hasher *Hasher) func() {
t.Helper()
if !hasher.memory.TryAcquire(hasher.budgetKiB) {
t.Fatal("the hashing budget is already in use")
}
return func() { hasher.memory.Release(hasher.budgetKiB) }
}
func mustPasswordHash(t *testing.T, phc string) domain.PasswordHash {
t.Helper()
hash, err := domain.NewPasswordHash(phc)
if err != nil {
t.Fatalf("NewPasswordHash() error = %v", err)
}
return hash
}
func TestNewHasherUsesTheRecommendedParameters(t *testing.T) {
hasher, err := NewHasher(1)
if err != nil {
t.Fatalf("NewHasher() error = %v", err)
}
password := newTestPassword(t, testRawPassword)
hash, err := hasher.Hash(context.Background(), password)
if err != nil {
t.Fatalf("Hash() error = %v", err)
}
if !strings.HasPrefix(hash.PHC(), "$argon2id$v=19$m=65536,t=3,p=4$") {
t.Fatal("Hash() did not use Argon2id v19 with m=65536, t=3, p=4")
}
decoded, err := parsePHC(hash.PHC())
if err != nil {
t.Fatalf("parsePHC(Hash()) error = %v", err)
}
if len(decoded.salt) != saltBytes || len(decoded.key) != keyBytes {
t.Fatalf("salt and key lengths = %d, %d, want %d, %d", len(decoded.salt), len(decoded.key), saltBytes, keyBytes)
}
needsRehash, err := hasher.Verify(context.Background(), password, hash)
if err != nil || needsRehash {
t.Fatalf("Verify(correct password) = %v, %v, want false, nil", needsRehash, err)
}
}
func TestHashUsesAUniqueSaltAndBothHashesVerify(t *testing.T) {
hasher := newCheapHasher(t, 2)
password := newTestPassword(t, testRawPassword)
first, err := hasher.Hash(context.Background(), password)
if err != nil {
t.Fatalf("Hash() error = %v", err)
}
second, err := hasher.Hash(context.Background(), password)
if err != nil {
t.Fatalf("Hash() error = %v", err)
}
firstDecoded, err := parsePHC(first.PHC())
if err != nil {
t.Fatalf("parsePHC() error = %v", err)
}
secondDecoded, err := parsePHC(second.PHC())
if err != nil {
t.Fatalf("parsePHC() error = %v", err)
}
if bytes.Equal(firstDecoded.salt, secondDecoded.salt) || bytes.Equal(firstDecoded.key, secondDecoded.key) {
t.Fatal("two hashes of the same password share a salt or a key")
}
for _, hash := range []domain.PasswordHash{first, second} {
if needsRehash, err := hasher.Verify(context.Background(), password, hash); err != nil || needsRehash {
t.Fatalf("Verify() = %v, %v, want false, nil", needsRehash, err)
}
}
}
func TestVerifyRejectsAWrongPassword(t *testing.T) {
hasher := newCheapHasher(t, 1)
hash, err := hasher.Hash(context.Background(), newTestPassword(t, testRawPassword))
if err != nil {
t.Fatalf("Hash() error = %v", err)
}
for _, raw := range []string{"correct horse battery stapl", "Correct horse battery staple", "x"} {
needsRehash, err := hasher.Verify(context.Background(), newTestPassword(t, raw), hash)
if !errors.Is(err, outbound.ErrPasswordMismatch) || needsRehash {
t.Fatalf("Verify(wrong password) = %v, %v, want false, ErrPasswordMismatch", needsRehash, err)
}
if errors.Is(err, outbound.ErrPasswordHashCorrupt) {
t.Fatal("a wrong password was reported as a corrupt hash")
}
}
}
func TestVerifyRejectsATamperedDigestAsAMismatch(t *testing.T) {
hasher := newCheapHasher(t, 1)
password := newTestPassword(t, testRawPassword)
hash, err := hasher.Hash(context.Background(), password)
if err != nil {
t.Fatalf("Hash() error = %v", err)
}
decoded, err := parsePHC(hash.PHC())
if err != nil {
t.Fatalf("parsePHC() error = %v", err)
}
decoded.key[0] ^= 0x01
tampered := mustPasswordHash(t, encodePHC(decoded.parameters, decoded.salt, decoded.key))
if _, err := hasher.Verify(context.Background(), password, tampered); !errors.Is(err, outbound.ErrPasswordMismatch) {
t.Fatalf("Verify(tampered digest) error = %v, want ErrPasswordMismatch", err)
}
}
func TestVerifyMatchesTheReferenceImplementation(t *testing.T) {
tests := map[string]struct {
phc string
heavy bool
}{
// The Argon2id test of phc-winner-argon2 src/test.c (password
// "password", salt "somesalt"), the encoded form of the reference
// implementation. It takes 64 MiB.
"phc-winner-argon2 test.c": {
phc: "$argon2id$v=19$m=65536,t=2,p=1$c29tZXNhbHQ$CTFhFdXPJO1aFaMaO6Mm5c8y7cJHAph8ArZWb2GRPPc",
heavy: true,
},
// The m=4096, t=4, p=4 entry of testVectors in
// golang.org/x/crypto/argon2/argon2_test.go, which that file states was
// generated with the phc-winner-argon2 CLI (24-byte tag), encoded here
// as PHC.
"x/crypto CLI vector": {phc: "$argon2id$v=19$m=4096,t=4,p=4$c29tZXNhbHQ$FF25czqfTuQ+3zPFCb6WuTTVBaTvszxa"},
}
// The budget of one production derivation fits both vectors.
hasher, err := NewHasher(1)
if err != nil {
t.Fatalf("NewHasher() error = %v", err)
}
for name, test := range tests {
if test.heavy && testing.Short() {
continue
}
needsRehash, err := hasher.Verify(context.Background(), newTestPassword(t, "password"), mustPasswordHash(t, test.phc))
if err != nil {
t.Fatalf("Verify(%s) error = %v", name, err)
}
if !needsRehash {
t.Fatalf("Verify(%s) did not request a rehash for other parameters or sizes", name)
}
if _, err := hasher.Verify(context.Background(), newTestPassword(t, "passwore"), mustPasswordHash(t, test.phc)); !errors.Is(err, outbound.ErrPasswordMismatch) {
t.Fatalf("Verify(%s, wrong password) error = %v, want ErrPasswordMismatch", name, err)
}
}
}
func TestVerifyReportsRehashForOtherParameters(t *testing.T) {
password := newTestPassword(t, testRawPassword)
older := newCheapHasher(t, 1)
hash, err := older.Hash(context.Background(), password)
if err != nil {
t.Fatalf("Hash() error = %v", err)
}
stronger, err := newHasher(parameters{memoryKiB: 128, iterations: 2, parallelism: 1}, 1)
if err != nil {
t.Fatalf("newHasher() error = %v", err)
}
needsRehash, err := stronger.Verify(context.Background(), password, hash)
if err != nil || !needsRehash {
t.Fatalf("Verify(older parameters) = %v, %v, want true, nil", needsRehash, err)
}
}
func TestVerifyRejectsCorruptHashesWithoutDerivation(t *testing.T) {
salt := base64.RawStdEncoding.EncodeToString([]byte("saltsaltsaltsalt"))
digest := base64.RawStdEncoding.EncodeToString(bytes.Repeat([]byte{7}, keyBytes))
// Each value passes domain.NewPasswordHash, so only the hasher's bounds
// stop it.
tests := map[string]string{
"huge memory": "$argon2id$v=19$m=4294967295,t=1,p=1$" + salt + "$" + digest,
"memory over 128 MiB": "$argon2id$v=19$m=131073,t=1,p=1$" + salt + "$" + digest,
"memory over the budget": "$argon2id$v=19$m=128,t=1,p=1$" + salt + "$" + digest,
"memory below 8 KiB/lane": "$argon2id$v=19$m=31,t=1,p=4$" + salt + "$" + digest,
"memory over uint32": "$argon2id$v=19$m=4294967296,t=1,p=1$" + salt + "$" + digest,
"huge iterations": "$argon2id$v=19$m=64,t=4294967295,p=1$" + salt + "$" + digest,
"iterations over 16": "$argon2id$v=19$m=64,t=17,p=1$" + salt + "$" + digest,
"parallelism over 16": "$argon2id$v=19$m=256,t=1,p=17$" + salt + "$" + digest,
"parallelism over uint8": "$argon2id$v=19$m=4096,t=1,p=256$" + salt + "$" + digest,
"salt over 64 bytes": "$argon2id$v=19$m=64,t=1,p=1$" + base64.RawStdEncoding.EncodeToString(make([]byte, 65)) + "$" + digest,
"digest over 64 bytes": "$argon2id$v=19$m=64,t=1,p=1$" + salt + "$" + base64.RawStdEncoding.EncodeToString(make([]byte, 65)),
}
// The budget is already taken: a derivation would block until the context
// ends, so a quick ErrPasswordHashCorrupt proves none started. The budget
// of one cheap derivation is 64 KiB.
hasher := newCheapHasher(t, 1)
defer holdBudget(t, hasher)()
password := newTestPassword(t, testRawPassword)
for name, phc := range tests {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
needsRehash, err := hasher.Verify(ctx, password, mustPasswordHash(t, phc))
cancel()
if !errors.Is(err, outbound.ErrPasswordHashCorrupt) || needsRehash {
t.Fatalf("Verify(%s) = %v, %v, want false, ErrPasswordHashCorrupt", name, needsRehash, err)
}
if errors.Is(err, outbound.ErrPasswordMismatch) {
t.Fatalf("Verify(%s) reported a corrupt hash as a wrong password", name)
}
if !errors.Is(err, domain.ErrInvalidPasswordHash) {
t.Fatalf("Verify(%s) error = %v, want it to match domain.ErrInvalidPasswordHash too", name, err)
}
}
if _, err := hasher.Verify(context.Background(), password, domain.PasswordHash{}); !errors.Is(err, outbound.ErrPasswordHashCorrupt) {
t.Fatalf("Verify(zero hash) error = %v, want ErrPasswordHashCorrupt", err)
}
}
func TestParsePHCAcceptsOnlyTheCanonicalForm(t *testing.T) {
salt := base64.RawStdEncoding.EncodeToString([]byte("saltsaltsaltsalt"))
digest := base64.RawStdEncoding.EncodeToString(bytes.Repeat([]byte{7}, keyBytes))
valid := "$argon2id$v=19$m=64,t=1,p=1$" + salt + "$" + digest
if _, err := parsePHC(valid); err != nil {
t.Fatalf("parsePHC(valid) error = %v", err)
}
for name, phc := range map[string]string{
"empty": "",
"argon2i": strings.Replace(valid, "argon2id", "argon2i", 1),
"version 16": strings.Replace(valid, "v=19", "v=16", 1),
"missing version": strings.Replace(valid, "$v=19", "", 1),
"reordered": strings.Replace(valid, "m=64,t=1,p=1", "t=1,m=64,p=1", 1),
"leading zero": strings.Replace(valid, "m=64", "m=064", 1),
"zero iterations": strings.Replace(valid, "t=1", "t=0", 1),
"signed value": strings.Replace(valid, "t=1", "t=+1", 1),
"extra parameter": strings.Replace(valid, "p=1", "p=1,k=1", 1),
"data parameter": strings.Replace(valid, "p=1", "p=1$data=abc", 1),
"padded salt": strings.Replace(valid, salt, salt+"==", 1),
"url-safe digest": strings.Replace(valid, digest, strings.ReplaceAll(digest, "B", "-"), 1),
"short salt": strings.Replace(valid, salt, "c2FsdA", 1),
"short digest": strings.Replace(valid, digest, "aGFzaA", 1),
"trailing separator": valid + "$",
"missing leading sep": strings.TrimPrefix(valid, "$"),
} {
if _, err := parsePHC(phc); !errors.Is(err, outbound.ErrPasswordHashCorrupt) {
t.Fatalf("parsePHC(%s) error = %v, want ErrPasswordHashCorrupt", name, err)
}
}
}
func TestVerifyDummyDoesTheSameWorkAndNeverMatches(t *testing.T) {
hasher := newCheapHasher(t, 1)
dummy, err := parsePHC(hasher.dummy.PHC())
if err != nil {
t.Fatalf("parsePHC(dummy) error = %v", err)
}
if dummy.parameters != hasher.current || len(dummy.salt) != saltBytes || len(dummy.key) != keyBytes {
t.Fatal("the dummy hash does not use the current parameters and sizes")
}
other := newCheapHasher(t, 1)
if hasher.dummy.PHC() == other.dummy.PHC() {
t.Fatal("two hashers share a dummy hash")
}
err = hasher.VerifyDummy(context.Background(), newTestPassword(t, testRawPassword))
if !errors.Is(err, outbound.ErrPasswordMismatch) {
t.Fatalf("VerifyDummy() error = %v, want ErrPasswordMismatch", err)
}
// VerifyDummy waits for hashing memory like Verify does.
defer holdBudget(t, hasher)()
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
defer cancel()
if err := hasher.VerifyDummy(ctx, newTestPassword(t, testRawPassword)); !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("VerifyDummy(no free slot) error = %v, want DeadlineExceeded", err)
}
}
func TestHashingWaitsForItsShareOfTheMemoryBudget(t *testing.T) {
// Budget for two current-parameter derivations.
hasher := newCheapHasher(t, 2)
password := newTestPassword(t, testRawPassword)
hash, err := hasher.Hash(context.Background(), password)
if err != nil {
t.Fatalf("Hash() error = %v", err)
}
// A stored hash with twice the current memory needs the whole budget.
double, err := newHasher(parameters{memoryKiB: 2 * cheapParameters.memoryKiB, iterations: 1, parallelism: 1}, 1)
if err != nil {
t.Fatalf("newHasher() error = %v", err)
}
doubleHash, err := double.Hash(context.Background(), password)
if err != nil {
t.Fatalf("Hash() error = %v", err)
}
// One share taken: a current derivation still runs, a double one waits.
share := int64(cheapParameters.memoryKiB)
if !hasher.memory.TryAcquire(share) {
t.Fatal("the hashing budget is already in use")
}
if _, err := hasher.Verify(context.Background(), password, hash); err != nil {
t.Fatalf("Verify(one free share) error = %v", err)
}
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
defer cancel()
if _, err := hasher.Verify(ctx, password, doubleHash); !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("Verify(double memory, one free share) error = %v, want DeadlineExceeded", err)
}
hasher.memory.Release(share)
if needsRehash, err := hasher.Verify(context.Background(), password, doubleHash); err != nil || !needsRehash {
t.Fatalf("Verify(double memory, free budget) = %v, %v, want true, nil", needsRehash, err)
}
// The whole budget taken: every call waits until its context ends.
release := holdBudget(t, hasher)
if _, err := hasher.Hash(ctx, password); !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("Hash(no free memory) error = %v, want DeadlineExceeded", err)
}
if _, err := hasher.Verify(ctx, password, hash); !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("Verify(no free memory) error = %v, want DeadlineExceeded", err)
}
release()
canceled, cancelNow := context.WithCancel(context.Background())
cancelNow()
if _, err := hasher.Hash(canceled, password); !errors.Is(err, context.Canceled) {
t.Fatalf("Hash(canceled context) error = %v, want Canceled even with free memory", err)
}
// Failed and finished calls returned their share.
holdBudget(t, hasher)()
}
func TestHasherRejectsAZeroPasswordAndInvalidSettings(t *testing.T) {
hasher := newCheapHasher(t, 1)
hash, err := hasher.Hash(context.Background(), newTestPassword(t, testRawPassword))
if err != nil {
t.Fatalf("Hash() error = %v", err)
}
if _, err := hasher.Hash(context.Background(), domain.Password{}); !errors.Is(err, domain.ErrInvalidPassword) {
t.Fatalf("Hash(zero password) error = %v, want ErrInvalidPassword", err)
}
if _, err := hasher.Verify(context.Background(), domain.Password{}, hash); !errors.Is(err, domain.ErrInvalidPassword) {
t.Fatalf("Verify(zero password) error = %v, want ErrInvalidPassword", err)
}
if err := hasher.VerifyDummy(context.Background(), domain.Password{}); !errors.Is(err, domain.ErrInvalidPassword) {
t.Fatalf("VerifyDummy(zero password) error = %v, want ErrInvalidPassword", err)
}
for _, concurrency := range []int{0, -1} {
if _, err := NewHasher(concurrency); err == nil {
t.Fatalf("NewHasher(%d) error = nil, want an error", concurrency)
}
}
if _, err := newHasher(parameters{memoryKiB: 8, iterations: 1, parallelism: 4}, 1); err == nil {
t.Fatal("newHasher(memory below 8 KiB per lane) error = nil, want an error")
}
}
func TestErrorsAndLogsNeverContainThePasswordOrTheHash(t *testing.T) {
hasher := newCheapHasher(t, 1)
password := newTestPassword(t, testRawPassword)
hash, err := hasher.Hash(context.Background(), password)
if err != nil {
t.Fatalf("Hash() error = %v", err)
}
_, mismatch := hasher.Verify(context.Background(), newTestPassword(t, "wrong password value"), hash)
corruptPHC := "$argon2id$v=19$m=131073,t=1,p=1$c2FsdHNhbHRzYWx0c2FsdA$" + base64.RawStdEncoding.EncodeToString(bytes.Repeat([]byte{7}, keyBytes))
_, corrupt := hasher.Verify(context.Background(), password, mustPasswordHash(t, corruptPHC))
dummy := hasher.VerifyDummy(context.Background(), password)
var logs bytes.Buffer
logger := slog.New(slog.NewJSONHandler(&logs, nil))
for _, err := range []error{mismatch, corrupt, dummy} {
if err == nil {
t.Fatal("expected an error")
}
logger.Error("password check failed", "error", err, "password", password, "hash", hash)
}
output := logs.String() + fmt.Sprint(mismatch, corrupt, dummy)
for _, secret := range []string{testRawPassword, "wrong password value", hash.PHC(), corruptPHC, hasher.dummy.PHC()} {
if strings.Contains(output, secret) {
t.Fatalf("errors or logs expose a secret: %s", output)
}
}
}
// BenchmarkHashRecommendedParameters measures one Hash with the production
// parameters: go test -run '^$' -bench . ./internal/adapter/secondary/argon2id/
func BenchmarkHashRecommendedParameters(b *testing.B) {
hasher, err := NewHasher(1)
if err != nil {
b.Fatalf("NewHasher() error = %v", err)
}
password, err := domain.NewPassword(testRawPassword)
if err != nil {
b.Fatalf("NewPassword() error = %v", err)
}
for b.Loop() {
if _, err := hasher.Hash(context.Background(), password); err != nil {
b.Fatalf("Hash() error = %v", err)
}
}
}