Keycloak 26 validates a user PUT against the declarative user profile and
clears email, firstName and lastName when the body leaves them out. The
registry wrote attributes with a body of only {attributes}, so every status
sync wiped the members' email addresses. Reprovision syncs the status right
after the invitation goes out; the action link then failed with "invalid
email address".
Attribute writes now read the full user, change the attributes in it and
write the whole representation back (SyncTenantStatus, ensureUserAttributes,
SyncClaims).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
210 lines
6.6 KiB
Go
210 lines
6.6 KiB
Go
package keycloak
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"log/slog"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
// memberRepresentation is the slice of KC 26's MemberRepresentation (a
|
|
// UserRepresentation plus membershipType) the portal needs. Attributes are
|
|
// present in the full representation; a nil map means KC answered with a
|
|
// brief representation and we fetch the user separately.
|
|
type memberRepresentation struct {
|
|
ID string `json:"id"`
|
|
Username string `json:"username"`
|
|
Email string `json:"email"`
|
|
FirstName string `json:"firstName"`
|
|
LastName string `json:"lastName"`
|
|
Enabled bool `json:"enabled"`
|
|
CreatedTimestamp int64 `json:"createdTimestamp"` // epoch millis
|
|
Attributes map[string][]string `json:"attributes"`
|
|
}
|
|
|
|
func (m memberRepresentation) toOrgMember() OrgMember {
|
|
var created *time.Time
|
|
if m.CreatedTimestamp > 0 {
|
|
t := time.UnixMilli(m.CreatedTimestamp).UTC()
|
|
created = &t
|
|
}
|
|
email := m.Email
|
|
if email == "" {
|
|
email = m.Username // registry-created users use the e-mail as username
|
|
}
|
|
return OrgMember{
|
|
UserID: m.ID,
|
|
Email: email,
|
|
FirstName: m.FirstName,
|
|
LastName: m.LastName,
|
|
OrgRoles: attrValues(m.Attributes, "org_roles"),
|
|
Enabled: m.Enabled,
|
|
CreatedAt: created,
|
|
}
|
|
}
|
|
|
|
// ListOrgMembers implements Adapter: GET /organizations/{id}/members for
|
|
// the org whose alias is slug.
|
|
func (a *HTTPAdapter) ListOrgMembers(ctx context.Context, slug string) ([]OrgMember, error) {
|
|
orgID, err := a.findOrgByAlias(ctx, slug)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
var members []memberRepresentation
|
|
resp, err := a.adminCall(ctx, http.MethodGet, fmt.Sprintf("/organizations/%s/members?max=500", orgID), nil, &members)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if resp.StatusCode/100 != 2 {
|
|
_ = resp.Body.Close()
|
|
return nil, fmt.Errorf("list members: %d", resp.StatusCode)
|
|
}
|
|
out := make([]OrgMember, 0, len(members))
|
|
for _, m := range members {
|
|
if m.Attributes == nil {
|
|
// Brief representation: attributes (org_roles) live on the user.
|
|
var u memberRepresentation
|
|
resp, err := a.adminCall(ctx, http.MethodGet, "/users/"+m.ID, nil, &u)
|
|
if err == nil && resp.StatusCode/100 == 2 {
|
|
m.Attributes = u.Attributes
|
|
} else if err == nil {
|
|
_ = resp.Body.Close()
|
|
}
|
|
}
|
|
out = append(out, m.toOrgMember())
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// InviteMember implements Adapter. Steps mirror CreateOrgAndInvite minus the
|
|
// org creation: find user by e-mail (create if missing, with the same
|
|
// tenant-context attributes the admin path writes), add as org member (KC 26:
|
|
// bare user id string body; 409 = already a member), then execute-actions
|
|
// e-mail. Best-effort atomicity, same as the admin path.
|
|
func (a *HTTPAdapter) InviteMember(ctx context.Context, in MemberInviteInput) (*MemberInviteResult, error) {
|
|
if in.Email == "" {
|
|
return nil, fmt.Errorf("keycloak: member email required")
|
|
}
|
|
orgID, err := a.findOrgByAlias(ctx, in.Slug)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
attrs := map[string][]string{
|
|
"tenant_id": {in.TenantID},
|
|
"tenant_slug": {in.Slug},
|
|
"org_roles": {in.Role},
|
|
"tenant_status": {in.TenantStatus},
|
|
}
|
|
created := false
|
|
userID, err := a.findUserByEmail(ctx, in.Email)
|
|
switch {
|
|
case err == nil:
|
|
// Existing user (possibly created by an earlier, half-failed invite):
|
|
// fill in missing tenant-context attributes, never overwrite — roles
|
|
// stay Keycloak-owned.
|
|
if aerr := a.ensureUserAttributes(ctx, userID, attrs); aerr != nil {
|
|
slog.Warn("keycloak user attributes not merged", "user_id", userID, "err", aerr)
|
|
}
|
|
case errors.Is(err, errUserLookupMiss):
|
|
userID, err = a.createUser(ctx, userCreate{
|
|
Username: in.Email,
|
|
Email: in.Email,
|
|
FirstName: in.FirstName,
|
|
LastName: in.LastName,
|
|
Enabled: true,
|
|
EmailVerified: false,
|
|
Attributes: attrs,
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
created = true
|
|
default:
|
|
return nil, err
|
|
}
|
|
|
|
// KC 26: the member endpoint takes the bare user id as the JSON body.
|
|
resp, err := a.adminCall(ctx, http.MethodPost, fmt.Sprintf("/organizations/%s/members", orgID), userID, nil)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("add member: %w", err)
|
|
}
|
|
if resp.StatusCode == http.StatusConflict {
|
|
_ = resp.Body.Close()
|
|
return &MemberInviteResult{UserID: userID, Status: InviteStatusMember, Created: created}, nil
|
|
}
|
|
if resp.StatusCode/100 != 2 {
|
|
body, _ := io.ReadAll(resp.Body)
|
|
_ = resp.Body.Close()
|
|
return nil, fmt.Errorf("add member: %d %s", resp.StatusCode, body)
|
|
}
|
|
_ = resp.Body.Close()
|
|
|
|
res := &MemberInviteResult{UserID: userID, Status: InviteStatusInvited, Created: created}
|
|
if _, merr := a.executeActionsEmail(ctx, userID, []string{"VERIFY_EMAIL", "UPDATE_PASSWORD"}, a.cfg.InviteRedirectURI); merr != nil {
|
|
res.MailError = merr
|
|
}
|
|
return res, nil
|
|
}
|
|
|
|
// createUser POSTs a user and returns its id (Location header, falling back
|
|
// to an e-mail lookup). A 409 means another caller created it first.
|
|
func (a *HTTPAdapter) createUser(ctx context.Context, u userCreate) (string, error) {
|
|
resp, err := a.adminCall(ctx, http.MethodPost, "/users", u, nil)
|
|
if err != nil {
|
|
return "", fmt.Errorf("create user: %w", err)
|
|
}
|
|
switch resp.StatusCode {
|
|
case http.StatusCreated:
|
|
userID := lastSegment(resp.Header.Get("Location"))
|
|
_ = resp.Body.Close()
|
|
if userID != "" {
|
|
return userID, nil
|
|
}
|
|
case http.StatusConflict:
|
|
_ = resp.Body.Close()
|
|
default:
|
|
body, _ := io.ReadAll(resp.Body)
|
|
_ = resp.Body.Close()
|
|
return "", fmt.Errorf("create user: %d %s", resp.StatusCode, body)
|
|
}
|
|
userID, err := a.findUserByEmail(ctx, u.Email)
|
|
if err != nil {
|
|
return "", fmt.Errorf("create user: lookup after create failed: %w", err)
|
|
}
|
|
return userID, nil
|
|
}
|
|
|
|
// ensureUserAttributes merges attrs into the user's attributes, adding only
|
|
// keys that are absent (same contract as ensureOrgAttributes).
|
|
func (a *HTTPAdapter) ensureUserAttributes(ctx context.Context, userID string, attrs map[string][]string) error {
|
|
return a.updateUserAttributes(ctx, userID, func(existing map[string][]string) bool {
|
|
changed := false
|
|
for k, v := range attrs {
|
|
if len(attrValues(existing, k)) == 0 {
|
|
existing[k] = v
|
|
changed = true
|
|
}
|
|
}
|
|
return changed
|
|
})
|
|
}
|
|
|
|
func (a *HTTPAdapter) ResendInvite(ctx context.Context, slug, email string) error {
|
|
members, err := a.ListOrgMembers(ctx, slug)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, m := range members {
|
|
if strings.EqualFold(m.Email, email) {
|
|
_, err := a.executeActionsEmail(ctx, m.UserID, []string{"VERIFY_EMAIL", "UPDATE_PASSWORD"}, a.cfg.InviteRedirectURI)
|
|
return err
|
|
}
|
|
}
|
|
return ErrUserNotFound
|
|
}
|