feat(identity): hash passwords with Argon2id and bounded inputs
This commit is contained in:
1 parent
6153887eb5
commit
dda3825786
26 files changed
+1475
-32
No files matched your search
@@ -59,6 +59,10 @@ type Config struct {
|
||||
LogLevel string
|
||||
ReadinessTimeout time.Duration
|
||||
ShutdownTimeout time.Duration
|
||||
|
||||
// PasswordHashConcurrency is the number of password hash derivations
|
||||
// that may run at once; further logins and registrations wait.
|
||||
PasswordHashConcurrency int
|
||||
}
|
||||
|
||||
type LookupEnv func(string) (string, bool)
|
||||
@@ -93,6 +97,9 @@ func LoadFromEnv(lookup LookupEnv) (Config, error) {
|
||||
if err := config.loadMail(lookup); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
if err := config.loadPasswordHash(lookup); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
var err error
|
||||
config.DatabaseMigrateOnStart, err = boolOrDefault(lookup, "DATABASE_MIGRATE_ON_START", defaultDatabaseMigrateOnStart)
|
||||
@@ -134,6 +141,9 @@ func (config Config) Validate() error {
|
||||
if err := config.ValidateMail(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := config.ValidatePasswordHash(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateAddress("HTTP_ADDR", config.HTTPAddr); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
// defaultPasswordHashConcurrency is the default number of Argon2id
|
||||
// derivations with the current parameters (64 MiB, 4 lanes each) that may
|
||||
// run at once. The default is lowered to GOMAXPROCS, which Go derives from
|
||||
// the container CPU limit, because more parallel derivations than CPUs
|
||||
// only share the same CPUs while holding more memory.
|
||||
defaultPasswordHashConcurrency = 2
|
||||
// maxPasswordHashConcurrency keeps the hashing budget at 256 MiB, which
|
||||
// fits under the 600 MiB GOMEMLIMIT of the 768 MiB backend container
|
||||
// together with the rest of the process.
|
||||
maxPasswordHashConcurrency = 4
|
||||
)
|
||||
|
||||
// loadPasswordHash reads PASSWORD_HASH_CONCURRENCY. An unset value takes the
|
||||
// smaller of the default and GOMAXPROCS; an empty or non-integer value is an
|
||||
// error.
|
||||
func (config *Config) loadPasswordHash(lookup LookupEnv) error {
|
||||
config.PasswordHashConcurrency = min(defaultPasswordHashConcurrency, runtime.GOMAXPROCS(0))
|
||||
value, ok := lookup("PASSWORD_HASH_CONCURRENCY")
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
number, err := strconv.Atoi(strings.TrimSpace(value))
|
||||
if err != nil {
|
||||
return fmt.Errorf("Config.loadPasswordHash - PASSWORD_HASH_CONCURRENCY must be an integer between 1 and %d", maxPasswordHashConcurrency)
|
||||
}
|
||||
config.PasswordHashConcurrency = number
|
||||
return nil
|
||||
}
|
||||
|
||||
// ValidatePasswordHash checks the password hashing budget: the number of
|
||||
// derivations with the current parameters that may run at once.
|
||||
func (config Config) ValidatePasswordHash() error {
|
||||
if config.PasswordHashConcurrency < 1 || config.PasswordHashConcurrency > maxPasswordHashConcurrency {
|
||||
return fmt.Errorf("Config.ValidatePasswordHash - PASSWORD_HASH_CONCURRENCY must be between 1 and %d", maxPasswordHashConcurrency)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLoadFromEnvPasswordHashConcurrency(t *testing.T) {
|
||||
tests := map[string]struct {
|
||||
values map[string]string
|
||||
want int
|
||||
}{
|
||||
"default": {values: nil, want: min(2, runtime.GOMAXPROCS(0))},
|
||||
"explicit": {values: map[string]string{"PASSWORD_HASH_CONCURRENCY": "3"}, want: 3},
|
||||
"spaces": {values: map[string]string{"PASSWORD_HASH_CONCURRENCY": " 1 "}, want: 1},
|
||||
"upper bound": {values: map[string]string{"PASSWORD_HASH_CONCURRENCY": "4"}, want: 4},
|
||||
}
|
||||
for name, test := range tests {
|
||||
settings, err := LoadFromEnv(testEnvironment(test.values))
|
||||
if err != nil {
|
||||
t.Fatalf("LoadFromEnv(%s) error = %v", name, err)
|
||||
}
|
||||
if settings.PasswordHashConcurrency != test.want {
|
||||
t.Fatalf("LoadFromEnv(%s) PasswordHashConcurrency = %d, want %d", name, settings.PasswordHashConcurrency, test.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadFromEnvRejectsPasswordHashConcurrency(t *testing.T) {
|
||||
tests := map[string]struct {
|
||||
value string
|
||||
want string
|
||||
}{
|
||||
"empty": {value: "", want: "Config.loadPasswordHash - PASSWORD_HASH_CONCURRENCY must be an integer between 1 and 4"},
|
||||
"not integer": {value: "four", want: "Config.loadPasswordHash - PASSWORD_HASH_CONCURRENCY"},
|
||||
"zero": {value: "0", want: "Config.ValidatePasswordHash - PASSWORD_HASH_CONCURRENCY must be between 1 and 4"},
|
||||
"negative": {value: "-1", want: "Config.ValidatePasswordHash - PASSWORD_HASH_CONCURRENCY"},
|
||||
"over bound": {value: "5", want: "Config.ValidatePasswordHash - PASSWORD_HASH_CONCURRENCY"},
|
||||
}
|
||||
for name, test := range tests {
|
||||
_, err := LoadFromEnv(testEnvironment(map[string]string{"PASSWORD_HASH_CONCURRENCY": test.value}))
|
||||
if err == nil || !strings.HasPrefix(err.Error(), test.want) {
|
||||
t.Fatalf("LoadFromEnv(%s) error = %v, want an error starting with %q", name, err, test.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -49,7 +49,7 @@ CREATE TABLE users (
|
||||
CONSTRAINT users_password_hash_format CHECK (
|
||||
char_length(password_hash) <= 512
|
||||
AND password_hash
|
||||
~ '^\$argon2id\$v=19\$m=[0-9]+,t=[0-9]+,p=[0-9]+\$[A-Za-z0-9+/]+\$[A-Za-z0-9+/]+$'
|
||||
~ '^\$argon2id\$v=19\$m=[1-9][0-9]{0,9},t=[1-9][0-9]{0,9},p=[1-9][0-9]{0,2}\$[A-Za-z0-9+/]+\$[A-Za-z0-9+/]+$'
|
||||
),
|
||||
CONSTRAINT users_scenario_onboarding_step CHECK (
|
||||
(
|
||||
|
||||
+3
-3
@@ -26,6 +26,9 @@ require (
|
||||
go.opentelemetry.io/otel v1.47.0
|
||||
go.opentelemetry.io/otel/metric v1.47.0
|
||||
go.opentelemetry.io/otel/trace v1.47.0
|
||||
golang.org/x/crypto v0.57.0
|
||||
golang.org/x/sync v0.23.0
|
||||
golang.org/x/text v0.42.0
|
||||
)
|
||||
|
||||
require (
|
||||
@@ -376,15 +379,12 @@ require (
|
||||
go.uber.org/zap v1.28.0 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.5 // indirect
|
||||
go.yaml.in/yaml/v4 v4.0.0-rc.6 // indirect
|
||||
golang.org/x/crypto v0.57.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20260908205506-85c1c2202aba // indirect
|
||||
golang.org/x/exp/typeparams v0.0.0-20260811152304-ee035b5b010f // indirect
|
||||
golang.org/x/mod v0.41.0 // indirect
|
||||
golang.org/x/net v0.59.0 // indirect
|
||||
golang.org/x/sync v0.23.0 // indirect
|
||||
golang.org/x/sys v0.48.0 // indirect
|
||||
golang.org/x/term v0.46.0 // indirect
|
||||
golang.org/x/text v0.42.0 // indirect
|
||||
golang.org/x/tools v0.50.0 // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260831171406-18b4a7587f8a // indirect
|
||||
|
||||
@@ -945,6 +945,17 @@ func TestIdentityRepositories(t *testing.T) {
|
||||
statement: `UPDATE users SET password_hash = 'correct horse battery staple' WHERE id = $1`,
|
||||
args: []any{user.ID},
|
||||
},
|
||||
{
|
||||
// The domain regex rejects zero and leading-zero parameters too.
|
||||
constraint: "users_password_hash_format",
|
||||
statement: `UPDATE users SET password_hash = '$argon2id$v=19$m=0,t=2,p=1$c2FsdHNhbHRzYWx0$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaA' WHERE id = $1`,
|
||||
args: []any{user.ID},
|
||||
},
|
||||
{
|
||||
constraint: "users_password_hash_format",
|
||||
statement: `UPDATE users SET password_hash = '$argon2id$v=19$m=019456,t=2,p=1$c2FsdHNhbHRzYWx0$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaA' WHERE id = $1`,
|
||||
args: []any{user.ID},
|
||||
},
|
||||
{
|
||||
// The key matches the address, so only the ASCII rule fails.
|
||||
constraint: "users_email_ascii",
|
||||
@@ -1111,7 +1122,8 @@ func assertSameUser(t *testing.T, got, want domain.User) {
|
||||
t.Helper()
|
||||
sameVerification := (got.EmailVerifiedAt == nil) == (want.EmailVerifiedAt == nil) &&
|
||||
(got.EmailVerifiedAt == nil || got.EmailVerifiedAt.Equal(*want.EmailVerifiedAt))
|
||||
if got.ID != want.ID || got.Email != want.Email || got.PasswordHash.PHC() != want.PasswordHash.PHC() ||
|
||||
if got.ID != want.ID || got.Email.Address() != want.Email.Address() || got.Email.Normalized() != want.Email.Normalized() ||
|
||||
got.PasswordHash.PHC() != want.PasswordHash.PHC() ||
|
||||
got.Scenario != want.Scenario || got.OnboardingStep != want.OnboardingStep || !sameVerification ||
|
||||
got.RegistrationVersion != want.RegistrationVersion || !got.LastRegisteredAt.Equal(want.LastRegisteredAt) ||
|
||||
got.Version != want.Version || !got.CreatedAt.Equal(want.CreatedAt) || !got.UpdatedAt.Equal(want.UpdatedAt) {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -38,8 +38,15 @@ var ErrInvalidEmailAddress = errors.New("invalid email address")
|
||||
// the domain, a rule for Unicode local parts, and SMTPUTF8 delivery.
|
||||
//
|
||||
// String, GoString, Format, and LogValue redact the address so it does not
|
||||
// reach logs by accident; Address returns the real value.
|
||||
// reach logs by accident; Address returns the real value. Both forms sit
|
||||
// behind a pointer: fmt cannot call Format on an unexported field of an
|
||||
// enclosing struct and prints its contents instead, but for a pointer it
|
||||
// prints only the address. A nil pointer is the zero, invalid value.
|
||||
type EmailAddress struct {
|
||||
value *emailAddressValue
|
||||
}
|
||||
|
||||
type emailAddressValue struct {
|
||||
address string
|
||||
normalized string
|
||||
}
|
||||
@@ -69,7 +76,7 @@ func NewEmailAddress(raw string) (EmailAddress, error) {
|
||||
if err := validateEmailDomain(domainPart); err != nil {
|
||||
return EmailAddress{}, err
|
||||
}
|
||||
return EmailAddress{address: address, normalized: normalizeEmailKey(address)}, nil
|
||||
return EmailAddress{value: &emailAddressValue{address: address, normalized: normalizeEmailKey(address)}}, nil
|
||||
}
|
||||
|
||||
// RestoreEmailAddress rebuilds an EmailAddress from storage. It checks only
|
||||
@@ -79,7 +86,7 @@ func RestoreEmailAddress(address, normalized string) (EmailAddress, error) {
|
||||
if address == "" || normalized != normalizeEmailKey(address) {
|
||||
return EmailAddress{}, fmt.Errorf("domain.RestoreEmailAddress - stored key does not match the stored address: %w", ErrInvalidEmailAddress)
|
||||
}
|
||||
return EmailAddress{address: address, normalized: normalized}, nil
|
||||
return EmailAddress{value: &emailAddressValue{address: address, normalized: normalized}}, nil
|
||||
}
|
||||
|
||||
// normalizeEmailKey lowercases A-Z only, independent of locale and Unicode
|
||||
@@ -139,13 +146,23 @@ func invalidEmailAddress(reason string) error {
|
||||
|
||||
// Address returns the delivery form. Use it only where the address is needed:
|
||||
// storage, mail delivery, and the account view.
|
||||
func (email EmailAddress) Address() string { return email.address }
|
||||
func (email EmailAddress) Address() string {
|
||||
if email.value == nil {
|
||||
return ""
|
||||
}
|
||||
return email.value.address
|
||||
}
|
||||
|
||||
// Normalized returns the comparison key that storage keeps unique.
|
||||
func (email EmailAddress) Normalized() string { return email.normalized }
|
||||
func (email EmailAddress) Normalized() string {
|
||||
if email.value == nil {
|
||||
return ""
|
||||
}
|
||||
return email.value.normalized
|
||||
}
|
||||
|
||||
// IsZero reports an EmailAddress not built by NewEmailAddress.
|
||||
func (email EmailAddress) IsZero() bool { return email.normalized == "" }
|
||||
func (email EmailAddress) IsZero() bool { return email.value == nil }
|
||||
|
||||
func (email EmailAddress) String() string { return redactedEmailAddress }
|
||||
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"unicode/utf8"
|
||||
|
||||
"golang.org/x/text/unicode/norm"
|
||||
)
|
||||
|
||||
const (
|
||||
// MinNewPasswordCodePoints follows NIST SP 800-63B-4 for a password used
|
||||
// as the only authentication factor (the NewPassword contract schema).
|
||||
MinNewPasswordCodePoints = 15
|
||||
// MaxPasswordCodePoints bounds the hashing input of new and login
|
||||
// passwords (NewPassword and LoginPassword in the contract).
|
||||
MaxPasswordCodePoints = 128
|
||||
// minLoginPasswordCodePoints only rejects an empty login password; login
|
||||
// applies no registration policy, so a policy change locks nobody out.
|
||||
minLoginPasswordCodePoints = 1
|
||||
// maxPasswordInputBytes caps the raw input before NFKC normalization so
|
||||
// an oversized value never reaches the normalizer. 128 code points take at
|
||||
// most 4 bytes each in UTF-8, so every value that the contract schema
|
||||
// accepts fits.
|
||||
maxPasswordInputBytes = MaxPasswordCodePoints * utf8.UTFMax
|
||||
)
|
||||
|
||||
// ErrInvalidPassword reports a password outside the length rules. Errors that
|
||||
// wrap it name the rule, never the value or its length.
|
||||
var ErrInvalidPassword = errors.New("invalid password")
|
||||
|
||||
// Password is a plaintext password normalized to Unicode NFKC, as NIST SP
|
||||
// 800-63B-4 recommends, so that equivalent input from different keyboards
|
||||
// and platforms hashes the same. It exists only between the request and the
|
||||
// password hasher and is never stored. String, GoString, Format, LogValue,
|
||||
// and MarshalJSON redact it; Reveal returns the value for the hasher. The
|
||||
// value sits behind a pointer so that printing an enclosing struct shows only
|
||||
// an address (see redactedValue).
|
||||
type Password struct {
|
||||
value *string
|
||||
}
|
||||
|
||||
// NewPassword applies the registration policy: 15 to 128 Unicode code points
|
||||
// after NFKC normalization. The blocklist of common or breached passwords is
|
||||
// a separate check.
|
||||
func NewPassword(raw string) (Password, error) {
|
||||
return parsePassword("domain.NewPassword", raw, MinNewPasswordCodePoints)
|
||||
}
|
||||
|
||||
// ParseLoginPassword accepts a password entered at login: 1 to 128 Unicode
|
||||
// code points after NFKC normalization.
|
||||
func ParseLoginPassword(raw string) (Password, error) {
|
||||
return parsePassword("domain.ParseLoginPassword", raw, minLoginPasswordCodePoints)
|
||||
}
|
||||
|
||||
// parsePassword runs only cheap checks, so a caller can reject a value before
|
||||
// any expensive hashing. The raw byte cap comes first, then UTF-8 validity,
|
||||
// then normalization and the code point count.
|
||||
func parsePassword(location, raw string, minCodePoints int) (Password, error) {
|
||||
if len(raw) > maxPasswordInputBytes {
|
||||
return Password{}, fmt.Errorf("%s - password must have at most %d bytes before normalization: %w",
|
||||
location, maxPasswordInputBytes, ErrInvalidPassword)
|
||||
}
|
||||
if !utf8.ValidString(raw) {
|
||||
return Password{}, fmt.Errorf("%s - password must be valid UTF-8: %w", location, ErrInvalidPassword)
|
||||
}
|
||||
normalized := norm.NFKC.String(raw)
|
||||
if count := utf8.RuneCountInString(normalized); count < minCodePoints || count > MaxPasswordCodePoints {
|
||||
return Password{}, fmt.Errorf("%s - password must have %d to %d code points after NFKC normalization: %w",
|
||||
location, minCodePoints, MaxPasswordCodePoints, ErrInvalidPassword)
|
||||
}
|
||||
return Password{value: newRedactedValue(normalized)}, nil
|
||||
}
|
||||
|
||||
// Reveal returns the normalized password for the password hasher. Never
|
||||
// store, log, or return it.
|
||||
func (password Password) Reveal() string { return redactedValue(password.value) }
|
||||
|
||||
// IsZero reports a Password not built by NewPassword or ParseLoginPassword.
|
||||
func (password Password) IsZero() bool { return password.value == nil }
|
||||
|
||||
func (password Password) String() string { return redactedSecret }
|
||||
|
||||
func (password Password) GoString() string { return redactedSecret }
|
||||
|
||||
func (password Password) LogValue() slog.Value { return slog.StringValue(redactedSecret) }
|
||||
|
||||
// Format redacts every verb; without it %d would print the struct fields.
|
||||
func (password Password) Format(state fmt.State, _ rune) { writeRedacted(state, redactedSecret) }
|
||||
|
||||
// MarshalJSON redacts the value in any JSON output, including a struct that
|
||||
// embeds a Password.
|
||||
func (password Password) MarshalJSON() ([]byte, error) { return redactedSecretJSON(), nil }
|
||||
|
||||
func redactedSecretJSON() []byte { return []byte(`"` + redactedSecret + `"`) }
|
||||
@@ -0,0 +1,132 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNewPasswordCountsCodePointsAfterNFKC(t *testing.T) {
|
||||
tests := map[string]struct {
|
||||
raw string
|
||||
want string
|
||||
}{
|
||||
"15 ASCII characters": {raw: strings.Repeat("a", 15), want: strings.Repeat("a", 15)},
|
||||
"128 ASCII characters": {raw: strings.Repeat("a", 128), want: strings.Repeat("a", 128)},
|
||||
// 15 code points in 30 bytes: the limit counts code points, not bytes.
|
||||
"15 Cyrillic letters": {raw: strings.Repeat("ж", 15), want: strings.Repeat("ж", 15)},
|
||||
// 128 code points in 512 bytes: the largest input the byte cap allows.
|
||||
"128 four-byte characters": {raw: strings.Repeat("\U0001F600", 128), want: strings.Repeat("\U0001F600", 128)},
|
||||
// Fullwidth forms normalize to ASCII.
|
||||
"fullwidth letters": {raw: strings.Repeat("pass", 4), want: strings.Repeat("pass", 4)},
|
||||
// 14 raw code points become 15 after NFKC expands the ligature.
|
||||
"expanding ligature": {raw: strings.Repeat("a", 13) + "fi", want: strings.Repeat("a", 13) + "fi"},
|
||||
// Spaces and surrounding whitespace are part of the password.
|
||||
"spaces kept": {raw: " correct horse battery ", want: " correct horse battery "},
|
||||
}
|
||||
for name, test := range tests {
|
||||
password, err := NewPassword(test.raw)
|
||||
if err != nil {
|
||||
t.Fatalf("NewPassword(%s) error = %v", name, err)
|
||||
}
|
||||
if password.Reveal() != test.want {
|
||||
t.Fatalf("NewPassword(%s) did not normalize to the expected NFKC form", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewPasswordRejectsValuesOutsideThePolicy(t *testing.T) {
|
||||
tests := map[string]string{
|
||||
"empty": "",
|
||||
"14 ASCII characters": strings.Repeat("a", 14),
|
||||
"129 ASCII characters": strings.Repeat("a", 129),
|
||||
"over the byte cap": strings.Repeat("a", maxPasswordInputBytes+1),
|
||||
"129 four-byte runes": strings.Repeat("\U0001F600", 129),
|
||||
"one megabyte": strings.Repeat("a", 1<<20),
|
||||
"invalid UTF-8": strings.Repeat("a", 20) + "\xff",
|
||||
"truncated UTF-8": strings.Repeat("a", 20) + "\xe2\x82",
|
||||
"expands past the limit": strings.Repeat("fi", 65),
|
||||
// 16 raw code points compose into 8 after NFKC.
|
||||
"composes below the minimum": strings.Repeat("é", 8),
|
||||
}
|
||||
for name, raw := range tests {
|
||||
_, err := NewPassword(raw)
|
||||
if !errors.Is(err, ErrInvalidPassword) {
|
||||
t.Fatalf("NewPassword(%s) error = %v, want ErrInvalidPassword", name, err)
|
||||
}
|
||||
if raw != "" && strings.Contains(err.Error(), raw) {
|
||||
t.Fatalf("NewPassword(%s) error exposes the input", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewPasswordChecksTheByteCapBeforeNormalizing(t *testing.T) {
|
||||
// Valid UTF-8 would normalize; the byte cap must answer first.
|
||||
_, err := NewPassword(strings.Repeat("fi", maxPasswordInputBytes))
|
||||
if !errors.Is(err, ErrInvalidPassword) || !strings.Contains(err.Error(), "bytes before normalization") {
|
||||
t.Fatalf("NewPassword(oversized) error = %v, want the byte cap", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseLoginPasswordAppliesOnlyTheHashingBound(t *testing.T) {
|
||||
for _, raw := range []string{"a", "short", strings.Repeat("a", 128)} {
|
||||
if _, err := ParseLoginPassword(raw); err != nil {
|
||||
t.Fatalf("ParseLoginPassword(%d bytes) error = %v", len(raw), err)
|
||||
}
|
||||
}
|
||||
for _, raw := range []string{"", strings.Repeat("a", 129), strings.Repeat("a", maxPasswordInputBytes+1), "\xff"} {
|
||||
if _, err := ParseLoginPassword(raw); !errors.Is(err, ErrInvalidPassword) {
|
||||
t.Fatalf("ParseLoginPassword(%d bytes) error = %v, want ErrInvalidPassword", len(raw), err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewPasswordAndLoginPasswordNormalizeAlike(t *testing.T) {
|
||||
registered, err := NewPassword("correct horse battery")
|
||||
if err != nil {
|
||||
t.Fatalf("NewPassword() error = %v", err)
|
||||
}
|
||||
login, err := ParseLoginPassword("correct horse battery")
|
||||
if err != nil {
|
||||
t.Fatalf("ParseLoginPassword() error = %v", err)
|
||||
}
|
||||
if registered.Reveal() != login.Reveal() {
|
||||
t.Fatal("equivalent registration and login input normalized differently")
|
||||
}
|
||||
if !(Password{}).IsZero() || registered.IsZero() {
|
||||
t.Fatal("IsZero() does not distinguish a built password from the zero value")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPasswordAndPasswordHashAreRedacted(t *testing.T) {
|
||||
const raw = "correct horse battery staple"
|
||||
password, err := NewPassword(raw)
|
||||
if err != nil {
|
||||
t.Fatalf("NewPassword() error = %v", err)
|
||||
}
|
||||
passwordHash, err := NewPasswordHash(testPasswordHash)
|
||||
if err != nil {
|
||||
t.Fatalf("NewPasswordHash() error = %v", err)
|
||||
}
|
||||
var logs bytes.Buffer
|
||||
slog.New(slog.NewTextHandler(&logs, nil)).Info("redaction", "password", password, "hash", passwordHash)
|
||||
slog.New(slog.NewJSONHandler(&logs, nil)).Info("redaction", "password", password, "hash", passwordHash)
|
||||
encoded, err := json.Marshal(map[string]any{"password": password, "hash": passwordHash})
|
||||
if err != nil {
|
||||
t.Fatalf("json.Marshal() error = %v", err)
|
||||
}
|
||||
formatted := fmt.Sprintf("%v %+v %#v %s %q %d", password, password, password, password, password, password) +
|
||||
logs.String() + string(encoded)
|
||||
for _, secret := range []string{raw, testPasswordHash, "c2FsdHNhbHRzYWx0"} {
|
||||
if strings.Contains(formatted, secret) {
|
||||
t.Fatalf("formatted output exposes a secret: %s", formatted)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(string(encoded), redactedSecret) {
|
||||
t.Fatalf("json.Marshal() = %s, want redacted values", encoded)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// nestedSecrets holds every secret type in unexported fields, where fmt does
|
||||
// not call their Format, String, or GoString methods.
|
||||
type nestedSecrets struct {
|
||||
password Password
|
||||
hash PasswordHash
|
||||
token SecretToken
|
||||
email EmailAddress
|
||||
}
|
||||
|
||||
// exportedSecrets is the same with exported fields, as in domain.User.
|
||||
type exportedSecrets struct {
|
||||
Password Password `json:"password"`
|
||||
Hash PasswordHash `json:"hash"`
|
||||
Token SecretToken `json:"token"`
|
||||
Email EmailAddress `json:"email"`
|
||||
}
|
||||
|
||||
func TestSecretsAreRedactedInsideEnclosingStructs(t *testing.T) {
|
||||
const rawPassword = "correct horse battery staple"
|
||||
const rawEmail = "Secret.Person@Example.com"
|
||||
password, err := NewPassword(rawPassword)
|
||||
if err != nil {
|
||||
t.Fatalf("NewPassword() error = %v", err)
|
||||
}
|
||||
hash, err := NewPasswordHash(testPasswordHash)
|
||||
if err != nil {
|
||||
t.Fatalf("NewPasswordHash() error = %v", err)
|
||||
}
|
||||
token, err := NewSecretToken()
|
||||
if err != nil {
|
||||
t.Fatalf("NewSecretToken() error = %v", err)
|
||||
}
|
||||
email, err := NewEmailAddress(rawEmail)
|
||||
if err != nil {
|
||||
t.Fatalf("NewEmailAddress() error = %v", err)
|
||||
}
|
||||
nested := nestedSecrets{password: password, hash: hash, token: token, email: email}
|
||||
exported := exportedSecrets{Password: password, Hash: hash, Token: token, Email: email}
|
||||
pointer := &nested
|
||||
|
||||
var logs bytes.Buffer
|
||||
for _, logger := range []*slog.Logger{
|
||||
slog.New(slog.NewTextHandler(&logs, nil)),
|
||||
slog.New(slog.NewJSONHandler(&logs, nil)),
|
||||
} {
|
||||
logger.Info("nested", "unexported", nested, "exported", exported, "pointer", pointer)
|
||||
}
|
||||
encoded, err := json.Marshal(exported)
|
||||
if err != nil {
|
||||
t.Fatalf("json.Marshal() error = %v", err)
|
||||
}
|
||||
output := fmt.Sprintf("%v %+v %#v %v %+v %#v %v %+v %v",
|
||||
nested, nested, nested, exported, exported, exported, pointer, []nestedSecrets{nested}, map[string]nestedSecrets{"k": nested}) +
|
||||
logs.String() + string(encoded)
|
||||
|
||||
secrets := []string{
|
||||
rawPassword, testPasswordHash, "c2FsdHNhbHRzYWx0", token.Reveal(), rawEmail, strings.ToLower(rawEmail),
|
||||
}
|
||||
for _, secret := range secrets {
|
||||
if strings.Contains(output, secret) {
|
||||
t.Fatalf("printing an enclosing struct exposes a secret: %s", output)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestZeroSecretValuesAreEmptyAndInvalid(t *testing.T) {
|
||||
if !(Password{}).IsZero() || (Password{}).Reveal() != "" {
|
||||
t.Fatal("zero Password is not empty and zero")
|
||||
}
|
||||
if !(PasswordHash{}).IsZero() || (PasswordHash{}).PHC() != "" {
|
||||
t.Fatal("zero PasswordHash is not empty and zero")
|
||||
}
|
||||
if !(SecretToken{}).IsZero() || (SecretToken{}).Reveal() != "" {
|
||||
t.Fatal("zero SecretToken is not empty and zero")
|
||||
}
|
||||
if !(EmailAddress{}).IsZero() || (EmailAddress{}).Address() != "" || (EmailAddress{}).Normalized() != "" {
|
||||
t.Fatal("zero EmailAddress is not empty and zero")
|
||||
}
|
||||
}
|
||||
@@ -31,8 +31,10 @@ var (
|
||||
// session cookie value. Only the holder sees the raw value; storage keeps
|
||||
// SecretTokenHash. String and LogValue redact the value so it does not reach
|
||||
// logs by accident; Reveal returns it for the one place that must send it.
|
||||
// The value sits behind a pointer so that printing an enclosing struct shows
|
||||
// only an address (see redactedValue).
|
||||
type SecretToken struct {
|
||||
value string
|
||||
value *string
|
||||
}
|
||||
|
||||
// NewSecretToken returns a token with 256 bits from crypto/rand.
|
||||
@@ -41,7 +43,7 @@ func NewSecretToken() (SecretToken, error) {
|
||||
if _, err := rand.Read(entropy); err != nil {
|
||||
return SecretToken{}, fmt.Errorf("domain.NewSecretToken - read random bytes: %w", err)
|
||||
}
|
||||
return SecretToken{value: base64.RawURLEncoding.EncodeToString(entropy)}, nil
|
||||
return SecretToken{value: newRedactedValue(base64.RawURLEncoding.EncodeToString(entropy))}, nil
|
||||
}
|
||||
|
||||
// ParseSecretToken accepts a raw token from a request. It checks only the
|
||||
@@ -50,19 +52,19 @@ func ParseSecretToken(raw string) (SecretToken, error) {
|
||||
if !secretTokenPattern.MatchString(raw) {
|
||||
return SecretToken{}, fmt.Errorf("domain.ParseSecretToken - token must have 32 to 128 base64url characters: %w", ErrInvalidSecretToken)
|
||||
}
|
||||
return SecretToken{value: raw}, nil
|
||||
return SecretToken{value: newRedactedValue(raw)}, nil
|
||||
}
|
||||
|
||||
// Hash returns the SHA-256 digest that storage keeps. A token carries 256 bits
|
||||
// of entropy, so a fast unsalted digest cannot be reversed by guessing, unlike
|
||||
// a password, and lookups by digest stay a single index probe.
|
||||
func (token SecretToken) Hash() SecretTokenHash {
|
||||
return SecretTokenHash(sha256.Sum256([]byte(token.value)))
|
||||
return SecretTokenHash(sha256.Sum256([]byte(token.Reveal())))
|
||||
}
|
||||
|
||||
// Reveal returns the raw value for delivery to its holder: the email link or
|
||||
// the Set-Cookie header. Never store or log it.
|
||||
func (token SecretToken) Reveal() string { return token.value }
|
||||
func (token SecretToken) Reveal() string { return redactedValue(token.value) }
|
||||
|
||||
func (token SecretToken) String() string { return redactedSecret }
|
||||
|
||||
@@ -73,12 +75,26 @@ func (token SecretToken) LogValue() slog.Value { return slog.StringValue(redacte
|
||||
// Format redacts every verb; without it %d would print the struct fields.
|
||||
func (token SecretToken) Format(state fmt.State, _ rune) { writeRedacted(state, redactedSecret) }
|
||||
|
||||
// newRedactedValue and redactedValue hold a secret string behind a pointer.
|
||||
// fmt calls Format, String, or GoString only on values it can reach through
|
||||
// an interface; for an unexported field of an enclosing struct it prints the
|
||||
// fields with reflection instead. A pointer field is then printed as an
|
||||
// address, so the secret never appears. A nil pointer is the zero value.
|
||||
func newRedactedValue(value string) *string { return &value }
|
||||
|
||||
func redactedValue(value *string) string {
|
||||
if value == nil {
|
||||
return ""
|
||||
}
|
||||
return *value
|
||||
}
|
||||
|
||||
func writeRedacted(state fmt.State, placeholder string) {
|
||||
_, _ = state.Write([]byte(placeholder))
|
||||
}
|
||||
|
||||
// IsZero reports a SecretToken not built by NewSecretToken or ParseSecretToken.
|
||||
func (token SecretToken) IsZero() bool { return token.value == "" }
|
||||
func (token SecretToken) IsZero() bool { return token.value == nil }
|
||||
|
||||
// SecretTokenHash is the SHA-256 digest of a SecretToken.
|
||||
type SecretTokenHash [SecretTokenHashSize]byte
|
||||
|
||||
@@ -105,9 +105,11 @@ func ParseOnboardingStep(value string) (OnboardingStep, error) {
|
||||
}
|
||||
|
||||
// PasswordHash is an Argon2id hash in the PHC string format. It is never the
|
||||
// password itself. String and LogValue redact it.
|
||||
// password itself. String and LogValue redact it. The string sits behind a
|
||||
// pointer so that printing an enclosing struct shows only an address (see
|
||||
// redactedValue).
|
||||
type PasswordHash struct {
|
||||
phc string
|
||||
phc *string
|
||||
}
|
||||
|
||||
// NewPasswordHash validates the structure of a PHC string produced by the
|
||||
@@ -129,7 +131,7 @@ func NewPasswordHash(phc string) (PasswordHash, error) {
|
||||
if err != nil || len(digest) < minPasswordDigestBytes {
|
||||
return PasswordHash{}, invalidPasswordHash("digest must be unpadded base64 of at least 16 bytes")
|
||||
}
|
||||
return PasswordHash{phc: phc}, nil
|
||||
return PasswordHash{phc: newRedactedValue(phc)}, nil
|
||||
}
|
||||
|
||||
func invalidPasswordHash(reason string) error {
|
||||
@@ -137,7 +139,7 @@ func invalidPasswordHash(reason string) error {
|
||||
}
|
||||
|
||||
// PHC returns the encoded hash for storage and verification.
|
||||
func (hash PasswordHash) PHC() string { return hash.phc }
|
||||
func (hash PasswordHash) PHC() string { return redactedValue(hash.phc) }
|
||||
|
||||
func (hash PasswordHash) String() string { return redactedSecret }
|
||||
|
||||
@@ -148,8 +150,12 @@ func (hash PasswordHash) LogValue() slog.Value { return slog.StringValue(redacte
|
||||
// Format redacts every verb; without it %d would print the struct fields.
|
||||
func (hash PasswordHash) Format(state fmt.State, _ rune) { writeRedacted(state, redactedSecret) }
|
||||
|
||||
// MarshalJSON redacts the hash in any JSON output, including a serialized
|
||||
// User.
|
||||
func (hash PasswordHash) MarshalJSON() ([]byte, error) { return redactedSecretJSON(), nil }
|
||||
|
||||
// IsZero reports a PasswordHash not built by NewPasswordHash.
|
||||
func (hash PasswordHash) IsZero() bool { return hash.phc == "" }
|
||||
func (hash PasswordHash) IsZero() bool { return hash.phc == nil }
|
||||
|
||||
// Registration is the validated content of one registration request.
|
||||
type Registration struct {
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
package outbound
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrPasswordMismatch reports a password that does not match the hash.
|
||||
// VerifyDummy ends with it whenever it completes the work.
|
||||
ErrPasswordMismatch = errors.New("password does not match")
|
||||
|
||||
// ErrPasswordHashCorrupt reports a stored hash that cannot be verified:
|
||||
// it is not a well-formed Argon2id v19 PHC string, or its parameters are
|
||||
// outside the bounds the hasher accepts. It wraps
|
||||
// domain.ErrInvalidPasswordHash, which the repository returns when a
|
||||
// stored hash fails domain.NewPasswordHash on read, so
|
||||
// errors.Is(err, domain.ErrInvalidPasswordHash) matches both cases. It is
|
||||
// a storage problem, not a wrong password.
|
||||
ErrPasswordHashCorrupt = fmt.Errorf("password hash corrupt: %w", domain.ErrInvalidPasswordHash)
|
||||
)
|
||||
|
||||
// PasswordHasher derives and checks password hashes with a slow, salted KDF.
|
||||
//
|
||||
// Callers validate the password with domain.NewPassword or
|
||||
// domain.ParseLoginPassword first, so the hasher only receives bounded
|
||||
// input; a zero domain.Password returns an error wrapping
|
||||
// domain.ErrInvalidPassword without hashing. Every derivation waits for its
|
||||
// share of a fixed memory budget, which bounds the memory and CPU of
|
||||
// concurrent hashing; a context that ends while waiting returns the context
|
||||
// error and computes nothing. Errors never contain the password or the hash.
|
||||
//
|
||||
// Login (TASK-055) must answer invalid_credentials for an unknown email, a
|
||||
// wrong password, and a stored hash that is invalid
|
||||
// (domain.ErrInvalidPasswordHash, from the repository or from Verify). For
|
||||
// an invalid hash it must also log an error and call VerifyDummy, because a
|
||||
// corrupt hash is refused without a derivation and would otherwise answer
|
||||
// faster than a real check.
|
||||
type PasswordHasher interface {
|
||||
// Hash returns a new hash with a fresh random salt and the current
|
||||
// parameters.
|
||||
Hash(ctx context.Context, password domain.Password) (domain.PasswordHash, error)
|
||||
|
||||
// Verify returns nil when password matches stored. needsRehash then
|
||||
// reports that stored was made with other parameters, salt length, or key
|
||||
// length than the current ones, so a login can store Hash(password) in
|
||||
// its place. A wrong password returns ErrPasswordMismatch and a malformed
|
||||
// or out-of-bounds hash returns ErrPasswordHashCorrupt without a
|
||||
// derivation; needsRehash is false with any error.
|
||||
Verify(ctx context.Context, password domain.Password, stored domain.PasswordHash) (needsRehash bool, err error)
|
||||
|
||||
// VerifyDummy does the same work as Verify against a hash with the current
|
||||
// parameters that no password matches. It returns ErrPasswordMismatch
|
||||
// after the work, the context error when the context ended before the
|
||||
// derivation, or domain.ErrInvalidPassword for a zero password; it never
|
||||
// returns nil. A login calls it for an unknown email so that the response
|
||||
// time does not reveal whether the account exists.
|
||||
VerifyDummy(ctx context.Context, password domain.Password) error
|
||||
}
|
||||
Whitespace-only changes.
@@ -0,0 +1,39 @@
|
||||
// Package identity holds the account usecases.
|
||||
package identity
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// Credentials applies the password rules in the order that keeps hashing
|
||||
// bounded: the cheap length and encoding checks first, the expensive KDF only
|
||||
// for a password that passes them.
|
||||
type Credentials struct {
|
||||
hasher outbound.PasswordHasher
|
||||
}
|
||||
|
||||
func NewCredentials(hasher outbound.PasswordHasher) *Credentials {
|
||||
return &Credentials{hasher: hasher}
|
||||
}
|
||||
|
||||
// HashNewPassword applies the registration password policy to raw and hashes
|
||||
// the normalized password. A password outside the policy returns an error
|
||||
// wrapping domain.ErrInvalidPassword without calling the hasher. Errors
|
||||
// never contain raw. Registration (TASK-053, not implemented yet) must call
|
||||
// it on every branch before it looks up the email, so that neither the
|
||||
// outcome nor the time depends on whether the account exists.
|
||||
func (credentials *Credentials) HashNewPassword(ctx context.Context, raw string) (domain.PasswordHash, error) {
|
||||
password, err := domain.NewPassword(raw)
|
||||
if err != nil {
|
||||
return domain.PasswordHash{}, fmt.Errorf("Credentials.HashNewPassword - validate password: %w", err)
|
||||
}
|
||||
hash, err := credentials.hasher.Hash(ctx, password)
|
||||
if err != nil {
|
||||
return domain.PasswordHash{}, fmt.Errorf("Credentials.HashNewPassword - hash password: %w", err)
|
||||
}
|
||||
return hash, nil
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package identity
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// countingHasher records calls so a test can prove that validation stops a
|
||||
// password before any hashing.
|
||||
type countingHasher struct {
|
||||
hashCalls int
|
||||
hashed domain.Password
|
||||
}
|
||||
|
||||
func (hasher *countingHasher) Hash(_ context.Context, password domain.Password) (domain.PasswordHash, error) {
|
||||
hasher.hashCalls++
|
||||
hasher.hashed = password
|
||||
return domain.NewPasswordHash("$argon2id$v=19$m=65536,t=3,p=4$c2FsdHNhbHRzYWx0c2FsdA$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaGhhc2g")
|
||||
}
|
||||
|
||||
func (hasher *countingHasher) Verify(context.Context, domain.Password, domain.PasswordHash) (bool, error) {
|
||||
return false, errors.New("countingHasher.Verify - not used")
|
||||
}
|
||||
|
||||
func (hasher *countingHasher) VerifyDummy(context.Context, domain.Password) error {
|
||||
return errors.New("countingHasher.VerifyDummy - not used")
|
||||
}
|
||||
|
||||
var _ outbound.PasswordHasher = (*countingHasher)(nil)
|
||||
|
||||
func TestHashNewPasswordRefusesAnOversizedPasswordBeforeHashing(t *testing.T) {
|
||||
const marker = "do-not-log-this-password-"
|
||||
tests := map[string]string{
|
||||
"129 code points": marker + strings.Repeat("x", 129-len(marker)),
|
||||
"over the raw byte cap": marker + strings.Repeat("\U0001F600", 200),
|
||||
"one megabyte": marker + strings.Repeat("y", 1<<20),
|
||||
"too long after normalization": marker + strings.Repeat("fi", 60),
|
||||
}
|
||||
for name, raw := range tests {
|
||||
hasher := &countingHasher{}
|
||||
var logs bytes.Buffer
|
||||
// The handling boundary logs the error as an HTTP handler would.
|
||||
logger := slog.New(slog.NewJSONHandler(&logs, nil))
|
||||
|
||||
_, err := NewCredentials(hasher).HashNewPassword(context.Background(), raw)
|
||||
logger.Error("registration refused", "error", err)
|
||||
|
||||
if !errors.Is(err, domain.ErrInvalidPassword) {
|
||||
t.Fatalf("HashNewPassword(%s) error = %v, want ErrInvalidPassword", name, err)
|
||||
}
|
||||
if hasher.hashCalls != 0 {
|
||||
t.Fatalf("HashNewPassword(%s) called the hasher %d times, want none", name, hasher.hashCalls)
|
||||
}
|
||||
if strings.Contains(logs.String(), marker) || strings.Contains(err.Error(), marker) {
|
||||
t.Fatalf("HashNewPassword(%s) exposed the input in the error or the log: %s", name, logs.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHashNewPasswordRefusesAShortPasswordBeforeHashing(t *testing.T) {
|
||||
hasher := &countingHasher{}
|
||||
_, err := NewCredentials(hasher).HashNewPassword(context.Background(), "fourteen chars")
|
||||
if !errors.Is(err, domain.ErrInvalidPassword) || hasher.hashCalls != 0 {
|
||||
t.Fatalf("HashNewPassword(14 code points) = %v after %d hash calls, want ErrInvalidPassword and no call", err, hasher.hashCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHashNewPasswordHashesTheNormalizedPassword(t *testing.T) {
|
||||
hasher := &countingHasher{}
|
||||
if _, err := NewCredentials(hasher).HashNewPassword(context.Background(), "correct horse battery"); err != nil {
|
||||
t.Fatalf("HashNewPassword() error = %v", err)
|
||||
}
|
||||
if hasher.hashCalls != 1 || hasher.hashed.Reveal() != "correct horse battery" {
|
||||
t.Fatalf("hasher received %d calls, want one with the NFKC form", hasher.hashCalls)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user