my-homelab-configs/cmd/nextpath/internal/account/store.go

336 lines
9.4 KiB
Go

// Package account owns NextPath identities and private assessment state.
package account
import (
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"net/mail"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"sync"
"time"
)
const DefaultPasswordIterations = 310_000
var (
ErrDuplicateEmail = errors.New("an account already exists for this email")
ErrNotFound = errors.New("account not found")
zipPattern = regexp.MustCompile(`^[0-9]{5}$`)
allowedAgeBands = map[string]bool{
"13-17": true,
"18-24": true,
"25-39": true,
"40-54": true,
"55+": true,
}
)
type RegisterInput struct {
Email string
DisplayName string
AgeBand string
ZIPCode string
Password string
Consent bool
}
// User is the safe application-facing account representation. Password
// material is intentionally inaccessible outside this package.
type User struct {
ID string `json:"id"`
Email string `json:"email"`
DisplayName string `json:"display_name"`
AgeBand string `json:"age_band"`
ZIPCode string `json:"zip_code"`
Answers map[string]int `json:"assessment_answers"`
CreatedAt time.Time `json:"created_at"`
ConsentAt time.Time `json:"consent_at"`
AssessmentSeen string `json:"assessment_version,omitempty"`
}
type storedUser struct {
User
PasswordSalt string `json:"password_salt"`
PasswordHash string `json:"password_hash"`
PasswordIterations int `json:"password_iterations"`
}
type diskState struct {
Version int `json:"version"`
Users map[string]storedUser `json:"users"`
}
type Store struct {
mu sync.RWMutex
path string
iterations int
state diskState
now func() time.Time
}
func Open(path string, iterations int) (*Store, error) {
if strings.TrimSpace(path) == "" {
return nil, errors.New("account store path is required")
}
if iterations < 1 {
return nil, errors.New("password iterations must be positive")
}
store := &Store{
path: path,
iterations: iterations,
state: diskState{
Version: 1,
Users: make(map[string]storedUser),
},
now: time.Now,
}
data, err := os.ReadFile(path)
if errors.Is(err, os.ErrNotExist) {
return store, nil
}
if err != nil {
return nil, fmt.Errorf("read account store: %w", err)
}
if err := json.Unmarshal(data, &store.state); err != nil {
return nil, fmt.Errorf("decode account store: %w", err)
}
if store.state.Version != 1 || store.state.Users == nil {
return nil, fmt.Errorf("unsupported account store version %d", store.state.Version)
}
return store, nil
}
func (store *Store) Register(input RegisterInput) (User, error) {
input.Email = strings.ToLower(strings.TrimSpace(input.Email))
input.DisplayName = strings.TrimSpace(input.DisplayName)
input.ZIPCode = strings.TrimSpace(input.ZIPCode)
if err := validateRegistration(input); err != nil {
return User{}, err
}
store.mu.Lock()
defer store.mu.Unlock()
for _, candidate := range store.state.Users {
if candidate.Email == input.Email {
return User{}, ErrDuplicateEmail
}
}
id, err := randomToken(18)
if err != nil {
return User{}, fmt.Errorf("create account identifier: %w", err)
}
salt := make([]byte, 24)
if _, err := rand.Read(salt); err != nil {
return User{}, fmt.Errorf("create password salt: %w", err)
}
created := store.now().UTC()
user := User{
ID: id,
Email: input.Email,
DisplayName: input.DisplayName,
AgeBand: input.AgeBand,
ZIPCode: input.ZIPCode,
Answers: make(map[string]int),
CreatedAt: created,
ConsentAt: created,
}
stored := storedUser{
User: user,
PasswordSalt: base64.RawURLEncoding.EncodeToString(salt),
PasswordHash: base64.RawURLEncoding.EncodeToString(derivePassword([]byte(input.Password), salt, store.iterations)),
PasswordIterations: store.iterations,
}
store.state.Users[id] = stored
if err := store.persistLocked(); err != nil {
delete(store.state.Users, id)
return User{}, err
}
return cloneUser(user), nil
}
func (store *Store) Authenticate(email, password string) (User, bool) {
email = strings.ToLower(strings.TrimSpace(email))
store.mu.RLock()
defer store.mu.RUnlock()
for _, candidate := range store.state.Users {
if candidate.Email != email {
continue
}
salt, saltErr := base64.RawURLEncoding.DecodeString(candidate.PasswordSalt)
expected, hashErr := base64.RawURLEncoding.DecodeString(candidate.PasswordHash)
if saltErr != nil || hashErr != nil || candidate.PasswordIterations < 1 {
return User{}, false
}
actual := derivePassword([]byte(password), salt, candidate.PasswordIterations)
if subtle.ConstantTimeCompare(expected, actual) != 1 {
return User{}, false
}
return cloneUser(candidate.User), true
}
// Perform equivalent work so a missing email is not substantially cheaper.
dummySalt := sha256.Sum256([]byte("nextpath-missing-account"))
_ = derivePassword([]byte(password), dummySalt[:], store.iterations)
return User{}, false
}
func (store *Store) Get(id string) (User, error) {
store.mu.RLock()
defer store.mu.RUnlock()
user, ok := store.state.Users[id]
if !ok {
return User{}, ErrNotFound
}
return cloneUser(user.User), nil
}
func (store *Store) SaveAnswers(id, version string, answers map[string]int) (User, error) {
store.mu.Lock()
defer store.mu.Unlock()
user, ok := store.state.Users[id]
if !ok {
return User{}, ErrNotFound
}
user.Answers = make(map[string]int, len(answers))
for question, answer := range answers {
user.Answers[question] = answer
}
user.AssessmentSeen = version
store.state.Users[id] = user
if err := store.persistLocked(); err != nil {
return User{}, err
}
return cloneUser(user.User), nil
}
func (store *Store) Delete(id string) error {
store.mu.Lock()
defer store.mu.Unlock()
if _, ok := store.state.Users[id]; !ok {
return ErrNotFound
}
delete(store.state.Users, id)
return store.persistLocked()
}
func validateRegistration(input RegisterInput) error {
parsed, err := mail.ParseAddress(input.Email)
if err != nil || parsed.Address != input.Email {
return errors.New("enter a valid email address")
}
if len(input.DisplayName) < 1 || len(input.DisplayName) > 80 {
return errors.New("display name must contain 1 to 80 characters")
}
if !allowedAgeBands[input.AgeBand] {
return errors.New("select a supported age band")
}
if !zipPattern.MatchString(input.ZIPCode) || input.ZIPCode < "85000" || input.ZIPCode > "86599" {
return errors.New("enter a five-digit Arizona ZIP code")
}
if len(input.Password) < 12 || len(input.Password) > 256 {
return errors.New("password must contain 12 to 256 characters")
}
if !input.Consent {
return errors.New("privacy notice acceptance is required")
}
return nil
}
func (store *Store) persistLocked() error {
directory := filepath.Dir(store.path)
if err := os.MkdirAll(directory, 0o700); err != nil {
return fmt.Errorf("create account store directory: %w", err)
}
data, err := json.MarshalIndent(store.state, "", " ")
if err != nil {
return fmt.Errorf("encode account store: %w", err)
}
temporary, err := os.CreateTemp(directory, ".nextpath-accounts-*")
if err != nil {
return fmt.Errorf("create temporary account store: %w", err)
}
temporaryPath := temporary.Name()
defer os.Remove(temporaryPath)
if err := temporary.Chmod(0o600); err != nil {
temporary.Close()
return fmt.Errorf("protect temporary account store: %w", err)
}
if _, err := temporary.Write(data); err != nil {
temporary.Close()
return fmt.Errorf("write temporary account store: %w", err)
}
if err := temporary.Sync(); err != nil {
temporary.Close()
return fmt.Errorf("sync temporary account store: %w", err)
}
if err := temporary.Close(); err != nil {
return fmt.Errorf("close temporary account store: %w", err)
}
if err := os.Rename(temporaryPath, store.path); err != nil {
return fmt.Errorf("replace account store: %w", err)
}
return nil
}
func cloneUser(user User) User {
clone := user
clone.Answers = make(map[string]int, len(user.Answers))
for question, answer := range user.Answers {
clone.Answers[question] = answer
}
return clone
}
func randomToken(bytes int) (string, error) {
value := make([]byte, bytes)
if _, err := rand.Read(value); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(value), nil
}
// derivePassword implements PBKDF2-HMAC-SHA256 without adding a runtime
// dependency to the family MVP binary.
func derivePassword(password, salt []byte, iterations int) []byte {
const outputLength = 32
result := make([]byte, 0, outputLength)
for block := uint32(1); len(result) < outputLength; block++ {
counter := []byte{byte(block >> 24), byte(block >> 16), byte(block >> 8), byte(block)}
mac := hmac.New(sha256.New, password)
mac.Write(salt)
mac.Write(counter)
u := mac.Sum(nil)
t := append([]byte(nil), u...)
for round := 1; round < iterations; round++ {
mac = hmac.New(sha256.New, password)
mac.Write(u)
u = mac.Sum(nil)
for index := range t {
t[index] ^= u[index]
}
}
result = append(result, t...)
}
return result[:outputLength]
}
// SortedAnswerIDs supports stable exports without exposing password material.
func SortedAnswerIDs(user User) []string {
ids := make([]string, 0, len(user.Answers))
for id := range user.Answers {
ids = append(ids, id)
}
sort.Strings(ids)
return ids
}