From 1d7e839a80aa1b9e902d0db27ea2250c0b894f24 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Wed, 23 Sep 2026 23:31:36 +0200 Subject: [PATCH] fix(signup): reject an email that already has an account Signup created the tenant and the Keycloak organization before the admin user; when the email already existed, provisioning failed after the fact and left an admin-less workspace and an orphan organization, while the portal told the person to check their inbox. createTenant now asks Keycloak first and answers 409 email_taken without creating anything. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB --- internal/keycloak/adapter.go | 4 ++++ internal/keycloak/client_test.go | 29 +++++++++++++++++++++++++++++ internal/keycloak/mock.go | 8 ++++++++ internal/keycloak/mock_test.go | 11 +++++++++++ internal/keycloak/orgs.go | 13 +++++++++++++ internal/server/keycloak_test.go | 20 ++++++++++++++++++++ internal/server/tenants.go | 12 ++++++++++++ 7 files changed, 97 insertions(+) diff --git a/internal/keycloak/adapter.go b/internal/keycloak/adapter.go index 4287e8a..d1fb9b9 100644 --- a/internal/keycloak/adapter.go +++ b/internal/keycloak/adapter.go @@ -146,6 +146,10 @@ type Adapter interface { // the org is missing, ErrUserNotFound when email is not a member of it. ResendInvite(ctx context.Context, slug, email string) error + // UserExists reports whether the realm already has an account with this + // email. Signup checks it first: an address can belong to one workspace. + UserExists(ctx context.Context, email string) (bool, error) + // SyncTenantStatus writes the coarse tenant_status attribute on every // member of the organization whose alias is slug (ERP/02: Keycloak // carries only the coarse flag; entitlements stay in the registry). diff --git a/internal/keycloak/client_test.go b/internal/keycloak/client_test.go index aafe069..85235f9 100644 --- a/internal/keycloak/client_test.go +++ b/internal/keycloak/client_test.go @@ -274,3 +274,32 @@ func tokenOK(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") _, _ = w.Write([]byte(`{"access_token":"t","expires_in":60}`)) } + +func TestHTTPAdapter_userExists(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/realms/test-realm/protocol/openid-connect/token", tokenOK) + mux.HandleFunc("/admin/realms/test-realm/users", func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Query().Get("email") { + case "a@b.test": + _ = json.NewEncoder(w).Encode([]map[string]string{{"id": "u1", "email": "A@b.test"}}) + case "boom@b.test": + w.WriteHeader(http.StatusInternalServerError) + default: + _ = json.NewEncoder(w).Encode([]map[string]string{}) + } + }) + srv := httptest.NewServer(mux) + defer srv.Close() + a := newTestAdapter(srv) + ctx := context.Background() + + if ok, err := a.UserExists(ctx, "a@b.test"); err != nil || !ok { + t.Errorf("existing: %v %v", ok, err) + } + if ok, err := a.UserExists(ctx, "new@b.test"); err != nil || ok { + t.Errorf("new: %v %v", ok, err) + } + if _, err := a.UserExists(ctx, "boom@b.test"); err == nil { + t.Error("lookup failure not reported") + } +} diff --git a/internal/keycloak/mock.go b/internal/keycloak/mock.go index 585ff06..39ee40b 100644 --- a/internal/keycloak/mock.go +++ b/internal/keycloak/mock.go @@ -85,6 +85,14 @@ func (m *Mock) InviteMember(_ context.Context, in MemberInviteInput) (*MemberInv return &MemberInviteResult{UserID: userID, Status: InviteStatusInvited, Created: !created}, nil } +// UserExists implements Adapter. +func (m *Mock) UserExists(_ context.Context, email string) (bool, error) { + m.mu.Lock() + defer m.mu.Unlock() + _, ok := m.Users[email] + return ok, nil +} + func (m *Mock) ResendInvite(_ context.Context, slug, email string) error { m.mu.Lock() defer m.mu.Unlock() diff --git a/internal/keycloak/mock_test.go b/internal/keycloak/mock_test.go index a572c92..8ada25a 100644 --- a/internal/keycloak/mock_test.go +++ b/internal/keycloak/mock_test.go @@ -82,3 +82,14 @@ func TestMock_syncClaimsRequiresUserID(t *testing.T) { t.Error("expected error for empty user id") } } + +func TestMock_userExists(t *testing.T) { + m := NewMock() + m.Users["a@y.test"] = "u1" + if ok, _ := m.UserExists(context.Background(), "a@y.test"); !ok { + t.Error("existing user not found") + } + if ok, _ := m.UserExists(context.Background(), "b@y.test"); ok { + t.Error("unknown user found") + } +} diff --git a/internal/keycloak/orgs.go b/internal/keycloak/orgs.go index 3c55527..4ff1271 100644 --- a/internal/keycloak/orgs.go +++ b/internal/keycloak/orgs.go @@ -258,6 +258,19 @@ func (a *HTTPAdapter) orgIDFrom(ctx context.Context, query, alias string) (strin // findUserByEmail so callers can create the user on a miss only. var errUserLookupMiss = errors.New("user not found") +// UserExists implements Adapter. +func (a *HTTPAdapter) UserExists(ctx context.Context, email string) (bool, error) { + _, err := a.findUserByEmail(ctx, email) + switch { + case err == nil: + return true, nil + case errors.Is(err, errUserLookupMiss): + return false, nil + default: + return false, err + } +} + func (a *HTTPAdapter) findUserByEmail(ctx context.Context, email string) (string, error) { resp, err := a.adminCall(ctx, http.MethodGet, fmt.Sprintf("/users?email=%s&exact=true", url.QueryEscape(email)), nil, nil) diff --git a/internal/server/keycloak_test.go b/internal/server/keycloak_test.go index c313d5d..a1e5434 100644 --- a/internal/server/keycloak_test.go +++ b/internal/server/keycloak_test.go @@ -2,6 +2,7 @@ package server_test import ( "net/http" + "strings" "testing" "git.breakpilot.com/platform/tenant-registry/internal/keycloak" @@ -145,3 +146,22 @@ func TestKcClaims_requiresInput(t *testing.T) { } }) } + +func TestCreateTenant_emailTaken(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + h.kcMock.Users["taken@kc-co.test"] = "u-existing" + resp, body := h.do("POST", "/v1/tenants", map[string]any{ + "slug": "taken-co", "name": "Taken Co.", "admin_email": " Taken@kc-co.test ", + }) + if resp.StatusCode != http.StatusConflict || !strings.Contains(string(body), "email_taken") { + t.Fatalf("status = %d, body=%s", resp.StatusCode, body) + } + // Nothing was created: the slug is still free. + if resp, _ := h.do("GET", "/v1/tenants/by-slug/taken-co", nil); resp.StatusCode != http.StatusNotFound { + t.Fatalf("tenant was created: %d", resp.StatusCode) + } + if len(h.kcMock.Orgs) != 0 { + t.Fatalf("org created: %v", h.kcMock.Orgs) + } + }) +} diff --git a/internal/server/tenants.go b/internal/server/tenants.go index 76432e4..1aba5d9 100644 --- a/internal/server/tenants.go +++ b/internal/server/tenants.go @@ -72,6 +72,18 @@ func (s *Server) createTenant(w http.ResponseWriter, r *http.Request) { ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) defer cancel() + // An address with an account already belongs to a workspace (or to + // staff): reject before anything is created, so no admin-less tenant and + // no orphan organization are left behind. A lookup failure falls through + // to the best-effort provisioning below. + if email := strings.ToLower(strings.TrimSpace(in.AdminEmail)); email != "" && s.Keycloak != nil { + if taken, err := s.Keycloak.UserExists(ctx, email); err == nil && taken { + writeError(w, http.StatusConflict, "email_taken", "an account with this email already exists") + return + } else if err != nil { + s.Log.Warn("keycloak user lookup failed", "err", err) + } + } t, err := s.Store.CreateTenant(ctx, store.TenantCreate{ Slug: in.Slug, Name: in.Name, Plan: in.Plan, Kind: in.Kind, SalesOwner: in.SalesOwner, AdminEmail: strings.ToLower(strings.TrimSpace(in.AdminEmail)), -- 2.54.1