Files
iam/normalize_test.go
zeekay 4d3861ad98 store: an email address is one value, on both sides of the comparison
Signup lowered the address on the way in (signup.go) and GetUserByEmail compared
the raw spelling on the way out, so anyone who capitalized a letter of their own
address created an account they could never sign into — including through the
auto-login that runs one request later, which answered "the username or password
is incorrect" for the password they had just chosen. Indistinguishable from a
typo, so undiscoverable, and permanent.

Phone already had the cure and its own comment states the rule: applying the
normalizer on only one side "would be a lookup that silently never matches".
NormalizeEmail is that rule for the other identifier — defined beside
NormalizePhone, applied inside the READ, and applied at the one WRITE every
create/update path reaches (users.Create/Update, plus bootstrap, which writes
around it and already states the username rule itself for the same reason). The
four inline ToLower+TrimSpace at the write sites become one call, so there is
nowhere left for the two sides to disagree.

GetUserByEmail also stops picking between rows. The document store hangs no
per-field UNIQUE constraint, so two rows in one org can hold one address — three
already do — and .First() with no ORDER BY handed back whichever the index
yielded, for the caller to authenticate somebody against. An address that names
two accounts names none: ErrEmailAmbiguous, exactly as ErrPhoneAmbiguous. Signup
reads that as "email already exists", which is what it means there.

`iam phones` becomes `iam normalize` and converts both identifiers in one pass.
One rule — an identifier is stored in the form it is compared in — so one command;
a second would be a second place to forget it.
2026-08-07 22:19:47 -07:00

164 lines
5.4 KiB
Go

// Copyright 2026 Hanzo AI, Inc.
// SPDX-License-Identifier: MIT OR Apache-2.0
package main
import (
"bytes"
"context"
"path/filepath"
"strings"
"testing"
"github.com/hanzoai/orm"
"github.com/spf13/cobra"
"github.com/hanzoai/iam/pkg/schema"
"github.com/hanzoai/iam/pkg/store"
"github.com/hanzoai/iam/server"
)
// seedUser writes a row the way the legacy write sites did — straight through orm,
// around users.Create — which is exactly how a non-canonical identifier got into
// the table in the first place.
func seedUser(t *testing.T, db orm.DB, owner, name, phone, email string) {
t.Helper()
row := orm.New[schema.User](db)
model := row.Model
row.Owner, row.Name, row.Phone, row.Email = owner, name, phone, email
row.Model = model
row.SetId(owner + "/" + name)
if err := row.CreateCtx(context.Background()); err != nil {
t.Fatalf("seed %s/%s: %v", owner, name, err)
}
}
func storedUser(t *testing.T, db orm.DB, owner, name string) *schema.User {
t.Helper()
u, err := store.GetUserByName(context.Background(), db, owner, name)
if err != nil || u == nil {
t.Fatalf("read %s/%s: %v", owner, name, err)
}
return u
}
func backfillDB(t *testing.T) orm.DB {
t.Helper()
sdb, err := server.OpenSQLite(filepath.Join(t.TempDir(), "backfill.db"))
if err != nil {
t.Fatalf("open sqlite: %v", err)
}
t.Cleanup(func() { _ = sdb.Close() })
return sdb
}
func run(t *testing.T, db orm.DB, apply bool) string {
t.Helper()
cmd := &cobra.Command{}
var out bytes.Buffer
cmd.SetOut(&out)
if err := normalizeIdentifiers(context.Background(), cmd, db, apply); err != nil {
t.Fatalf("normalizeIdentifiers(apply=%v): %v", apply, err)
}
return out.String()
}
// The default posture REPORTS and writes nothing. This is the property that makes
// the count trustworthy before anyone points it at a production user table.
func TestBackfillDryRunWritesNothing(t *testing.T) {
db := backfillDB(t)
seedUser(t, db, "hanzo", "ada", "+1 (415) 555-0134", "")
out := run(t, db, false)
if got := storedUser(t, db, "hanzo", "ada").Phone; got != "+1 (415) 555-0134" {
t.Fatalf("dry run mutated the row: %q", got)
}
if !strings.Contains(out, "would convert 1") {
t.Errorf("report did not state the pending change:\n%s", out)
}
if !strings.Contains(out, "--apply") {
t.Errorf("report did not say how to perform it:\n%s", out)
}
}
// With --apply the row becomes exactly what the sign-in lookup compares against.
func TestBackfillApplyCanonicalizes(t *testing.T) {
db := backfillDB(t)
seedUser(t, db, "hanzo", "ada", "+1 (415) 555-0134", "")
seedUser(t, db, "hanzo", "grace", "415-555-0199", "")
run(t, db, true)
if got := storedUser(t, db, "hanzo", "ada").Phone; got != "+14155550134" {
t.Errorf("ada = %q, want the canonical form", got)
}
if got := storedUser(t, db, "hanzo", "grace").Phone; got != "4155550199" {
t.Errorf("grace = %q, want the canonical form", got)
}
// The converted row is now reachable by the lookup sign-in actually uses —
// the point of the whole exercise.
u, err := store.GetUserByPhone(context.Background(), db, "hanzo", "+1 415 555 0134")
if err != nil || u == nil || u.Name != "ada" {
t.Fatalf("converted row not reachable by sign-in lookup: %v %v", u, err)
}
}
// An ADDRESS is the other sign-in identifier, and it is converted in the same
// pass by the same rule: a row stored in mixed case is unreachable by the lookup
// login uses, which is a person who cannot sign in by their own address.
func TestBackfillCanonicalizesEmail(t *testing.T) {
db := backfillDB(t)
seedUser(t, db, "hanzo", "ada", "", " [email protected] ")
// Before: the stored spelling is not the compared spelling, so nothing matches.
if u, err := store.GetUserByEmail(context.Background(), db, "hanzo", "[email protected]"); err != nil || u != nil {
t.Fatalf("a non-canonical row was reachable before conversion: %v %v", u, err)
}
out := run(t, db, true)
if got := storedUser(t, db, "hanzo", "ada").Email; got != "[email protected]" {
t.Errorf("ada email = %q, want the canonical form", got)
}
if !strings.Contains(out, "email") {
t.Errorf("report did not name the address it converted:\n%s", out)
}
u, err := store.GetUserByEmail(context.Background(), db, "hanzo", "[email protected]")
if err != nil || u == nil || u.Name != "ada" {
t.Fatalf("converted row not reachable by sign-in lookup: %v %v", u, err)
}
}
// Re-running is a no-op. The normalizers are idempotent, so a second pass must
// report zero rather than rewrite the table again.
func TestBackfillIsSafeToRerun(t *testing.T) {
db := backfillDB(t)
seedUser(t, db, "hanzo", "ada", "+1 (415) 555-0134", "[email protected]")
run(t, db, true)
out := run(t, db, true)
if !strings.Contains(out, "converted 0") {
t.Errorf("a second pass was not a no-op:\n%s", out)
}
}
// A value with no digits is LEFT ALONE. Blanking it would destroy the original
// and put nothing usable in its place; a human should look at those.
func TestBackfillLeavesUnusableValuesIntact(t *testing.T) {
db := backfillDB(t)
seedUser(t, db, "hanzo", "ada", "n/a", "")
seedUser(t, db, "hanzo", "grace", "", "")
out := run(t, db, true)
if got := storedUser(t, db, "hanzo", "ada").Phone; got != "n/a" {
t.Errorf("unusable value was rewritten to %q", got)
}
if !strings.Contains(out, "no digits") {
t.Errorf("report did not flag the unusable row:\n%s", out)
}
if got := storedUser(t, db, "hanzo", "grace").Phone; got != "" {
t.Errorf("empty phone became %q", got)
}
}