From 51ecb9d94a61f96478ffc9181daf50b3519dae70 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Thu, 24 Sep 2026 12:20:17 +0200 Subject: [PATCH] fix(signup): report when Keycloak refuses to send the invitation CreateOrgAndInvite swallowed a failed execute-actions-email and the registry audited keycloak.invite_sent anyway. On production the invite client did not allow the /start redirect, Keycloak answered 400, and nobody could tell. The result now carries MailError (with Keycloak's answer), the registry logs it and audits keycloak.invite_mail_failed. 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 | 20 ++++++++++++++++++++ internal/keycloak/mock.go | 2 ++ internal/keycloak/orgs.go | 7 ++++--- internal/server/keycloak.go | 22 +++++++++++++++++----- internal/server/keycloak_test.go | 24 ++++++++++++++++++++++++ internal/server/tenants.go | 10 ++++++++-- 7 files changed, 79 insertions(+), 10 deletions(-) diff --git a/internal/keycloak/adapter.go b/internal/keycloak/adapter.go index d1fb9b9..58fd314 100644 --- a/internal/keycloak/adapter.go +++ b/internal/keycloak/adapter.go @@ -50,6 +50,10 @@ type InviteResult struct { // Stalwart yet) we surface it in the response so testers can use it // directly. In prod it's emailed by Keycloak and we discard it. InviteURL string + // MailError is set when the org and user exist but Keycloak refused to + // send the invitation (e.g. the redirect URI is not allowed for the + // invite client). The admin can resend once the cause is fixed. + MailError error } // OrgMember is one member of a tenant's Keycloak organization as the portal diff --git a/internal/keycloak/client_test.go b/internal/keycloak/client_test.go index 85235f9..2acaccb 100644 --- a/internal/keycloak/client_test.go +++ b/internal/keycloak/client_test.go @@ -29,6 +29,7 @@ type stubKC struct { lastOrgBody string tokenFails atomic.Bool // when true, /token returns 401 once + emailFails atomic.Bool // when true, execute-actions-email answers 400 } func newStubKC(t *testing.T) *stubKC { @@ -103,6 +104,10 @@ func newStubKC(t *testing.T) *stubKC { mux.HandleFunc("/admin/realms/test-realm/users/user-abc/execute-actions-email", func(w http.ResponseWriter, r *http.Request) { s.emailCalls.Add(1) + if s.emailFails.Load() { + http.Error(w, `{"errorMessage":"Invalid redirect uri."}`, http.StatusBadRequest) + return + } w.WriteHeader(http.StatusNoContent) }) @@ -303,3 +308,18 @@ func TestHTTPAdapter_userExists(t *testing.T) { t.Error("lookup failure not reported") } } + +func TestHTTPAdapter_inviteMailRefused(t *testing.T) { + s := newStubKC(t) + defer s.close() + s.emailFails.Store(true) + res, err := newTestAdapter(s.srv).CreateOrgAndInvite(context.Background(), InviteInput{ + TenantID: "t1", Slug: "acme", Name: "Acme", AdminEmail: "it@acme.test", + }) + if err != nil { + t.Fatalf("provisioning must still succeed: %v", err) + } + if res.UserID != "user-abc" || res.MailError == nil || !strings.Contains(res.MailError.Error(), "Invalid redirect uri") { + t.Fatalf("result = %+v", res) + } +} diff --git a/internal/keycloak/mock.go b/internal/keycloak/mock.go index 39ee40b..a92eb6d 100644 --- a/internal/keycloak/mock.go +++ b/internal/keycloak/mock.go @@ -18,6 +18,7 @@ type Mock struct { Claims map[string]Claims // userID → last synced Status map[string]string // tenant slug → last synced tenant_status FailNext error // set to force the next call to fail + FailMail error // set to make CreateOrgAndInvite report an unsent invitation // Members is the org membership per tenant slug. A slug with no entry // has no organization (ListOrgMembers/InviteMember → ErrOrgNotFound); @@ -153,6 +154,7 @@ func (m *Mock) CreateOrgAndInvite(_ context.Context, in InviteInput) (*InviteRes OrganizationID: orgID, UserID: userID, InviteURL: "http://mock-keycloak/invite/" + userID, + MailError: m.FailMail, }, nil } diff --git a/internal/keycloak/orgs.go b/internal/keycloak/orgs.go index 4ff1271..421b0c1 100644 --- a/internal/keycloak/orgs.go +++ b/internal/keycloak/orgs.go @@ -164,8 +164,8 @@ func (a *HTTPAdapter) CreateOrgAndInvite(ctx context.Context, in InviteInput) (* []string{"VERIFY_EMAIL", "UPDATE_PASSWORD"}, a.cfg.InviteRedirectURI) if err != nil { - // Non-fatal — admin can resend from the KC UI. - return &InviteResult{OrganizationID: orgID, UserID: userID, InviteURL: ""}, nil + // Non-fatal: the account exists, the mail can be resent. + return &InviteResult{OrganizationID: orgID, UserID: userID, MailError: err}, nil } return &InviteResult{OrganizationID: orgID, UserID: userID, InviteURL: inviteURL}, nil @@ -305,7 +305,8 @@ func (a *HTTPAdapter) executeActionsEmail(ctx context.Context, userID string, ac } defer func() { _ = resp.Body.Close() }() if resp.StatusCode/100 != 2 { - return "", fmt.Errorf("execute-actions: %d", resp.StatusCode) + body, _ := io.ReadAll(io.LimitReader(resp.Body, 512)) + return "", fmt.Errorf("execute-actions: %d %s", resp.StatusCode, strings.TrimSpace(string(body))) } // KC doesn't return the action-token URL via this endpoint — it sends // the email. For dev we surface an admin-portal pointer so the tester diff --git a/internal/server/keycloak.go b/internal/server/keycloak.go index 1086243..ada4b5e 100644 --- a/internal/server/keycloak.go +++ b/internal/server/keycloak.go @@ -15,12 +15,20 @@ import ( // audit_log captures the error so the operator can heal it later // (resending the invite is a one-click in the KC admin UI). // -// Returns the InviteURL so the API response can surface it for dev. -func (s *Server) provisionKeycloak(ctx context.Context, t *store.Tenant, adminEmail, adminName string) (string, error) { +// Returns the InviteURL so the API response can surface it for dev, the +// provisioning error, and separately a failure to send the invitation mail. +// kcInvite is the outcome of a successful provisioning: the dev invite URL +// and, separately, a failure to send the invitation mail. +type kcInvite struct { + URL string + MailErr error +} + +func (s *Server) provisionKeycloak(ctx context.Context, t *store.Tenant, adminEmail, adminName string) (kcInvite, error) { if adminEmail == "" { // Skip silently — caller chose not to invite anyone yet (sales-led // flow, demo tenant, test fixture, etc.). - return "", nil + return kcInvite{}, nil } res, err := s.Keycloak.CreateOrgAndInvite(ctx, keycloak.InviteInput{ TenantID: t.ID, @@ -32,11 +40,15 @@ func (s *Server) provisionKeycloak(ctx context.Context, t *store.Tenant, adminEm if err != nil { s.Log.Error("keycloak provision failed", "tenant_id", t.ID, "slug", t.Slug, "err", err) - return "", err + return kcInvite{}, err } s.Log.Info("keycloak provisioned", "tenant_id", t.ID, "kc_org_id", res.OrganizationID, "kc_user_id", res.UserID) - return res.InviteURL, nil + if res.MailError != nil { + s.Log.Error("keycloak invitation mail not sent", + "tenant_id", t.ID, "slug", t.Slug, "err", res.MailError) + } + return kcInvite{URL: res.InviteURL, MailErr: res.MailError}, nil } // kcClaims is POST /v1/internal/keycloak/claims. Called by Keycloak's diff --git a/internal/server/keycloak_test.go b/internal/server/keycloak_test.go index a1e5434..17264d8 100644 --- a/internal/server/keycloak_test.go +++ b/internal/server/keycloak_test.go @@ -1,6 +1,7 @@ package server_test import ( + "errors" "net/http" "strings" "testing" @@ -165,3 +166,26 @@ func TestCreateTenant_emailTaken(t *testing.T) { } }) } + +func TestCreateTenant_inviteMailFailure_isAudited(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + h.kcMock.FailMail = errors.New("execute-actions: 400 invalid redirect uri") + resp, body := h.do("POST", "/v1/tenants", map[string]any{ + "slug": "mailfail-co", "name": "Mailfail Co.", "admin_email": "it@mailfail.test", + }) + if resp.StatusCode != http.StatusCreated { + t.Fatalf("status = %d, body=%s", resp.StatusCode, body) + } + id := decode[struct { + Tenant *store.Tenant `json:"tenant"` + }](t, body).Tenant.ID + for action, want := range map[string]int{"keycloak.invite_mail_failed": 1, "keycloak.invite_sent": 0} { + _, body := h.do("GET", "/v1/audit?action="+action+"&tenant_id="+id, nil) + if got := len(decode[struct { + Items []store.AuditEvent `json:"items"` + }](t, body).Items); got != want { + t.Errorf("%s: %d events, want %d", action, got, want) + } + } + }) +} diff --git a/internal/server/tenants.go b/internal/server/tenants.go index 1aba5d9..f089eac 100644 --- a/internal/server/tenants.go +++ b/internal/server/tenants.go @@ -109,13 +109,19 @@ func (s *Server) createTenant(w http.ResponseWriter, r *http.Request) { // Best-effort Keycloak provisioning. A failure here doesn't roll the // tenant back — the operator can resend the invite via the KC admin UI. // We emit an audit event regardless so the failure is traceable. - inviteURL, kcErr := s.provisionKeycloak(ctx, t, in.AdminEmail, in.AdminName) + invite, kcErr := s.provisionKeycloak(ctx, t, in.AdminEmail, in.AdminName) if kcErr != nil { s.emitAudit(ctx, r, store.AuditEvent{ TenantID: t.ID, Action: "keycloak.provision_failed", TargetID: t.ID, TargetType: "tenant", Metadata: map[string]interface{}{"err": kcErr.Error(), "admin_email": in.AdminEmail}, }) + } else if invite.MailErr != nil { + s.emitAudit(ctx, r, store.AuditEvent{ + TenantID: t.ID, Action: "keycloak.invite_mail_failed", + TargetID: in.AdminEmail, TargetType: "user", TargetName: in.AdminEmail, + Metadata: map[string]interface{}{"err": invite.MailErr.Error()}, + }) } else if in.AdminEmail != "" { s.emitAudit(ctx, r, store.AuditEvent{ TenantID: t.ID, Action: "keycloak.invite_sent", @@ -151,7 +157,7 @@ func (s *Server) createTenant(w http.ResponseWriter, r *http.Request) { s.EnqueueCustomerUpsert(ctx, t) } - writeJSON(w, http.StatusCreated, createTenantResp{Tenant: t, InviteURL: inviteURL}) + writeJSON(w, http.StatusCreated, createTenantResp{Tenant: t, InviteURL: invite.URL}) } func (s *Server) getTenant(w http.ResponseWriter, r *http.Request) {