Contract step of the account-phone-login expand-migrate-contract rollout. Phone is now the sole account identifier end to end: - domain.UserRecord/CreateUserInput: delete Email, drop Phone's omitempty (required going forward). - store: delete email_unique Mongo index; phone_unique is now non-sparse (unique, not sparse) since every account creation path requires a phone. Delete FindUserByEmail, ensureUserEmailAvailableLocked, and ErrDuplicateUserEmail (confirmed dead via grep - all real call sites were already migrated to the *Phone equivalents by tickets 01-03). Mongo duplicate-key fallback and the account-mutation-guard's stale-write snapshot/filter now key off Phone instead of Email. - api: drop the now-impossible ErrDuplicateUserEmail branch in renderUserMutationError. The account-hierarchy audit endpoint and the supplier-deletion receipt struct both switch their identifying field from Email to Phone, since both are populated fresh from current account state (not frozen historical snapshots) - continuing to read a "email" key would silently go blank for every account created after this change. - frontend: src/types.ts User.phone is now required (email removed); AccountHierarchyIssue.email -> .phone in services/api/users.ts and pages/Users.tsx to match the backend audit endpoint's renamed field. - Rewrote the wide blast radius of Go test fixtures that constructed users by email across internal/api/*_test.go and internal/store/*_test.go, including the two dedicated memory-store uniqueness tests (merged into phone-only equivalents) and several opt-in "live" acceptance-fixture tests gated behind env vars for real Fanyu deployments. Repo-wide grep of Go and TS/TSX for Email/email/邮箱 turned up no remaining account-identifier references outside of a few harmless test-only cosmetic labels (e.g. "Email Tenant" as an org display name in a seed helper) and assertions that explicitly check "邮箱" text is absent from API responses. go build/vet clean. go test ./internal/api/... ./internal/store/... ./internal/domain/... : 75 failures, identical test names to the pre-ticket-05 baseline (diffed against a throwaway worktree at the prior tip). npm run lint:web (tsc --noEmit) clean. npm run test:frontend: 599/586/13, matching the stated baseline exactly. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
161 lines
6.5 KiB
Go
161 lines
6.5 KiB
Go
package api
|
|
|
|
import (
|
|
"context"
|
|
"droboticflow/internal/domain"
|
|
"droboticflow/internal/store"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"go.mongodb.org/mongo-driver/mongo"
|
|
"go.mongodb.org/mongo-driver/mongo/options"
|
|
"net/http"
|
|
"os"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
func accountDeleteContract(t *testing.T, ds store.Store) {
|
|
t.Helper()
|
|
t.Setenv("DROBOTICFLOW_REQUIRE_SESSION_AUTH", "true")
|
|
h := NewHandler(ds, nil)
|
|
root := bootstrapSuperAdminSession(t, h)
|
|
org := adminCreateOrganization(t, h, root, "Account deletion", "account-deletion")
|
|
admin := adminCreateUser(t, h, root, org.ID, "Admin", "delete-admin@example.invalid", domain.UserRoleAdmin, "delete-test-password")
|
|
supplier, e := ds.EnsureDefaultSupplier(t.Context(), org.ID)
|
|
if e != nil {
|
|
t.Fatal(e)
|
|
}
|
|
victim := adminCreateUser(t, h, root, org.ID, "Deleted identity", "delete-worker@example.invalid", domain.UserRoleAnnotator, "delete-test-password", supplier.ID)
|
|
disabled := adminCreateUser(t, h, root, org.ID, "Only disabled", "disabled-worker@example.invalid", domain.UserRoleAnnotator, "delete-test-password", supplier.ID)
|
|
ac := loginSession(t, h, admin.Phone, "delete-test-password")
|
|
vc := loginSession(t, h, victim.Phone, "delete-test-password")
|
|
must := func(e error) {
|
|
t.Helper()
|
|
if e != nil {
|
|
t.Fatal(e)
|
|
}
|
|
}
|
|
must(ds.UpsertProject(t.Context(), domain.ProjectRecord{ID: "delete-project", OrganizationID: org.ID, Name: "Shared project", Status: domain.ProjectStatusActive}))
|
|
must(ds.UpsertProjectMember(t.Context(), domain.ProjectMemberRecord{ID: "delete-member", OrganizationID: org.ID, ProjectID: "delete-project", UserID: victim.ID, SupplierID: supplier.ID, Roles: domain.AccountProductionRoles(victim)}))
|
|
for _, status := range []domain.HumanItemStatus{domain.HumanItemInProgress, domain.HumanItemAccepted} {
|
|
must(ds.UpsertHumanItem(t.Context(), domain.HumanItemRecord{ID: "delete-" + string(status), OrganizationID: org.ID, AssignedUserID: victim.ID, Status: status, Version: 1, Subject: domain.HumanSubjectRef{ItemKey: string(status)}}))
|
|
}
|
|
r := serveJSONWithCookie(h, "PUT", "/api/users/"+disabled.ID, []byte(`{"status":"disabled"}`), ac)
|
|
if r.Code != 200 {
|
|
t.Fatal(r.Code, r.Body.String())
|
|
}
|
|
r = serveJSONWithCookie(h, "DELETE", "/api/users/"+victim.ID, nil, ac)
|
|
if r.Code != 204 {
|
|
t.Fatal(r.Code, r.Body.String())
|
|
}
|
|
saved, e := ds.GetUser(t.Context(), victim.ID)
|
|
must(e)
|
|
if saved == nil || saved.DeletedAt == "" || saved.PasswordHash != "" || saved.DeletedBy != admin.ID || saved.Status != domain.UserStatusDisabled || saved.Name != victim.Name || saved.Phone != victim.Phone {
|
|
t.Fatalf("audit deletion not finalized: %+v", saved)
|
|
}
|
|
r = serveJSONWithCookie(h, "GET", "/api/users?includeDisabled=true", nil, ac)
|
|
var list struct {
|
|
Items []domain.UserRecord `json:"items"`
|
|
}
|
|
must(json.Unmarshal(r.Body.Bytes(), &list))
|
|
foundDisabled := false
|
|
for _, u := range list.Items {
|
|
if u.ID == victim.ID {
|
|
t.Fatal("deleted identity reappeared in full directory")
|
|
}
|
|
if u.ID == disabled.ID {
|
|
foundDisabled = true
|
|
}
|
|
}
|
|
if !foundDisabled {
|
|
t.Fatal("merely disabled account was hidden")
|
|
}
|
|
members, e := ds.ListProjectMembers(t.Context(), org.ID, "")
|
|
must(e)
|
|
for _, m := range members {
|
|
if m.UserID == victim.ID {
|
|
t.Fatal("project member survived")
|
|
}
|
|
}
|
|
pending, e := ds.GetHumanItem(t.Context(), "delete-"+string(domain.HumanItemInProgress))
|
|
must(e)
|
|
done, e := ds.GetHumanItem(t.Context(), "delete-"+string(domain.HumanItemAccepted))
|
|
must(e)
|
|
if pending.AssignedUserID != "" || pending.Status != domain.HumanItemReady || done.AssignedUserID != victim.ID {
|
|
t.Fatal("pending release/history preservation failed")
|
|
}
|
|
if r = serveJSONWithCookie(h, "GET", "/api/auth/me", nil, vc); r.Code != 401 {
|
|
t.Fatal("deleted session survived")
|
|
}
|
|
if r = serveJSONWithCookie(h, "PUT", "/api/users/"+victim.ID, []byte(`{"status":"active"}`), ac); r.Code != 410 {
|
|
t.Fatalf("reactivation admitted: %d %s", r.Code, r.Body.String())
|
|
}
|
|
if e = ds.UpsertUser(t.Context(), victim); !errors.Is(e, store.ErrAccountDeleted) {
|
|
t.Fatalf("stale writer resurrected account: %v", e)
|
|
}
|
|
if r = serveJSONWithCookie(h, "DELETE", "/api/users/"+victim.ID, nil, ac); r.Code != 204 {
|
|
t.Fatal("repeat delete not idempotent")
|
|
}
|
|
again, e := ds.GetUser(t.Context(), victim.ID)
|
|
must(e)
|
|
if again.DeletedAt != saved.DeletedAt {
|
|
t.Fatal("repeat deletion rewrote audit")
|
|
}
|
|
}
|
|
func TestAccountDeleteDirectoryAndAudit(t *testing.T) {
|
|
accountDeleteContract(t, store.NewMemoryStore())
|
|
}
|
|
func TestAccountDeleteMongoDirectoryAndAudit(t *testing.T) {
|
|
if os.Getenv("ACCOUNT_DELETE_MONGO_TEST") != "1" {
|
|
t.Skip("isolated local Mongo")
|
|
}
|
|
ctx, cancel := context.WithTimeout(t.Context(), 30*time.Second)
|
|
defer cancel()
|
|
c, e := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://127.0.0.1:27029/?directConnection=true"))
|
|
if e != nil {
|
|
t.Fatal(e)
|
|
}
|
|
defer c.Disconnect(context.Background())
|
|
db := c.Database(fmt.Sprintf("account_delete_test_%d", time.Now().UnixNano()))
|
|
defer db.Drop(context.Background())
|
|
accountDeleteContract(t, store.NewMongoStore(db))
|
|
}
|
|
|
|
// A partial failure must remain visible/retryable, not be labelled deleted.
|
|
type failedAccountReleaseStore struct {
|
|
store.Store
|
|
fail bool
|
|
}
|
|
|
|
func (s *failedAccountReleaseStore) ListHumanItems(ctx context.Context, org string, q domain.HumanItemQuery) ([]domain.HumanItemRecord, error) {
|
|
if s.fail {
|
|
return nil, errors.New("injected release failure")
|
|
}
|
|
return s.Store.ListHumanItems(ctx, org, q)
|
|
}
|
|
func TestAccountDeleteFailureCanBeRetried(t *testing.T) {
|
|
t.Setenv("DROBOTICFLOW_REQUIRE_SESSION_AUTH", "true")
|
|
ds := &failedAccountReleaseStore{Store: store.NewMemoryStore()}
|
|
h := NewHandler(ds, nil)
|
|
root := bootstrapSuperAdminSession(t, h)
|
|
org := adminCreateOrganization(t, h, root, "Retry deletion", "retry-deletion")
|
|
admin := adminCreateUser(t, h, root, org.ID, "Admin", "retry-admin@example.invalid", domain.UserRoleAdmin, "test-password")
|
|
worker := adminCreateUser(t, h, root, org.ID, "Worker", "retry-worker@example.invalid", domain.UserRoleAnnotator, "test-password")
|
|
cookie := loginSession(t, h, admin.Phone, "test-password")
|
|
ds.fail = true
|
|
r := serveJSONWithCookie(h, http.MethodDelete, "/api/users/"+worker.ID, nil, cookie)
|
|
if r.Code != 500 {
|
|
t.Fatal(r.Code)
|
|
}
|
|
user, e := ds.GetUser(t.Context(), worker.ID)
|
|
if e != nil || user == nil || user.DeletedAt != "" || user.Status != domain.UserStatusDisabled {
|
|
t.Fatal("failed cleanup incorrectly finalized deletion")
|
|
}
|
|
ds.fail = false
|
|
r = serveJSONWithCookie(h, http.MethodDelete, "/api/users/"+worker.ID, nil, cookie)
|
|
if r.Code != 204 {
|
|
t.Fatal(r.Code, r.Body.String())
|
|
}
|
|
}
|