From 3389ea3d2cb82d75b51b3b426afc54e974868e6e Mon Sep 17 00:00:00 2001 From: "juvenal.diaz" Date: Sat, 5 Dec 2026 10:20:42 -0600 Subject: [PATCH] Add private NextPath account store --- cmd/nextpath/internal/account/store.go | 335 ++++++++++++++++++++ cmd/nextpath/internal/account/store_test.go | 107 +++++++ 2 files changed, 442 insertions(+) create mode 100644 cmd/nextpath/internal/account/store.go create mode 100644 cmd/nextpath/internal/account/store_test.go diff --git a/cmd/nextpath/internal/account/store.go b/cmd/nextpath/internal/account/store.go new file mode 100644 index 0000000..98ccd20 --- /dev/null +++ b/cmd/nextpath/internal/account/store.go @@ -0,0 +1,335 @@ +// 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 +} diff --git a/cmd/nextpath/internal/account/store_test.go b/cmd/nextpath/internal/account/store_test.go new file mode 100644 index 0000000..6feb4d4 --- /dev/null +++ b/cmd/nextpath/internal/account/store_test.go @@ -0,0 +1,107 @@ +package account + +import ( + "encoding/json" + "errors" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestRegistrationAuthenticationPersistenceAndDeletion(t *testing.T) { + path := filepath.Join(t.TempDir(), "private", "accounts.json") + store, err := Open(path, 10) + if err != nil { + t.Fatal(err) + } + registered, err := store.Register(RegisterInput{ + Email: " Explorer@Example.Test ", + DisplayName: "Explorer", + AgeBand: "18-24", + ZIPCode: "85001", + Password: "a sufficiently long password", + Consent: true, + }) + if err != nil { + t.Fatal(err) + } + if registered.Email != "explorer@example.test" { + t.Fatalf("normalized email = %q", registered.Email) + } + if _, ok := store.Authenticate(registered.Email, "wrong password"); ok { + t.Fatal("wrong password authenticated") + } + if _, ok := store.Authenticate(registered.Email, "a sufficiently long password"); !ok { + t.Fatal("valid password did not authenticate") + } + + updated, err := store.SaveAnswers(registered.ID, "bank-v1", map[string]int{"r01": 5}) + if err != nil { + t.Fatal(err) + } + updated.Answers["r01"] = 1 + stored, err := store.Get(registered.ID) + if err != nil { + t.Fatal(err) + } + if stored.Answers["r01"] != 5 { + t.Fatal("caller mutated persisted answers") + } + + reopened, err := Open(path, 10) + if err != nil { + t.Fatal(err) + } + if _, ok := reopened.Authenticate(registered.Email, "a sufficiently long password"); !ok { + t.Fatal("persisted account did not authenticate") + } + data, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(data), "a sufficiently long password") { + t.Fatal("account store contains plaintext password") + } + var decoded map[string]any + if err := json.Unmarshal(data, &decoded); err != nil { + t.Fatalf("account store is not valid JSON: %v", err) + } + + if err := reopened.Delete(registered.ID); err != nil { + t.Fatal(err) + } + if _, err := reopened.Get(registered.ID); !errors.Is(err, ErrNotFound) { + t.Fatalf("Get after delete error = %v, want ErrNotFound", err) + } +} + +func TestRegistrationValidationAndDuplicateEmail(t *testing.T) { + store, err := Open(filepath.Join(t.TempDir(), "accounts.json"), 2) + if err != nil { + t.Fatal(err) + } + valid := RegisterInput{ + Email: "person@example.test", DisplayName: "Person", AgeBand: "25-39", + ZIPCode: "85701", Password: "long enough password", Consent: true, + } + if _, err := store.Register(valid); err != nil { + t.Fatal(err) + } + if _, err := store.Register(valid); !errors.Is(err, ErrDuplicateEmail) { + t.Fatalf("duplicate error = %v, want ErrDuplicateEmail", err) + } + + cases := []RegisterInput{ + {Email: "bad", DisplayName: "Person", AgeBand: "25-39", ZIPCode: "85701", Password: "long enough password", Consent: true}, + {Email: "a@example.test", DisplayName: "Person", AgeBand: "unknown", ZIPCode: "85701", Password: "long enough password", Consent: true}, + {Email: "a@example.test", DisplayName: "Person", AgeBand: "25-39", ZIPCode: "10001", Password: "long enough password", Consent: true}, + {Email: "a@example.test", DisplayName: "Person", AgeBand: "25-39", ZIPCode: "85701", Password: "short", Consent: true}, + {Email: "a@example.test", DisplayName: "Person", AgeBand: "25-39", ZIPCode: "85701", Password: "long enough password", Consent: false}, + } + for index, input := range cases { + if _, err := store.Register(input); err == nil { + t.Fatalf("invalid case %d was accepted", index) + } + } +}