feat(identity): store users, email tokens, and sessions

This commit is contained in:
shira committed 2026-10-06 00:15:22 +03:00
1 parent 15e2e50561
commit e7d0d92ef9
30 files changed
+4792 -32

No files matched your search

+157
View File
@@ -0,0 +1,157 @@
package domain
import (
"errors"
"fmt"
"log/slog"
"strings"
)
const (
// Bounds follow the EmailAddress schema in the public contract (3 to 254
// characters) and the RFC 5321 local-part limit of 64 octets. Addresses
// are ASCII, so characters and bytes coincide.
minEmailAddressLength = 3
maxEmailAddressLength = 254
maxEmailLocalPartSize = 64
maxEmailDomainLabel = 63
redactedEmailAddress = "[redacted email]"
asciiWhitespace = " \t\n\v\f\r"
)
var ErrInvalidEmailAddress = errors.New("invalid email address")
// EmailAddress is a syntactically valid ASCII account email in two forms.
//
// Address is the delivery form: the input with surrounding ASCII whitespace
// removed, in the letter case the user typed, because RFC 5321 allows a
// case-sensitive local part. The account view returns it.
//
// Normalized is the comparison key: the address with A-Z lowercased. Storage
// keeps it unique, so addresses that differ only in letter case conflict. Go
// owns this rule; the database never recomputes the key, because PostgreSQL
// lower() depends on the collation.
//
// Only ASCII addresses are accepted because the mailer does not support
// SMTPUTF8. Internationalized domains are accepted in their ASCII (punycode)
// form. Accepting Unicode addresses is future work: it needs IDNA ToASCII for
// 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.
type EmailAddress struct {
address string
normalized string
}
// NewEmailAddress validates raw and returns both forms. It rejects non-ASCII
// characters, display names, quoted local parts, comments, whitespace or
// control characters inside the address, IP-literal domains, and domains
// without a dot. The outcome depends only on raw, never on stored accounts.
func NewEmailAddress(raw string) (EmailAddress, error) {
// Only ASCII whitespace is trimmed; any other character is validated.
address := strings.Trim(raw, asciiWhitespace)
for index := range len(address) {
if address[index] <= ' ' || address[index] > '~' {
return EmailAddress{}, invalidEmailAddress("address must contain printable ASCII characters only")
}
}
if length := len(address); length < minEmailAddressLength || length > maxEmailAddressLength {
return EmailAddress{}, invalidEmailAddress("address must have 3 to 254 characters")
}
localPart, domainPart, found := strings.Cut(address, "@")
if !found || strings.Contains(domainPart, "@") {
return EmailAddress{}, invalidEmailAddress("address must contain exactly one @")
}
if err := validateEmailLocalPart(localPart); err != nil {
return EmailAddress{}, err
}
if err := validateEmailDomain(domainPart); err != nil {
return EmailAddress{}, err
}
return EmailAddress{address: address, normalized: normalizeEmailKey(address)}, nil
}
// RestoreEmailAddress rebuilds an EmailAddress from storage. It checks only
// that the stored key matches the stored address, so a later, stricter
// NewEmailAddress rule does not make existing accounts unreadable.
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
}
// normalizeEmailKey lowercases A-Z only, independent of locale and Unicode
// case rules.
func normalizeEmailKey(address string) string {
return strings.Map(func(character rune) rune {
if 'A' <= character && character <= 'Z' {
return character + ('a' - 'A')
}
return character
}, address)
}
func validateEmailLocalPart(localPart string) error {
if localPart == "" || len(localPart) > maxEmailLocalPartSize {
return invalidEmailAddress("local part must have 1 to 64 characters")
}
if strings.HasPrefix(localPart, ".") || strings.HasSuffix(localPart, ".") || strings.Contains(localPart, "..") {
return invalidEmailAddress("local part must not start or end with a dot or contain consecutive dots")
}
for _, character := range localPart {
if !isASCIILetterOrDigit(character) && !strings.ContainsRune(".!#$%&'*+-/=?^_`{|}~", character) {
return invalidEmailAddress("local part contains a character outside an unquoted dot-atom")
}
}
return nil
}
func validateEmailDomain(domainPart string) error {
labels := strings.Split(domainPart, ".")
if len(labels) < 2 {
return invalidEmailAddress("domain must contain at least two labels")
}
for _, label := range labels {
if label == "" || len(label) > maxEmailDomainLabel {
return invalidEmailAddress("domain labels must have 1 to 63 characters")
}
if strings.HasPrefix(label, "-") || strings.HasSuffix(label, "-") {
return invalidEmailAddress("domain labels must not start or end with a hyphen")
}
for _, character := range label {
if !isASCIILetterOrDigit(character) && character != '-' {
return invalidEmailAddress("domain contains a character outside letters, digits, and hyphens")
}
}
}
return nil
}
func isASCIILetterOrDigit(character rune) bool {
return ('a' <= character && character <= 'z') || ('A' <= character && character <= 'Z') || ('0' <= character && character <= '9')
}
func invalidEmailAddress(reason string) error {
return fmt.Errorf("domain.NewEmailAddress - %s: %w", reason, ErrInvalidEmailAddress)
}
// 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 }
// Normalized returns the comparison key that storage keeps unique.
func (email EmailAddress) Normalized() string { return email.normalized }
// IsZero reports an EmailAddress not built by NewEmailAddress.
func (email EmailAddress) IsZero() bool { return email.normalized == "" }
func (email EmailAddress) String() string { return redactedEmailAddress }
func (email EmailAddress) GoString() string { return redactedEmailAddress }
// Format redacts every verb; without it %d would print the struct fields.
func (email EmailAddress) Format(state fmt.State, _ rune) { writeRedacted(state, redactedEmailAddress) }
func (email EmailAddress) LogValue() slog.Value { return slog.StringValue(redactedEmailAddress) }
@@ -0,0 +1,145 @@
package domain
import (
"bytes"
"errors"
"fmt"
"log/slog"
"strings"
"testing"
)
func TestNewEmailAddressNormalizes(t *testing.T) {
tests := []struct {
name string
raw string
wantAddress string
wantNormalized string
}{
{name: "plain", raw: "candidate@example.com", wantAddress: "candidate@example.com", wantNormalized: "candidate@example.com"},
{name: "trims and keeps case for delivery", raw: " \tAlice.Smith@Example.COM\n", wantAddress: "Alice.Smith@Example.COM", wantNormalized: "alice.smith@example.com"},
{name: "atext characters", raw: "O'Neil+Tag_1!#$%&*/=?^`{|}~-x@example.com", wantAddress: "O'Neil+Tag_1!#$%&*/=?^`{|}~-x@example.com", wantNormalized: "o'neil+tag_1!#$%&*/=?^`{|}~-x@example.com"},
{name: "punycode domain stays ASCII", raw: "Info@XN--E1AFMKFD.xn--p1ai", wantAddress: "Info@XN--E1AFMKFD.xn--p1ai", wantNormalized: "info@xn--e1afmkfd.xn--p1ai"},
{name: "minimum length", raw: "a@b.c", wantAddress: "a@b.c", wantNormalized: "a@b.c"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
email, err := NewEmailAddress(test.raw)
if err != nil {
t.Fatalf("NewEmailAddress(%q) error = %v", test.raw, err)
}
if email.Address() != test.wantAddress || email.Normalized() != test.wantNormalized {
t.Fatalf("NewEmailAddress(%q) = (%q, %q), want (%q, %q)",
test.raw, email.Address(), email.Normalized(), test.wantAddress, test.wantNormalized)
}
})
}
}
func TestNewEmailAddressCaseVariantsShareTheKey(t *testing.T) {
variants := []string{"Candidate@Example.com", "CANDIDATE@EXAMPLE.COM", " candidate@example.com "}
first, err := NewEmailAddress(variants[0])
if err != nil {
t.Fatalf("NewEmailAddress(%q) error = %v", variants[0], err)
}
for _, variant := range variants[1:] {
email, err := NewEmailAddress(variant)
if err != nil {
t.Fatalf("NewEmailAddress(%q) error = %v", variant, err)
}
if email.Normalized() != first.Normalized() {
t.Fatalf("Normalized(%q) = %q, want %q", variant, email.Normalized(), first.Normalized())
}
}
}
func TestNewEmailAddressRejectsInvalidInput(t *testing.T) {
longLocal := strings.Repeat("a", maxEmailLocalPartSize+1) + "@example.com"
longLabel := "a@" + strings.Repeat("b", maxEmailDomainLabel+1) + ".com"
tooLong := strings.Repeat("a", 60) + "@" + strings.Repeat(strings.Repeat("b", 60)+".", 3) + "example.com"
tests := map[string]string{
"empty": "",
"blank": " ",
"too short": "a@",
"too long": tooLong,
"no at": "candidate.example.com",
"two ats": "a@b@example.com",
"empty local part": "@example.com",
"empty domain": "candidate@",
"single-label domain": "candidate@localhost",
"leading dot": ".candidate@example.com",
"trailing dot": "candidate.@example.com",
"consecutive dots": "can..didate@example.com",
"inner space": "can didate@example.com",
"quoted local part": `"can didate"@example.com`,
"display name": "Candidate <candidate@example.com>",
"comment": "candidate(comment)@example.com",
"control character": "cand\x00idate@example.com",
"empty domain label": "candidate@example..com",
"hyphen edge label": "candidate@-example.com",
"ip literal": "candidate@[127.0.0.1]",
"underscore in domain": "candidate@exa_mple.com",
"local part too long": longLocal,
"domain label too long": longLabel,
"invalid utf-8": "cand\xffidate@example.com",
// Non-ASCII input is rejected until IDNA and SMTPUTF8 are supported.
"dotted capital I": "İnfo@x.com",
"fullwidth domain": "info@example.com",
"mixed-script homoglyph": "pаypal@example.com",
"cyrillic domain": "info@пример.рф",
"decomposed accent": "José@example.com",
"non-breaking space trim": " candidate@example.com",
}
for name, raw := range tests {
t.Run(name, func(t *testing.T) {
if _, err := NewEmailAddress(raw); !errors.Is(err, ErrInvalidEmailAddress) {
t.Fatalf("NewEmailAddress(%q) error = %v, want ErrInvalidEmailAddress", raw, err)
}
})
}
}
func TestRestoreEmailAddressChecksOnlyConsistency(t *testing.T) {
// A stored address that today's rule would reject still restores, as long
// as its key matches.
restored, err := RestoreEmailAddress("Legacy@Host", "legacy@host")
if err != nil {
t.Fatalf("RestoreEmailAddress(consistent) error = %v", err)
}
if restored.Address() != "Legacy@Host" || restored.Normalized() != "legacy@host" {
t.Fatalf("RestoreEmailAddress() = (%q, %q)", restored.Address(), restored.Normalized())
}
for _, pair := range [][2]string{{"Legacy@Host", "Legacy@Host"}, {"a@example.com", "b@example.com"}, {"", ""}} {
if _, err := RestoreEmailAddress(pair[0], pair[1]); !errors.Is(err, ErrInvalidEmailAddress) {
t.Fatalf("RestoreEmailAddress(%q, %q) error = %v, want ErrInvalidEmailAddress", pair[0], pair[1], err)
}
}
}
func TestEmailAddressZeroValue(t *testing.T) {
if !(EmailAddress{}).IsZero() {
t.Fatal("zero EmailAddress is not reported as zero")
}
email, err := NewEmailAddress("candidate@example.com")
if err != nil {
t.Fatalf("NewEmailAddress() error = %v", err)
}
if email.IsZero() {
t.Fatal("valid EmailAddress is reported as zero")
}
}
func TestEmailAddressIsRedacted(t *testing.T) {
email, err := NewEmailAddress("Secret.Person@Example.com")
if err != nil {
t.Fatalf("NewEmailAddress() error = %v", err)
}
var logs bytes.Buffer
slog.New(slog.NewJSONHandler(&logs, nil)).Info("redaction", "email", email)
formatted := fmt.Sprintf("%v %+v %#v %s %q %x %d", email, email, email, email, email, email, email) + logs.String()
for _, secret := range []string{email.Address(), email.Normalized(), "Secret", "secret"} {
if strings.Contains(formatted, secret) {
t.Fatalf("formatted output exposes the address: %s", formatted)
}
}
}
+90
View File
@@ -0,0 +1,90 @@
package domain
import (
"errors"
"fmt"
"time"
"github.com/google/uuid"
)
var ErrInvalidEmailToken = errors.New("invalid email token")
// EmailTokenPurpose names what an email token authorizes. New purposes, such
// as a planned password reset, are added here and in the email_tokens CHECK
// constraint together.
type EmailTokenPurpose string
// EmailTokenPurposeEmailVerification authorizes confirming the account email.
const EmailTokenPurposeEmailVerification EmailTokenPurpose = "email_verification" //nolint:gosec // A purpose name, not a credential.
// ParseEmailTokenPurpose accepts a known purpose.
func ParseEmailTokenPurpose(value string) (EmailTokenPurpose, error) {
purpose := EmailTokenPurpose(value)
if purpose != EmailTokenPurposeEmailVerification {
return "", fmt.Errorf("domain.ParseEmailTokenPurpose - unknown purpose: %w", ErrInvalidEmailToken)
}
return purpose, nil
}
// EmailToken is the stored record of a one-time token sent by email. It holds
// only the hash of the raw token. A token ends at most once: it is either
// consumed or invalidated, and it stops working at ExpiresAt.
type EmailToken struct {
ID uuid.UUID
UserID uuid.UUID
Purpose EmailTokenPurpose
TokenHash SecretTokenHash
RegistrationVersion int64
CreatedAt time.Time
ExpiresAt time.Time
ConsumedAt *time.Time
InvalidatedAt *time.Time
}
// NewEmailTokenInput describes a token to issue. RegistrationVersion is the
// user's current registration version.
type NewEmailTokenInput struct {
UserID uuid.UUID
Purpose EmailTokenPurpose
TokenHash SecretTokenHash
RegistrationVersion int64
IssuedAt time.Time
Lifetime time.Duration
}
// NewEmailToken validates input and assigns a UUIDv7 identifier.
func NewEmailToken(input NewEmailTokenInput) (EmailToken, error) {
switch {
case input.UserID == uuid.Nil:
return EmailToken{}, invalidEmailToken("user ID must not be nil")
case input.TokenHash.IsZero():
return EmailToken{}, invalidEmailToken("token hash must be set")
case input.RegistrationVersion <= 0:
return EmailToken{}, invalidEmailToken("registration version must be positive")
case input.IssuedAt.IsZero():
return EmailToken{}, invalidEmailToken("issue time must be set")
case input.Lifetime <= 0:
return EmailToken{}, invalidEmailToken("lifetime must be positive")
}
if _, err := ParseEmailTokenPurpose(string(input.Purpose)); err != nil {
return EmailToken{}, fmt.Errorf("domain.NewEmailToken - validate purpose: %w", err)
}
id, err := uuid.NewV7()
if err != nil {
return EmailToken{}, fmt.Errorf("domain.NewEmailToken - generate token ID: %w", err)
}
return EmailToken{
ID: id,
UserID: input.UserID,
Purpose: input.Purpose,
TokenHash: input.TokenHash,
RegistrationVersion: input.RegistrationVersion,
CreatedAt: input.IssuedAt,
ExpiresAt: input.IssuedAt.Add(input.Lifetime),
}, nil
}
func invalidEmailToken(reason string) error {
return fmt.Errorf("domain.NewEmailToken - %s: %w", reason, ErrInvalidEmailToken)
}
@@ -0,0 +1,66 @@
package domain
import (
"errors"
"testing"
"time"
"github.com/google/uuid"
)
func testTokenHash(t *testing.T) SecretTokenHash {
t.Helper()
token, err := NewSecretToken()
if err != nil {
t.Fatalf("NewSecretToken() error = %v", err)
}
return token.Hash()
}
func TestNewEmailTokenSetsExpiryFromLifetime(t *testing.T) {
input := NewEmailTokenInput{
UserID: uuid.New(),
Purpose: EmailTokenPurposeEmailVerification,
TokenHash: testTokenHash(t),
RegistrationVersion: 3,
IssuedAt: testRegisteredAt,
Lifetime: 24 * time.Hour,
}
token, err := NewEmailToken(input)
if err != nil {
t.Fatalf("NewEmailToken() error = %v", err)
}
if token.ID.Version() != 7 || token.UserID != input.UserID || token.TokenHash != input.TokenHash ||
token.RegistrationVersion != 3 || !token.CreatedAt.Equal(testRegisteredAt) ||
!token.ExpiresAt.Equal(testRegisteredAt.Add(24*time.Hour)) || token.ConsumedAt != nil || token.InvalidatedAt != nil {
t.Fatalf("NewEmailToken() = %+v", token)
}
}
func TestNewEmailTokenRejectsInvalidInput(t *testing.T) {
valid := NewEmailTokenInput{
UserID: uuid.New(),
Purpose: EmailTokenPurposeEmailVerification,
TokenHash: testTokenHash(t),
RegistrationVersion: 1,
IssuedAt: testRegisteredAt,
Lifetime: time.Hour,
}
tests := map[string]func(*NewEmailTokenInput){
"nil user": func(input *NewEmailTokenInput) { input.UserID = uuid.Nil },
"unknown purpose": func(input *NewEmailTokenInput) { input.Purpose = "password_reset" },
"zero hash": func(input *NewEmailTokenInput) { input.TokenHash = SecretTokenHash{} },
"zero version": func(input *NewEmailTokenInput) { input.RegistrationVersion = 0 },
"zero issue time": func(input *NewEmailTokenInput) { input.IssuedAt = time.Time{} },
"non-positive lifetime": func(input *NewEmailTokenInput) { input.Lifetime = 0 },
}
for name, mutate := range tests {
t.Run(name, func(t *testing.T) {
input := valid
mutate(&input)
if _, err := NewEmailToken(input); !errors.Is(err, ErrInvalidEmailToken) {
t.Fatalf("NewEmailToken() error = %v, want ErrInvalidEmailToken", err)
}
})
}
}
+88
View File
@@ -0,0 +1,88 @@
package domain
import (
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"errors"
"fmt"
"log/slog"
"regexp"
)
const (
// secretTokenEntropyBytes gives 256 bits of entropy. The encoded value is
// 43 base64url characters, inside the 32 to 128 character bounds that the
// contract sets for VerificationToken and CsrfToken.
secretTokenEntropyBytes = 32
// SecretTokenHashSize is the size of a SHA-256 digest.
SecretTokenHashSize = sha256.Size
redactedSecret = "[redacted]"
)
var (
ErrInvalidSecretToken = errors.New("invalid secret token")
// The contract pattern for raw tokens that arrive in requests.
secretTokenPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{32,128}$`)
)
// SecretToken is a random bearer secret: the token in an email link or the
// 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.
type SecretToken struct {
value string
}
// NewSecretToken returns a token with 256 bits from crypto/rand.
func NewSecretToken() (SecretToken, error) {
entropy := make([]byte, secretTokenEntropyBytes)
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
}
// ParseSecretToken accepts a raw token from a request. It checks only the
// contract shape; whether the token exists is decided by its hash in storage.
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
}
// 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)))
}
// 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) String() string { return redactedSecret }
func (token SecretToken) GoString() string { return redactedSecret }
func (token SecretToken) LogValue() slog.Value { return slog.StringValue(redactedSecret) }
// Format redacts every verb; without it %d would print the struct fields.
func (token SecretToken) Format(state fmt.State, _ rune) { writeRedacted(state, redactedSecret) }
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 == "" }
// SecretTokenHash is the SHA-256 digest of a SecretToken.
type SecretTokenHash [SecretTokenHashSize]byte
// IsZero reports the all-zero value, which no real token hashes to in practice
// and which marks a missing hash.
func (hash SecretTokenHash) IsZero() bool { return hash == SecretTokenHash{} }
@@ -0,0 +1,80 @@
package domain
import (
"bytes"
"crypto/sha256"
"errors"
"fmt"
"log/slog"
"strings"
"testing"
)
func TestNewSecretTokenMatchesTheContractShape(t *testing.T) {
token, err := NewSecretToken()
if err != nil {
t.Fatalf("NewSecretToken() error = %v", err)
}
parsed, err := ParseSecretToken(token.Reveal())
if err != nil {
t.Fatalf("ParseSecretToken(generated) error = %v", err)
}
if parsed.Hash() != token.Hash() {
t.Fatal("a parsed token hashes differently from the generated one")
}
other, err := NewSecretToken()
if err != nil {
t.Fatalf("NewSecretToken() error = %v", err)
}
if other.Reveal() == token.Reveal() {
t.Fatal("NewSecretToken() repeated a value")
}
}
func TestSecretTokenHashIsSHA256OfTheRawValue(t *testing.T) {
raw := strings.Repeat("A", 43)
token, err := ParseSecretToken(raw)
if err != nil {
t.Fatalf("ParseSecretToken() error = %v", err)
}
if want := sha256.Sum256([]byte(raw)); token.Hash() != SecretTokenHash(want) {
t.Fatal("Hash() is not the SHA-256 digest of the raw token")
}
if token.Hash().IsZero() || !(SecretTokenHash{}).IsZero() {
t.Fatal("IsZero() does not distinguish a real digest from the zero value")
}
}
func TestParseSecretTokenRejectsValuesOutsideTheContract(t *testing.T) {
for _, raw := range []string{
"",
strings.Repeat("a", 31),
strings.Repeat("a", 129),
strings.Repeat("a", 40) + "=",
strings.Repeat("a", 40) + "+/",
strings.Repeat("a", 40) + " ",
} {
if _, err := ParseSecretToken(raw); !errors.Is(err, ErrInvalidSecretToken) {
t.Fatalf("ParseSecretToken(%q) error = %v, want ErrInvalidSecretToken", raw, err)
}
}
}
func TestSecretTokenAndPasswordHashAreRedacted(t *testing.T) {
token, err := NewSecretToken()
if err != nil {
t.Fatalf("NewSecretToken() 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", "token", token, "hash", passwordHash)
formatted := fmt.Sprintf("%v %+v %#v %s %v %#v", token, token, token, passwordHash, passwordHash, passwordHash) + logs.String()
for _, secret := range []string{token.Reveal(), testPasswordHash} {
if strings.Contains(formatted, secret) {
t.Fatalf("formatted output exposes a secret: %s", formatted)
}
}
}
+67
View File
@@ -0,0 +1,67 @@
package domain
import (
"errors"
"fmt"
"time"
"github.com/google/uuid"
)
var ErrInvalidSession = errors.New("invalid session")
// Session is a server-side login session. The cookie carries the raw
// SecretToken; storage keeps only TokenHash. ID identifies the session inside
// the server, for example to revoke it, and never leaves the server.
//
// A session is active while it is not revoked, ExpiresAt (the absolute
// deadline) is in the future, and LastSeenAt is within the idle timeout.
// Activity moves only LastSeenAt.
type Session struct {
ID uuid.UUID
UserID uuid.UUID
TokenHash SecretTokenHash
CreatedAt time.Time
LastSeenAt time.Time
ExpiresAt time.Time
RevokedAt *time.Time
}
// NewSessionInput describes a session to start. AbsoluteLifetime fixes
// ExpiresAt; the idle timeout is applied when the session is looked up.
type NewSessionInput struct {
UserID uuid.UUID
TokenHash SecretTokenHash
StartedAt time.Time
AbsoluteLifetime time.Duration
}
// NewSession validates input and assigns a UUIDv7 identifier.
func NewSession(input NewSessionInput) (Session, error) {
switch {
case input.UserID == uuid.Nil:
return Session{}, invalidSession("user ID must not be nil")
case input.TokenHash.IsZero():
return Session{}, invalidSession("token hash must be set")
case input.StartedAt.IsZero():
return Session{}, invalidSession("start time must be set")
case input.AbsoluteLifetime <= 0:
return Session{}, invalidSession("absolute lifetime must be positive")
}
id, err := uuid.NewV7()
if err != nil {
return Session{}, fmt.Errorf("domain.NewSession - generate session ID: %w", err)
}
return Session{
ID: id,
UserID: input.UserID,
TokenHash: input.TokenHash,
CreatedAt: input.StartedAt,
LastSeenAt: input.StartedAt,
ExpiresAt: input.StartedAt.Add(input.AbsoluteLifetime),
}, nil
}
func invalidSession(reason string) error {
return fmt.Errorf("domain.NewSession - %s: %w", reason, ErrInvalidSession)
}
+46
View File
@@ -0,0 +1,46 @@
package domain
import (
"errors"
"testing"
"time"
"github.com/google/uuid"
)
func TestNewSessionSetsDeadlines(t *testing.T) {
input := NewSessionInput{
UserID: uuid.New(),
TokenHash: testTokenHash(t),
StartedAt: testRegisteredAt,
AbsoluteLifetime: 7 * 24 * time.Hour,
}
session, err := NewSession(input)
if err != nil {
t.Fatalf("NewSession() error = %v", err)
}
if session.ID.Version() != 7 || session.UserID != input.UserID || session.TokenHash != input.TokenHash ||
!session.CreatedAt.Equal(testRegisteredAt) || !session.LastSeenAt.Equal(testRegisteredAt) ||
!session.ExpiresAt.Equal(testRegisteredAt.Add(7*24*time.Hour)) || session.RevokedAt != nil {
t.Fatalf("NewSession() = %+v", session)
}
}
func TestNewSessionRejectsInvalidInput(t *testing.T) {
valid := NewSessionInput{UserID: uuid.New(), TokenHash: testTokenHash(t), StartedAt: testRegisteredAt, AbsoluteLifetime: time.Hour}
tests := map[string]func(*NewSessionInput){
"nil user": func(input *NewSessionInput) { input.UserID = uuid.Nil },
"zero hash": func(input *NewSessionInput) { input.TokenHash = SecretTokenHash{} },
"zero start": func(input *NewSessionInput) { input.StartedAt = time.Time{} },
"non-positive lifetime": func(input *NewSessionInput) { input.AbsoluteLifetime = -time.Second },
}
for name, mutate := range tests {
t.Run(name, func(t *testing.T) {
input := valid
mutate(&input)
if _, err := NewSession(input); !errors.Is(err, ErrInvalidSession) {
t.Fatalf("NewSession() error = %v, want ErrInvalidSession", err)
}
})
}
}
+255
View File
@@ -0,0 +1,255 @@
package domain
import (
"encoding/base64"
"errors"
"fmt"
"log/slog"
"regexp"
"time"
"github.com/google/uuid"
)
const (
// maxPasswordHashLength bounds a PHC string. Encoded Argon2id hashes with
// common parameters stay near 100 bytes.
maxPasswordHashLength = 512
// minPasswordSaltBytes and minPasswordDigestBytes follow the RFC 9106
// recommendations of a 16-byte salt and a 32-byte tag, relaxed to bounds
// that still reject truncated or placeholder values.
minPasswordSaltBytes = 8
minPasswordDigestBytes = 16
)
// passwordHashPattern is the Argon2id PHC string format: version 19, memory,
// iterations, and parallelism, then the salt and the digest in unpadded
// standard base64. Argon2id is the only password hash the identity contract
// accepts.
var passwordHashPattern = regexp.MustCompile(
`^\$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+/]+)$`,
)
var (
ErrInvalidUser = errors.New("invalid user")
ErrInvalidPasswordHash = errors.New("invalid password hash")
ErrEmailAlreadyVerified = errors.New("email already verified")
)
// Scenario is the account scenario chosen at registration. Values match the
// AccountScenario schema of the public contract.
type Scenario string
const (
ScenarioCandidate Scenario = "candidate"
ScenarioEmployer Scenario = "employer"
)
// ParseScenario accepts a value of the AccountScenario contract enum.
func ParseScenario(value string) (Scenario, error) {
scenario := Scenario(value)
switch scenario {
case ScenarioCandidate, ScenarioEmployer:
return scenario, nil
default:
return "", fmt.Errorf("domain.ParseScenario - unknown scenario: %w", ErrInvalidUser)
}
}
// InitialOnboardingStep is the step a new or re-registered account starts at.
func (scenario Scenario) InitialOnboardingStep() OnboardingStep {
if scenario == ScenarioEmployer {
return OnboardingStepEmployerCompany
}
return OnboardingStepCandidateConsents
}
// AllowsStep reports whether step belongs to the scenario's onboarding.
func (scenario Scenario) AllowsStep(step OnboardingStep) bool {
switch step {
case OnboardingStepCompleted:
return scenario == ScenarioCandidate || scenario == ScenarioEmployer
case OnboardingStepCandidateConsents, OnboardingStepCandidateProfile,
OnboardingStepCandidateQuestionnaire, OnboardingStepCandidateAssessment:
return scenario == ScenarioCandidate
case OnboardingStepEmployerCompany:
return scenario == ScenarioEmployer
default:
return false
}
}
// OnboardingStep is the saved step the account returns to after login. Values
// match the OnboardingStep schema of the public contract.
type OnboardingStep string
const (
OnboardingStepCandidateConsents OnboardingStep = "candidate_consents"
OnboardingStepCandidateProfile OnboardingStep = "candidate_profile"
OnboardingStepCandidateQuestionnaire OnboardingStep = "candidate_questionnaire"
OnboardingStepCandidateAssessment OnboardingStep = "candidate_assessment"
OnboardingStepEmployerCompany OnboardingStep = "employer_company"
OnboardingStepCompleted OnboardingStep = "completed"
)
// ParseOnboardingStep accepts a value of the OnboardingStep contract enum.
func ParseOnboardingStep(value string) (OnboardingStep, error) {
step := OnboardingStep(value)
switch step {
case OnboardingStepCandidateConsents, OnboardingStepCandidateProfile, OnboardingStepCandidateQuestionnaire,
OnboardingStepCandidateAssessment, OnboardingStepEmployerCompany, OnboardingStepCompleted:
return step, nil
default:
return "", fmt.Errorf("domain.ParseOnboardingStep - unknown onboarding step: %w", ErrInvalidUser)
}
}
// PasswordHash is an Argon2id hash in the PHC string format. It is never the
// password itself. String and LogValue redact it.
type PasswordHash struct {
phc string
}
// NewPasswordHash validates the structure of a PHC string produced by the
// password hasher, which also keeps a raw password from being stored by
// mistake.
func NewPasswordHash(phc string) (PasswordHash, error) {
if len(phc) > maxPasswordHashLength {
return PasswordHash{}, invalidPasswordHash("hash must have at most 512 bytes")
}
parts := passwordHashPattern.FindStringSubmatch(phc)
if parts == nil {
return PasswordHash{}, invalidPasswordHash("hash must be an Argon2id v19 PHC string")
}
salt, err := base64.RawStdEncoding.Strict().DecodeString(parts[1])
if err != nil || len(salt) < minPasswordSaltBytes {
return PasswordHash{}, invalidPasswordHash("salt must be unpadded base64 of at least 8 bytes")
}
digest, err := base64.RawStdEncoding.Strict().DecodeString(parts[2])
if err != nil || len(digest) < minPasswordDigestBytes {
return PasswordHash{}, invalidPasswordHash("digest must be unpadded base64 of at least 16 bytes")
}
return PasswordHash{phc: phc}, nil
}
func invalidPasswordHash(reason string) error {
return fmt.Errorf("domain.NewPasswordHash - %s: %w", reason, ErrInvalidPasswordHash)
}
// PHC returns the encoded hash for storage and verification.
func (hash PasswordHash) PHC() string { return hash.phc }
func (hash PasswordHash) String() string { return redactedSecret }
func (hash PasswordHash) GoString() string { return redactedSecret }
func (hash PasswordHash) LogValue() slog.Value { return slog.StringValue(redactedSecret) }
// Format redacts every verb; without it %d would print the struct fields.
func (hash PasswordHash) Format(state fmt.State, _ rune) { writeRedacted(state, redactedSecret) }
// IsZero reports a PasswordHash not built by NewPasswordHash.
func (hash PasswordHash) IsZero() bool { return hash.phc == "" }
// Registration is the validated content of one registration request.
type Registration struct {
Email EmailAddress
PasswordHash PasswordHash
Scenario Scenario
// RegisteredAt is the application clock at registration. The planned
// cleanup deletes an account that stays unverified past a deadline counted
// from the latest registration.
RegisteredAt time.Time
}
func (registration Registration) validate(location string) error {
if registration.Email.IsZero() {
return fmt.Errorf("%s - email must be built by NewEmailAddress: %w", location, ErrInvalidUser)
}
if registration.PasswordHash.IsZero() {
return fmt.Errorf("%s - password hash must be built by NewPasswordHash: %w", location, ErrInvalidUser)
}
if _, err := ParseScenario(string(registration.Scenario)); err != nil {
return fmt.Errorf("%s - validate scenario: %w", location, err)
}
if registration.RegisteredAt.IsZero() {
return fmt.Errorf("%s - registration time must be set: %w", location, ErrInvalidUser)
}
return nil
}
// User is an account. Storage reconstructs it from trusted rows; new accounts
// come from NewUser and changes from its methods.
type User struct {
ID uuid.UUID
Email EmailAddress
PasswordHash PasswordHash
Scenario Scenario
// OnboardingStep always belongs to Scenario (see Scenario.AllowsStep).
OnboardingStep OnboardingStep
EmailVerifiedAt *time.Time
// RegistrationVersion starts at 1 and advances on every registration of
// the still unverified email. Email tokens are bound to the version they
// were issued for, so a token from an earlier registration never confirms
// newer credentials.
RegistrationVersion int64
LastRegisteredAt time.Time
// Version is the optimistic concurrency version. Storage advances it on
// every update and accepts an update only from the version it was read at.
Version int64
CreatedAt time.Time
UpdatedAt time.Time
}
// NewUser creates an unverified account at the scenario's first onboarding
// step with a time-ordered UUIDv7 identifier.
func NewUser(registration Registration) (User, error) {
if err := registration.validate("domain.NewUser"); err != nil {
return User{}, err
}
id, err := uuid.NewV7()
if err != nil {
return User{}, fmt.Errorf("domain.NewUser - generate user ID: %w", err)
}
return User{
ID: id,
Email: registration.Email,
PasswordHash: registration.PasswordHash,
Scenario: registration.Scenario,
OnboardingStep: registration.Scenario.InitialOnboardingStep(),
RegistrationVersion: 1,
LastRegisteredAt: registration.RegisteredAt,
Version: 1,
CreatedAt: registration.RegisteredAt,
UpdatedAt: registration.RegisteredAt,
}, nil
}
// EmailVerified reports whether the email has been confirmed.
func (user User) EmailVerified() bool { return user.EmailVerifiedAt != nil }
// ReRegister applies a new registration of the same unverified email. It
// replaces the delivery form of the email, the password hash, the scenario,
// and the onboarding step. Version and RegistrationVersion are left unchanged:
// storage checks Version as the expected version, advances both in the same
// statement, and returns the stored account. A verified account returns
// ErrEmailAlreadyVerified and does not change.
func (user User) ReRegister(registration Registration) (User, error) {
if err := registration.validate("User.ReRegister"); err != nil {
return User{}, err
}
if user.EmailVerified() {
return User{}, fmt.Errorf("User.ReRegister - re-register account: %w", ErrEmailAlreadyVerified)
}
if registration.Email.Normalized() != user.Email.Normalized() {
return User{}, fmt.Errorf("User.ReRegister - email must match the account email: %w", ErrInvalidUser)
}
updated := user
updated.Email = registration.Email
updated.PasswordHash = registration.PasswordHash
updated.Scenario = registration.Scenario
updated.OnboardingStep = registration.Scenario.InitialOnboardingStep()
updated.LastRegisteredAt = registration.RegisteredAt
updated.UpdatedAt = registration.RegisteredAt
return updated, nil
}
+211
View File
@@ -0,0 +1,211 @@
package domain
import (
"errors"
"fmt"
"strings"
"testing"
"time"
)
const testPasswordHash = "$argon2id$v=19$m=19456,t=2,p=1$c2FsdHNhbHRzYWx0$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaA"
var testRegisteredAt = time.Date(2026, time.October, 5, 12, 0, 0, 0, time.UTC)
func testRegistration(t *testing.T, rawEmail string, scenario Scenario) Registration {
t.Helper()
email, err := NewEmailAddress(rawEmail)
if err != nil {
t.Fatalf("NewEmailAddress() error = %v", err)
}
passwordHash, err := NewPasswordHash(testPasswordHash)
if err != nil {
t.Fatalf("NewPasswordHash() error = %v", err)
}
return Registration{Email: email, PasswordHash: passwordHash, Scenario: scenario, RegisteredAt: testRegisteredAt}
}
func TestParseScenarioAndOnboardingStepAcceptContractValues(t *testing.T) {
for _, value := range []string{"candidate", "employer"} {
if scenario, err := ParseScenario(value); err != nil || string(scenario) != value {
t.Fatalf("ParseScenario(%q) = %q, %v", value, scenario, err)
}
}
for _, value := range []string{
"candidate_consents", "candidate_profile", "candidate_questionnaire",
"candidate_assessment", "employer_company", "completed",
} {
if step, err := ParseOnboardingStep(value); err != nil || string(step) != value {
t.Fatalf("ParseOnboardingStep(%q) = %q, %v", value, step, err)
}
}
for _, value := range []string{"", "Candidate", "admin"} {
if _, err := ParseScenario(value); !errors.Is(err, ErrInvalidUser) {
t.Fatalf("ParseScenario(%q) error = %v, want ErrInvalidUser", value, err)
}
if _, err := ParseOnboardingStep(value); !errors.Is(err, ErrInvalidUser) {
t.Fatalf("ParseOnboardingStep(%q) error = %v, want ErrInvalidUser", value, err)
}
}
}
func TestScenarioOnboardingSteps(t *testing.T) {
tests := []struct {
scenario Scenario
initial OnboardingStep
allowed []OnboardingStep
denied []OnboardingStep
}{
{
scenario: ScenarioCandidate,
initial: OnboardingStepCandidateConsents,
allowed: []OnboardingStep{
OnboardingStepCandidateConsents, OnboardingStepCandidateProfile, OnboardingStepCandidateQuestionnaire,
OnboardingStepCandidateAssessment, OnboardingStepCompleted,
},
denied: []OnboardingStep{OnboardingStepEmployerCompany, "unknown"},
},
{
scenario: ScenarioEmployer,
initial: OnboardingStepEmployerCompany,
allowed: []OnboardingStep{OnboardingStepEmployerCompany, OnboardingStepCompleted},
denied: []OnboardingStep{OnboardingStepCandidateConsents, OnboardingStepCandidateAssessment, "unknown"},
},
}
for _, test := range tests {
if got := test.scenario.InitialOnboardingStep(); got != test.initial {
t.Fatalf("%s.InitialOnboardingStep() = %q, want %q", test.scenario, got, test.initial)
}
for _, step := range test.allowed {
if !test.scenario.AllowsStep(step) {
t.Fatalf("%s.AllowsStep(%q) = false, want true", test.scenario, step)
}
}
for _, step := range test.denied {
if test.scenario.AllowsStep(step) {
t.Fatalf("%s.AllowsStep(%q) = true, want false", test.scenario, step)
}
}
}
}
func TestNewPasswordHashAcceptsOnlyArgon2idPHC(t *testing.T) {
for _, value := range []string{
testPasswordHash,
"$argon2id$v=19$m=65536,t=3,p=4$c29tZXNhbHRzb21lc2FsdA$RdescudvJCsgt3ub+b+dWRWJTmaaJObG",
} {
if _, err := NewPasswordHash(value); err != nil {
t.Fatalf("NewPasswordHash(%.30q) error = %v", value, err)
}
}
for name, value := range map[string]string{
"empty": "",
"raw password": "correct horse battery staple",
"bcrypt": "$2b$12$abcdefghijklmnopqrstuuABCDEFGHIJKLMNOPQRSTUVWXYZ01234",
"argon2i": "$argon2i$v=19$m=19456,t=2,p=1$c2FsdHNhbHRzYWx0$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaA",
"prefix only": "$argon2id$",
"old version": "$argon2id$v=16$m=19456,t=2,p=1$c2FsdHNhbHRzYWx0$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaA",
"missing parameter": "$argon2id$v=19$m=19456,t=2$c2FsdHNhbHRzYWx0$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaA",
"zero memory": "$argon2id$v=19$m=0,t=2,p=1$c2FsdHNhbHRzYWx0$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaA",
"padded salt": "$argon2id$v=19$m=19456,t=2,p=1$c2FsdHNhbHQ=$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaA",
"short salt": "$argon2id$v=19$m=19456,t=2,p=1$c2FsdA$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaA",
"short digest": "$argon2id$v=19$m=19456,t=2,p=1$c2FsdHNhbHRzYWx0$aGFzaA",
"impossible base64": "$argon2id$v=19$m=19456,t=2,p=1$c2FsdHNhbHRzYWx0a$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaA",
"url-safe alphabet": "$argon2id$v=19$m=19456,t=2,p=1$c2FsdHNhbHRzYWx0$aGFzaGhhc2hoYXNoaGF_aGhhc2hoYXNoaGFzaA",
"trailing space": testPasswordHash + " ",
"trailing newline": testPasswordHash + "\n",
"extra segment": testPasswordHash + "$extra",
"too long": "$argon2id$v=19$m=19456,t=2,p=1$c2FsdHNhbHRzYWx0$" + strings.Repeat("a", maxPasswordHashLength),
} {
if _, err := NewPasswordHash(value); !errors.Is(err, ErrInvalidPasswordHash) {
t.Fatalf("NewPasswordHash(%s) error = %v, want ErrInvalidPasswordHash", name, err)
}
}
}
func TestNewUserStartsUnverifiedAtTheFirstStep(t *testing.T) {
registration := testRegistration(t, "Employer@Example.com", ScenarioEmployer)
user, err := NewUser(registration)
if err != nil {
t.Fatalf("NewUser() error = %v", err)
}
if user.ID.Version() != 7 {
t.Fatalf("ID version = %d, want UUIDv7", user.ID.Version())
}
if user.EmailVerified() || user.OnboardingStep != OnboardingStepEmployerCompany ||
user.RegistrationVersion != 1 || user.Version != 1 {
t.Fatalf("NewUser() = %+v, want an unverified employer at employer_company with versions 1", user)
}
if !user.LastRegisteredAt.Equal(testRegisteredAt) || !user.CreatedAt.Equal(testRegisteredAt) || !user.UpdatedAt.Equal(testRegisteredAt) {
t.Fatalf("NewUser() timestamps = %v, %v, %v, want the registration time", user.LastRegisteredAt, user.CreatedAt, user.UpdatedAt)
}
}
func TestNewUserRejectsIncompleteRegistration(t *testing.T) {
valid := testRegistration(t, "candidate@example.com", ScenarioCandidate)
tests := map[string]func(*Registration){
"zero email": func(registration *Registration) { registration.Email = EmailAddress{} },
"zero password hash": func(registration *Registration) { registration.PasswordHash = PasswordHash{} },
"unknown scenario": func(registration *Registration) { registration.Scenario = "admin" },
"zero time": func(registration *Registration) { registration.RegisteredAt = time.Time{} },
}
for name, mutate := range tests {
t.Run(name, func(t *testing.T) {
registration := valid
mutate(&registration)
if _, err := NewUser(registration); !errors.Is(err, ErrInvalidUser) {
t.Fatalf("NewUser() error = %v, want ErrInvalidUser", err)
}
})
}
}
func TestReRegisterReplacesTheRegistrationOfAnUnverifiedAccount(t *testing.T) {
user, err := NewUser(testRegistration(t, "candidate@example.com", ScenarioCandidate))
if err != nil {
t.Fatalf("NewUser() error = %v", err)
}
user.OnboardingStep = OnboardingStepCandidateProfile
again := testRegistration(t, "Candidate@Example.com", ScenarioEmployer)
again.RegisteredAt = testRegisteredAt.Add(time.Hour)
updated, err := user.ReRegister(again)
if err != nil {
t.Fatalf("ReRegister() error = %v", err)
}
if updated.ID != user.ID || updated.Email.Address() != "Candidate@Example.com" ||
updated.Scenario != ScenarioEmployer || updated.OnboardingStep != OnboardingStepEmployerCompany ||
updated.RegistrationVersion != user.RegistrationVersion || updated.Version != user.Version ||
!updated.LastRegisteredAt.Equal(again.RegisteredAt) || !updated.UpdatedAt.Equal(again.RegisteredAt) ||
!updated.CreatedAt.Equal(user.CreatedAt) {
t.Fatalf("ReRegister() = %+v", updated)
}
}
func TestReRegisterRejectsVerifiedOrDifferentEmail(t *testing.T) {
user, err := NewUser(testRegistration(t, "candidate@example.com", ScenarioCandidate))
if err != nil {
t.Fatalf("NewUser() error = %v", err)
}
if _, err := user.ReRegister(testRegistration(t, "other@example.com", ScenarioCandidate)); !errors.Is(err, ErrInvalidUser) {
t.Fatalf("ReRegister(other email) error = %v, want ErrInvalidUser", err)
}
verifiedAt := testRegisteredAt.Add(time.Minute)
user.EmailVerifiedAt = &verifiedAt
if _, err := user.ReRegister(testRegistration(t, "candidate@example.com", ScenarioCandidate)); !errors.Is(err, ErrEmailAlreadyVerified) {
t.Fatalf("ReRegister(verified) error = %v, want ErrEmailAlreadyVerified", err)
}
}
func TestFormattedUserHidesEmailAndPasswordHash(t *testing.T) {
user, err := NewUser(testRegistration(t, "Private.Person@Example.com", ScenarioCandidate))
if err != nil {
t.Fatalf("NewUser() error = %v", err)
}
formatted := fmt.Sprintf("%v %+v %#v", user, user, user)
for _, secret := range []string{"Private", "private", "example.com", testPasswordHash, "argon2id"} {
if strings.Contains(formatted, secret) {
t.Fatalf("formatted user exposes %q: %s", secret, formatted)
}
}
}