Files
tenant-registry/internal/keycloak/members.go
T
Sharang ParnerkarandClaude Opus 5.5 fe05192182
ci / shared (pull_request) Successful in 26s
ci / test (pull_request) Successful in 6m7s
ci / image (pull_request) Skipped
feat(authz): individual capabilities per member (RBAC step 3)
A member can hold capabilities on top of their bundle. They live in the
Keycloak user attribute extra_capabilities, which the tenant-context
mapper puts into the token; the registry writes it like org_roles and
clears it when the member leaves.

- POST/DELETE /v1/tenants/{id}/members/{uid}/capabilities[/{cap}]
- a person who holds registry:members.manage grants, never on
  themselves, and only what they hold themselves
- an administration capability waits for a second person: open
  requests in capability_requests (0029), approve or reject under
  /v1/tenants/{id}/capability-requests
- a role change keeps the extras; the principal parses the claim, the
  registry's own checks still go by org_roles

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014aRnCGqELxoix5TfpX8Ejf
2026-11-11 13:39:36 +01:00

214 lines
6.8 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,
BlockedTenants: attrValues(m.Attributes, AttrOrgBlocked),
ExtraCapabilities: attrValues(m.Attributes, AttrExtraCapabilities),
}
}
// 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()
}
}
om := m.toOrgMember()
om.Pending = !a.hasPassword(ctx, m.ID)
out = append(out, om)
}
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.inviteRedirect(in.Slug)); 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.inviteRedirect(slug))
return err
}
}
return ErrUserNotFound
}