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) } }