feat(identity): hash passwords with Argon2id and bounded inputs

This commit is contained in:
shira committed 2026-10-06 01:07:55 +03:00
1 parent 6153887eb5
commit dda3825786
26 files changed
+1475 -32

No files matched your search

@@ -0,0 +1,304 @@
// Package argon2id implements outbound.PasswordHasher with Argon2id (RFC 9106)
// from golang.org/x/crypto/argon2 and the PHC string format.
package argon2id
import (
"context"
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"errors"
"fmt"
"strconv"
"strings"
"golang.org/x/crypto/argon2"
"golang.org/x/sync/semaphore"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// Parameters of new hashes: the second recommended option of RFC 9106,
// section 4 (64 MiB, 3 passes, 4 lanes). It is stronger than the OWASP
// Password Storage Cheat Sheet baseline (19 MiB, 2 passes, 1 lane).
const (
recommendedMemoryKiB = 64 * 1024
recommendedIterations = 3
recommendedParallelism = 4
// RFC 9106 recommends a 128-bit salt and a 256-bit tag.
saltBytes = 16
keyBytes = 32
)
// Bounds for stored hashes. Verify recomputes a hash with the parameters
// stored in it, so a crafted or corrupted row must not be able to demand
// unbounded memory or time. They leave room to raise the current parameters
// and still verify older hashes until a login rehashes them. A stored hash
// must also fit the memory budget of the hasher (see Hasher).
const (
maxStoredMemoryKiB = 2 * recommendedMemoryKiB
maxStoredIterations = 16
maxStoredParallelism = 16
// Argon2 needs at least 8 KiB per lane; x/crypto silently raises a lower
// value, which no conforming encoder writes.
minMemoryKiBPerLane = 8
// The salt and digest minimums match domain.NewPasswordHash.
minStoredSaltBytes = 8
maxStoredSaltBytes = 64
minStoredKeyBytes = 16
maxStoredKeyBytes = 64
phcFieldCount = 6
phcParameterCount = 3
)
type parameters struct {
memoryKiB uint32
iterations uint32
parallelism uint8
}
func recommendedParameters() parameters {
return parameters{
memoryKiB: recommendedMemoryKiB,
iterations: recommendedIterations,
parallelism: recommendedParallelism,
}
}
// Hasher is safe for concurrent use. Derivations share a memory budget of
// concurrency times the current memory parameter: each one holds its own
// memory parameter in a weighted semaphore while it runs, so at most
// concurrency current-parameter derivations run at once, and a stored hash
// with a larger memory parameter takes a larger share. Other calls wait in
// FIFO order until the budget frees up or their context ends; the queue is
// bounded only by the callers' contexts, and request rate limiting belongs
// to the HTTP layer.
type Hasher struct {
current parameters
budgetKiB int64
memory *semaphore.Weighted
// dummy has the current parameters, a random salt, and a random digest
// that no password derives in practice.
dummy domain.PasswordHash
}
var _ outbound.PasswordHasher = (*Hasher)(nil)
// NewHasher returns a hasher with the RFC 9106 parameters and a memory
// budget for concurrency derivations with those parameters.
func NewHasher(concurrency int) (*Hasher, error) {
return newHasher(recommendedParameters(), concurrency)
}
func newHasher(current parameters, concurrency int) (*Hasher, error) {
if concurrency < 1 {
return nil, errors.New("argon2id.newHasher - concurrency must be positive")
}
if violation := current.violation(); violation != "" {
return nil, errors.New("argon2id.newHasher - " + violation)
}
salt, err := randomBytes(saltBytes)
if err != nil {
return nil, fmt.Errorf("argon2id.newHasher - generate dummy salt: %w", err)
}
digest, err := randomBytes(keyBytes)
if err != nil {
return nil, fmt.Errorf("argon2id.newHasher - generate dummy digest: %w", err)
}
dummy, err := domain.NewPasswordHash(encodePHC(current, salt, digest))
if err != nil {
return nil, fmt.Errorf("argon2id.newHasher - encode dummy hash: %w", err)
}
budgetKiB := int64(concurrency) * int64(current.memoryKiB)
return &Hasher{
current: current,
budgetKiB: budgetKiB,
memory: semaphore.NewWeighted(budgetKiB),
dummy: dummy,
}, nil
}
// Hash derives a 32-byte key with a fresh 16-byte salt from crypto/rand.
func (hasher *Hasher) Hash(ctx context.Context, password domain.Password) (domain.PasswordHash, error) {
if password.IsZero() {
return domain.PasswordHash{}, fmt.Errorf("Hasher.Hash - password must be built by a domain constructor: %w", domain.ErrInvalidPassword)
}
salt, err := randomBytes(saltBytes)
if err != nil {
return domain.PasswordHash{}, fmt.Errorf("Hasher.Hash - generate salt: %w", err)
}
key, err := hasher.derive(ctx, password, hasher.current, salt, keyBytes)
if err != nil {
return domain.PasswordHash{}, fmt.Errorf("Hasher.Hash - derive key: %w", err)
}
hash, err := domain.NewPasswordHash(encodePHC(hasher.current, salt, key))
if err != nil {
return domain.PasswordHash{}, fmt.Errorf("Hasher.Hash - encode hash: %w", err)
}
return hash, nil
}
// Verify recomputes the key with the salt, parameters, and key length stored
// in the hash and compares it in constant time.
func (hasher *Hasher) Verify(ctx context.Context, password domain.Password, stored domain.PasswordHash) (bool, error) {
if password.IsZero() {
return false, fmt.Errorf("Hasher.Verify - password must be built by a domain constructor: %w", domain.ErrInvalidPassword)
}
decoded, err := parsePHC(stored.PHC())
if err != nil {
return false, fmt.Errorf("Hasher.Verify - parse stored hash: %w", err)
}
// The semaphore would block until the context ends on a weight above its
// size, so such a hash is refused up front.
if int64(decoded.parameters.memoryKiB) > hasher.budgetKiB {
return false, corruptHash("Hasher.Verify", "memory exceeds the hashing budget")
}
keyLength := uint32(len(decoded.key)) //nolint:gosec // parsePHC bounds the digest to 64 bytes.
key, err := hasher.derive(ctx, password, decoded.parameters, decoded.salt, keyLength)
if err != nil {
return false, fmt.Errorf("Hasher.Verify - derive key: %w", err)
}
if subtle.ConstantTimeCompare(key, decoded.key) != 1 {
return false, fmt.Errorf("Hasher.Verify - compare keys: %w", outbound.ErrPasswordMismatch)
}
needsRehash := decoded.parameters != hasher.current || len(decoded.salt) != saltBytes || len(decoded.key) != keyBytes
return needsRehash, nil
}
// VerifyDummy runs Verify against the dummy hash, so it parses, waits for a
// slot, derives, and compares exactly as a real verification does.
func (hasher *Hasher) VerifyDummy(ctx context.Context, password domain.Password) error {
_, err := hasher.Verify(ctx, password, hasher.dummy)
if err != nil {
return fmt.Errorf("Hasher.VerifyDummy - verify dummy hash: %w", err)
}
// Unreachable in practice (a 2^-256 chance); fail closed all the same.
return fmt.Errorf("Hasher.VerifyDummy - dummy hash matched: %w", outbound.ErrPasswordMismatch)
}
func (hasher *Hasher) derive(ctx context.Context, password domain.Password, params parameters, salt []byte, keyLength uint32) ([]byte, error) {
weight := int64(params.memoryKiB)
if err := hasher.acquire(ctx, weight); err != nil {
return nil, err
}
defer hasher.memory.Release(weight)
secret := []byte(password.Reveal())
// Best effort: this clears only the byte copy handed to Argon2. The
// normalized string inside domain.Password cannot be wiped in Go and stays
// in memory until the garbage collector reuses it.
defer clear(secret)
return argon2.IDKey(secret, salt, params.iterations, params.memoryKiB, params.parallelism, keyLength), nil
}
// acquire checks the context first, because Acquire may succeed on an ended
// context when the budget is free.
func (hasher *Hasher) acquire(ctx context.Context, weight int64) error {
if err := ctx.Err(); err != nil {
return fmt.Errorf("Hasher.acquire - context ended before hashing: %w", err)
}
if err := hasher.memory.Acquire(ctx, weight); err != nil {
return fmt.Errorf("Hasher.acquire - wait for hashing memory: %w", err)
}
return nil
}
func randomBytes(size int) ([]byte, error) {
buffer := make([]byte, size)
if _, err := rand.Read(buffer); err != nil {
return nil, fmt.Errorf("argon2id.randomBytes - read random bytes: %w", err)
}
return buffer, nil
}
// encodePHC writes $argon2id$v=19$m=<KiB>,t=<passes>,p=<lanes>$<salt>$<key>
// with unpadded standard base64, the format of the reference implementation.
func encodePHC(params parameters, salt, key []byte) string {
return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
argon2.Version, params.memoryKiB, params.iterations, params.parallelism,
base64.RawStdEncoding.EncodeToString(salt), base64.RawStdEncoding.EncodeToString(key))
}
type decodedHash struct {
parameters parameters
salt []byte
key []byte
}
// parsePHC accepts only what encodePHC writes: Argon2id version 19, the
// parameters in the order m, t, p as decimals without leading zeros, and
// unpadded standard base64. Every failure wraps outbound.ErrPasswordHashCorrupt,
// and through it domain.ErrInvalidPasswordHash, and never quotes the input.
func parsePHC(encoded string) (decodedHash, error) {
fields := strings.Split(encoded, "$")
if len(fields) != phcFieldCount || fields[0] != "" || fields[1] != "argon2id" {
return decodedHash{}, corruptHash("argon2id.parsePHC", "hash must be an Argon2id PHC string")
}
if fields[2] != "v="+strconv.Itoa(argon2.Version) {
return decodedHash{}, corruptHash("argon2id.parsePHC", "hash must use Argon2 version 19")
}
params, err := parseParameters(fields[3])
if err != nil {
return decodedHash{}, err
}
salt, err := base64.RawStdEncoding.Strict().DecodeString(fields[4])
if err != nil || len(salt) < minStoredSaltBytes || len(salt) > maxStoredSaltBytes {
return decodedHash{}, corruptHash("argon2id.parsePHC", "salt must be unpadded base64 of 8 to 64 bytes")
}
key, err := base64.RawStdEncoding.Strict().DecodeString(fields[5])
if err != nil || len(key) < minStoredKeyBytes || len(key) > maxStoredKeyBytes {
return decodedHash{}, corruptHash("argon2id.parsePHC", "digest must be unpadded base64 of 16 to 64 bytes")
}
return decodedHash{parameters: params, salt: salt, key: key}, nil
}
func parseParameters(field string) (parameters, error) {
values := strings.Split(field, ",")
if len(values) != phcParameterCount {
return parameters{}, corruptHash("argon2id.parseParameters", "parameters must be m, t, and p")
}
memory, memoryOK := parseParameter(values[0], "m=", 32)
iterations, iterationsOK := parseParameter(values[1], "t=", 32)
parallelism, parallelismOK := parseParameter(values[2], "p=", 8)
if !memoryOK || !iterationsOK || !parallelismOK {
return parameters{}, corruptHash("argon2id.parseParameters", "parameters must be m, t, and p as decimals without leading zeros")
}
params := parameters{
memoryKiB: uint32(memory), //nolint:gosec // ParseUint limited the value to 32 bits.
iterations: uint32(iterations), //nolint:gosec // ParseUint limited the value to 32 bits.
parallelism: uint8(parallelism), //nolint:gosec // ParseUint limited the value to 8 bits.
}
if violation := params.violation(); violation != "" {
return parameters{}, corruptHash("argon2id.parseParameters", violation)
}
return params, nil
}
// parseParameter reads one "<prefix><decimal>" value that fits bitSize bits.
func parseParameter(value, prefix string, bitSize int) (uint64, bool) {
digits, found := strings.CutPrefix(value, prefix)
if !found || digits == "" || digits[0] == '0' {
return 0, false
}
number, err := strconv.ParseUint(digits, 10, bitSize)
return number, err == nil
}
// violation returns the stored-hash bound that params break, or "". The
// current parameters must pass it too, so every new hash stays verifiable.
func (params parameters) violation() string {
switch {
case params.parallelism < 1 || params.parallelism > maxStoredParallelism:
return "parallelism must be between 1 and 16"
case params.iterations < 1 || params.iterations > maxStoredIterations:
return "iterations must be between 1 and 16"
case params.memoryKiB < minMemoryKiBPerLane*uint32(params.parallelism) || params.memoryKiB > maxStoredMemoryKiB:
return "memory must be between 8 KiB per lane and 128 MiB"
default:
return ""
}
}
func corruptHash(location, reason string) error {
return fmt.Errorf("%s - %s: %w", location, reason, outbound.ErrPasswordHashCorrupt)
}
@@ -0,0 +1,433 @@
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)
}
}
}