Files
lincodex/backend/internal/domain/user.go
T

262 lines
9.9 KiB
Go

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. The string sits behind a
// pointer so that printing an enclosing struct shows only an address (see
// redactedValue).
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: newRedactedValue(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 redactedValue(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) }
// 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 == nil }
// 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
}