feat(identity): confirm the email address with a six-digit code from the message
This commit is contained in:
1 parent
c94434cd09
commit
d365a05c96
87 files changed
+4764
-224
No files matched your search
@@ -0,0 +1,106 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"math/big"
|
||||
"regexp"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
// VerificationCodeDigits is the length of the code in a verification
|
||||
// message. The contract pattern is ^[0-9]{6}$.
|
||||
VerificationCodeDigits = 6
|
||||
|
||||
// VerificationCodeMaxFailedAttempts is the number of failed attempts
|
||||
// against one open code after which the code and its token are burned.
|
||||
// The storage check constraint repeats this value.
|
||||
VerificationCodeMaxFailedAttempts = 5
|
||||
|
||||
// VerificationCodeLifetime bounds how long a code works. A token lasts
|
||||
// longer, so the code ends first; the code expiry is the earlier of the
|
||||
// two, see NewEmailToken.
|
||||
VerificationCodeLifetime = 30 * time.Minute
|
||||
|
||||
// verificationCodeSpace is the number of distinct codes: 000000 to 999999.
|
||||
verificationCodeSpace = 1_000_000
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrInvalidVerificationCode reports a code that is not six ASCII digits.
|
||||
// Its message never contains the rejected value.
|
||||
ErrInvalidVerificationCode = errors.New("invalid verification code")
|
||||
|
||||
verificationCodeSpaceBig = big.NewInt(verificationCodeSpace)
|
||||
verificationCodePattern = regexp.MustCompile(`^[0-9]{6}$`)
|
||||
)
|
||||
|
||||
// VerificationCode is the six-digit code of a verification message. Only the
|
||||
// holder sees the value; String, GoString, Format, and LogValue redact it so
|
||||
// that it does not reach logs by accident. Reveal returns it for the one place
|
||||
// that must send it. The value sits behind a pointer, as in SecretToken.
|
||||
type VerificationCode struct {
|
||||
value *string
|
||||
}
|
||||
|
||||
// NewVerificationCode returns a code drawn uniformly from 000000 to 999999
|
||||
// with crypto/rand.
|
||||
func NewVerificationCode() (VerificationCode, error) {
|
||||
return newVerificationCode(rand.Reader)
|
||||
}
|
||||
|
||||
// newVerificationCode draws from random. crypto/rand.Int rejects the draws
|
||||
// above the bound instead of reducing them modulo it, so every code is equally
|
||||
// likely.
|
||||
func newVerificationCode(random io.Reader) (VerificationCode, error) {
|
||||
number, err := rand.Int(random, verificationCodeSpaceBig)
|
||||
if err != nil {
|
||||
return VerificationCode{}, fmt.Errorf("domain.NewVerificationCode - draw code: %w", err)
|
||||
}
|
||||
return VerificationCode{value: newRedactedValue(fmt.Sprintf("%0*d", VerificationCodeDigits, number.Int64()))}, nil
|
||||
}
|
||||
|
||||
// ParseVerificationCode accepts exactly six ASCII digits from a request. Spaces
|
||||
// and separators are rejected rather than stripped, so the contract stays exact.
|
||||
func ParseVerificationCode(raw string) (VerificationCode, error) {
|
||||
if !verificationCodePattern.MatchString(raw) {
|
||||
return VerificationCode{}, fmt.Errorf("domain.ParseVerificationCode - code must have %d digits: %w", VerificationCodeDigits, ErrInvalidVerificationCode)
|
||||
}
|
||||
return VerificationCode{value: newRedactedValue(raw)}, nil
|
||||
}
|
||||
|
||||
// Reveal returns the digits for delivery to the holder, or for the keyed
|
||||
// digest. Never store or log the result.
|
||||
func (code VerificationCode) Reveal() string { return redactedValue(code.value) }
|
||||
|
||||
// IsZero reports a VerificationCode not built by NewVerificationCode or
|
||||
// ParseVerificationCode.
|
||||
func (code VerificationCode) IsZero() bool { return code.value == nil }
|
||||
|
||||
func (code VerificationCode) String() string { return redactedSecret }
|
||||
|
||||
func (code VerificationCode) GoString() string { return redactedSecret }
|
||||
|
||||
// Format redacts every verb; without it %d would print the digits.
|
||||
func (code VerificationCode) Format(state fmt.State, _ rune) { writeRedacted(state, redactedSecret) }
|
||||
|
||||
func (code VerificationCode) LogValue() slog.Value { return slog.StringValue(redactedSecret) }
|
||||
|
||||
// VerificationCodeHash is the keyed digest of a VerificationCode that storage
|
||||
// keeps. It is an HMAC under a server secret: the code space has only a
|
||||
// million values, so an unkeyed digest could be reversed by enumeration.
|
||||
type VerificationCodeHash [SecretTokenHashSize]byte
|
||||
|
||||
// IsZero reports the all-zero value, which marks a missing digest.
|
||||
func (hash VerificationCodeHash) IsZero() bool { return hash == VerificationCodeHash{} }
|
||||
|
||||
// EmailCode is the code state of an email token: its keyed digest and the end
|
||||
// of its validity.
|
||||
type EmailCode struct {
|
||||
Hash VerificationCodeHash
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// fixedReader yields the given bytes in order and then reports an error, so a
|
||||
// draw that needs more entropy than the test provides fails loudly.
|
||||
type fixedReader struct {
|
||||
data []byte
|
||||
}
|
||||
|
||||
func (reader *fixedReader) Read(buffer []byte) (int, error) {
|
||||
if len(reader.data) == 0 {
|
||||
return 0, io.ErrUnexpectedEOF
|
||||
}
|
||||
count := copy(buffer, reader.data)
|
||||
reader.data = reader.data[count:]
|
||||
return count, nil
|
||||
}
|
||||
|
||||
func TestVerificationCodeRejectsDrawsAboveTheBoundInsteadOfReducingThem(t *testing.T) {
|
||||
// crypto/rand.Int draws 20 random bits for the 1,000,000 codes and masks the
|
||||
// top byte to 4 bits. 0x0FFFFF is 1048575, above the bound, so it is drawn
|
||||
// again; the next draw 0x000007 is code 000007. A modulo reduction would
|
||||
// have returned 048575 here and biased every code.
|
||||
code, err := newVerificationCode(&fixedReader{data: []byte{0x0F, 0xFF, 0xFF, 0x00, 0x00, 0x07}})
|
||||
if err != nil {
|
||||
t.Fatalf("newVerificationCode() error = %v", err)
|
||||
}
|
||||
if code.Reveal() != "000007" {
|
||||
t.Fatalf("code = %q, want 000007", code.Reveal())
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerificationCodeCoversTheWholeRange(t *testing.T) {
|
||||
low, err := newVerificationCode(&fixedReader{data: []byte{0x00, 0x00, 0x00}})
|
||||
if err != nil {
|
||||
t.Fatalf("newVerificationCode(0) error = %v", err)
|
||||
}
|
||||
high, err := newVerificationCode(&fixedReader{data: []byte{0x0F, 0x42, 0x3F}})
|
||||
if err != nil {
|
||||
t.Fatalf("newVerificationCode(999999) error = %v", err)
|
||||
}
|
||||
if low.Reveal() != "000000" || high.Reveal() != "999999" {
|
||||
t.Fatalf("bounds = %q and %q, want 000000 and 999999", low.Reveal(), high.Reveal())
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerificationCodeDrawFailureIsReported(t *testing.T) {
|
||||
if _, err := newVerificationCode(&fixedReader{}); err == nil {
|
||||
t.Fatal("newVerificationCode() accepted a failing entropy source")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewVerificationCodeIsRoughlyUniform(t *testing.T) {
|
||||
const draws = 20_000
|
||||
var buckets [10]int
|
||||
for range draws {
|
||||
code, err := NewVerificationCode()
|
||||
if err != nil {
|
||||
t.Fatalf("NewVerificationCode() error = %v", err)
|
||||
}
|
||||
if len(code.Reveal()) != VerificationCodeDigits {
|
||||
t.Fatalf("code %q does not have %d digits", code.Reveal(), VerificationCodeDigits)
|
||||
}
|
||||
buckets[code.Reveal()[0]-'0']++
|
||||
}
|
||||
// The expected count per leading digit is 2000 with a standard deviation
|
||||
// near 42. A window of about seven standard deviations keeps the test
|
||||
// deterministic in practice and still rejects a visibly skewed generator.
|
||||
for digit, count := range buckets {
|
||||
if count < 1700 || count > 2300 {
|
||||
t.Fatalf("leading digit %d appeared %d times in %d draws", digit, count, draws)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseVerificationCodeAcceptsOnlySixASCIIDigits(t *testing.T) {
|
||||
for _, valid := range []string{"000000", "482915", "999999"} {
|
||||
code, err := ParseVerificationCode(valid)
|
||||
if err != nil || code.Reveal() != valid {
|
||||
t.Fatalf("ParseVerificationCode(%q) = %q, %v", valid, code.Reveal(), err)
|
||||
}
|
||||
}
|
||||
for _, invalid := range []string{"", "48291", "4829156", "48291a", " 482915", "482915\n", "482 915", "482915", "-82915"} {
|
||||
if _, err := ParseVerificationCode(invalid); !errors.Is(err, ErrInvalidVerificationCode) {
|
||||
t.Fatalf("ParseVerificationCode(%q) error = %v, want ErrInvalidVerificationCode", invalid, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerificationCodeNeverPrintsItsDigits(t *testing.T) {
|
||||
code, err := ParseVerificationCode("482915")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, rendered := range []string{
|
||||
fmt.Sprint(code),
|
||||
fmt.Sprintf("%v %+v %#v %s %d", code, code, code, code, code),
|
||||
code.LogValue().String(),
|
||||
fmt.Sprint(struct{ Code VerificationCode }{code}),
|
||||
} {
|
||||
if strings.Contains(rendered, "482915") {
|
||||
t.Fatalf("rendering %q contains the code", rendered)
|
||||
}
|
||||
}
|
||||
if code.Reveal() != "482915" || code.IsZero() || !(VerificationCode{}).IsZero() {
|
||||
t.Fatal("Reveal or IsZero does not report the stored code")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerificationCodeHashIsZeroOnlyWhenUnset(t *testing.T) {
|
||||
if !(VerificationCodeHash{}).IsZero() {
|
||||
t.Fatal("the zero digest is not reported as zero")
|
||||
}
|
||||
if (VerificationCodeHash{1}).IsZero() {
|
||||
t.Fatal("a set digest is reported as zero")
|
||||
}
|
||||
}
|
||||
|
||||
func verificationTokenInput(t *testing.T, purpose EmailTokenPurpose) NewEmailTokenInput {
|
||||
t.Helper()
|
||||
raw, err := NewSecretToken()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return NewEmailTokenInput{
|
||||
UserID: uuid.New(),
|
||||
Purpose: purpose,
|
||||
TokenHash: raw.Hash(),
|
||||
RegistrationVersion: 1,
|
||||
IssuedAt: time.Date(2026, time.October, 9, 12, 0, 0, 0, time.UTC),
|
||||
Lifetime: 24 * time.Hour,
|
||||
CodeHash: VerificationCodeHash{1},
|
||||
CodeLifetime: VerificationCodeLifetime,
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewEmailTokenEndsTheCodeAtTheEarlierOfTokenAndCodeLifetime(t *testing.T) {
|
||||
input := verificationTokenInput(t, EmailTokenPurposeEmailVerification)
|
||||
token, err := NewEmailToken(input)
|
||||
if err != nil {
|
||||
t.Fatalf("NewEmailToken() error = %v", err)
|
||||
}
|
||||
if token.Code == nil || token.Code.Hash != input.CodeHash {
|
||||
t.Fatalf("token code = %+v, want the digest", token.Code)
|
||||
}
|
||||
if want := input.IssuedAt.Add(VerificationCodeLifetime); !token.Code.ExpiresAt.Equal(want) {
|
||||
t.Fatalf("code expiry = %s, want %s", token.Code.ExpiresAt, want)
|
||||
}
|
||||
|
||||
input.Lifetime = 10 * time.Minute
|
||||
token, err = NewEmailToken(input)
|
||||
if err != nil {
|
||||
t.Fatalf("NewEmailToken(short token) error = %v", err)
|
||||
}
|
||||
if !token.Code.ExpiresAt.Equal(token.ExpiresAt) {
|
||||
t.Fatalf("code expiry = %s, want the token expiry %s", token.Code.ExpiresAt, token.ExpiresAt)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewEmailTokenRequiresCodeFieldsTogetherAndOnlyForVerification(t *testing.T) {
|
||||
cases := map[string]func(*NewEmailTokenInput){
|
||||
"hash without lifetime": func(input *NewEmailTokenInput) { input.CodeLifetime = 0 },
|
||||
"lifetime without hash": func(input *NewEmailTokenInput) { input.CodeHash = VerificationCodeHash{} },
|
||||
"negative lifetime": func(input *NewEmailTokenInput) { input.CodeLifetime = -time.Minute },
|
||||
}
|
||||
for name, mutate := range cases {
|
||||
input := verificationTokenInput(t, EmailTokenPurposeEmailVerification)
|
||||
mutate(&input)
|
||||
if _, err := NewEmailToken(input); !errors.Is(err, ErrInvalidEmailToken) {
|
||||
t.Fatalf("NewEmailToken(%s) error = %v, want ErrInvalidEmailToken", name, err)
|
||||
}
|
||||
}
|
||||
reset := verificationTokenInput(t, EmailTokenPurposePasswordReset)
|
||||
if _, err := NewEmailToken(reset); !errors.Is(err, ErrInvalidEmailToken) {
|
||||
t.Fatalf("NewEmailToken(reset with code) error = %v, want ErrInvalidEmailToken", err)
|
||||
}
|
||||
plain := verificationTokenInput(t, EmailTokenPurposeEmailVerification)
|
||||
plain.CodeHash = VerificationCodeHash{}
|
||||
plain.CodeLifetime = 0
|
||||
token, err := NewEmailToken(plain)
|
||||
if err != nil || token.Code != nil {
|
||||
t.Fatalf("NewEmailToken(no code) = %+v, %v; want no code state", token.Code, err)
|
||||
}
|
||||
}
|
||||
@@ -68,6 +68,9 @@ type EmailToken struct {
|
||||
ExpiresAt time.Time
|
||||
ConsumedAt *time.Time
|
||||
InvalidatedAt *time.Time
|
||||
// Code is set on a verification token that carries a six-digit code and
|
||||
// nil otherwise. Its digest is never the code itself.
|
||||
Code *EmailCode
|
||||
// Pending is set on the verification token of a registration and nil on
|
||||
// a token that carries no credentials.
|
||||
Pending *PendingRegistration
|
||||
@@ -82,6 +85,11 @@ type NewEmailTokenInput struct {
|
||||
RegistrationVersion int64
|
||||
IssuedAt time.Time
|
||||
Lifetime time.Duration
|
||||
// CodeHash and CodeLifetime describe the optional verification code. Both
|
||||
// are set together or both are zero. The code expires at the earlier of
|
||||
// the token expiry and IssuedAt plus CodeLifetime.
|
||||
CodeHash VerificationCodeHash
|
||||
CodeLifetime time.Duration
|
||||
// Pending is optional; see PendingRegistration.
|
||||
Pending *PendingRegistration
|
||||
}
|
||||
@@ -99,24 +107,45 @@ func NewEmailToken(input NewEmailTokenInput) (EmailToken, error) {
|
||||
return EmailToken{}, invalidEmailToken("issue time must be set")
|
||||
case input.Lifetime <= 0:
|
||||
return EmailToken{}, invalidEmailToken("lifetime must be positive")
|
||||
case input.CodeHash.IsZero() != (input.CodeLifetime == 0):
|
||||
return EmailToken{}, invalidEmailToken("code hash and code lifetime must be set together")
|
||||
case input.CodeLifetime < 0:
|
||||
return EmailToken{}, invalidEmailToken("code lifetime must not be negative")
|
||||
}
|
||||
if _, err := ParseEmailTokenPurpose(string(input.Purpose)); err != nil {
|
||||
return EmailToken{}, fmt.Errorf("domain.NewEmailToken - validate purpose: %w", err)
|
||||
}
|
||||
if !input.CodeHash.IsZero() && input.Purpose != EmailTokenPurposeEmailVerification {
|
||||
return EmailToken{}, invalidEmailToken("only an email verification token carries a code")
|
||||
}
|
||||
id, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
return EmailToken{}, fmt.Errorf("domain.NewEmailToken - generate token ID: %w", err)
|
||||
}
|
||||
return EmailToken{
|
||||
expiresAt := input.IssuedAt.Add(input.Lifetime)
|
||||
token := EmailToken{
|
||||
ID: id,
|
||||
UserID: input.UserID,
|
||||
Purpose: input.Purpose,
|
||||
TokenHash: input.TokenHash,
|
||||
RegistrationVersion: input.RegistrationVersion,
|
||||
CreatedAt: input.IssuedAt,
|
||||
ExpiresAt: input.IssuedAt.Add(input.Lifetime),
|
||||
ExpiresAt: expiresAt,
|
||||
Pending: input.Pending,
|
||||
}, nil
|
||||
}
|
||||
if !input.CodeHash.IsZero() {
|
||||
token.Code = &EmailCode{Hash: input.CodeHash, ExpiresAt: earlierInstant(expiresAt, input.IssuedAt.Add(input.CodeLifetime))}
|
||||
}
|
||||
return token, nil
|
||||
}
|
||||
|
||||
// earlierInstant returns the earlier of two instants. The time type is not
|
||||
// ordered by the built-in min.
|
||||
func earlierInstant(left, right time.Time) time.Time {
|
||||
if right.Before(left) {
|
||||
return right
|
||||
}
|
||||
return left
|
||||
}
|
||||
|
||||
func invalidEmailToken(reason string) error {
|
||||
|
||||
Reference in new issue
Block a user