fix(signup): reject an email that already has an account (#37)
ci / shared (push) Successful in 12s
ci / test (push) Successful in 23m29s
ci / image (push) Successful in 32s

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
This commit was merged in pull request #37.
This commit is contained in:
sharangandClaude Opus 5.5 committed 2026-09-23 22:09:00 +00:00
1 parent 25419c48b3
commit 0a26331ffd
7 files changed
+97

No files matched your search

+4
View File
@@ -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).
+29
View File
@@ -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")
}
}
+8
View File
@@ -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()
+11
View File
@@ -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")
}
}
+13
View File
@@ -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)
+20
View File
@@ -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)
}
})
}
+12
View File
@@ -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)),