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

+23 -6
View File
@@ -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 }
+96
View File
@@ -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 + `"`) }
+132
View File
@@ -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)
}
}
+90
View File
@@ -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")
}
}
+22 -6
View File
@@ -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
+11 -5
View File
@@ -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 {