Files
tenant-registry/internal/keycloak/manage.go
T
sharangandClaude Opus 5.5 1f6236a754
ci / shared (push) Successful in 12s
ci / test (push) Successful in 24m46s
ci / image (push) Successful in 33s
feat(members): team management: role, block, remove, revoke, resend (#64)
portal#74: PATCH/DELETE /v1/tenants/{id}/members/{uid}, POST .../resend and the staff variants; per-workspace block via org_blocked, session logout, last-admin and self guards, audit events.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
2026-10-05 18:43:31 +00:00

183 lines
6.3 KiB
Go

package keycloak
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"slices"
)
// Team management (portal#74): role change, block/unblock, remove/revoke and
// session logout for one member of a tenant's organization.
//
// Blocking is per workspace. Keycloak's `enabled=false` would lock the
// person out of every workspace in the realm, so the block is recorded in
// the user attribute AttrOrgBlocked: the registry tenant ids (UUIDs) the
// user is blocked in. The attribute is admin-only (the realm's unmanaged
// attribute policy is ADMIN_EDIT), so a user cannot unblock themselves.
// Memberships() leaves blocked orgs out, MemberBlocked() answers the
// registry's authz and the entitlement check, and the portal derives
// "no access" from the memberships.
// AttrOrgBlocked is the user attribute listing the tenant ids a user is
// blocked in.
const AttrOrgBlocked = "org_blocked"
// tenantAttrs are the tenant-context user attributes the registry writes at
// invitation; removing a member clears them when they name that tenant.
var tenantAttrs = []string{"tenant_id", "tenant_slug", "org_roles", "tenant_status", "products", "plan"}
// SetMemberRole implements Adapter: org_roles becomes exactly [role].
func (a *HTTPAdapter) SetMemberRole(ctx context.Context, userID, role string) error {
return a.updateUserAttributes(ctx, userID, func(attrs map[string][]string) bool {
if cur := attrValues(attrs, "org_roles"); len(cur) == 1 && cur[0] == role {
return false
}
attrs["org_roles"] = []string{role}
return true
})
}
// SetMemberBlocked implements Adapter: adds or removes tenantID in the
// user's org_blocked attribute.
func (a *HTTPAdapter) SetMemberBlocked(ctx context.Context, userID, tenantID string, blocked bool) error {
return a.updateUserAttributes(ctx, userID, func(attrs map[string][]string) bool {
cur := attrValues(attrs, AttrOrgBlocked)
has := slices.Contains(cur, tenantID)
switch {
case blocked && !has:
attrs[AttrOrgBlocked] = append(cur, tenantID)
return true
case !blocked && has:
next := slices.DeleteFunc(cur, func(v string) bool { return v == tenantID })
if len(next) == 0 {
delete(attrs, AttrOrgBlocked)
} else {
attrs[AttrOrgBlocked] = next
}
return true
}
return false
})
}
// MemberBlocked implements Adapter: reads the user's org_blocked attribute.
// ErrUserNotFound for an unknown user.
func (a *HTTPAdapter) MemberBlocked(ctx context.Context, userID, tenantID string) (bool, error) {
var u userRepresentation
resp, err := a.adminCall(ctx, http.MethodGet, "/users/"+url.PathEscape(userID), nil, &u)
if err != nil {
return false, err
}
_ = resp.Body.Close()
if resp.StatusCode == http.StatusNotFound {
return false, ErrUserNotFound
}
if resp.StatusCode/100 != 2 {
return false, fmt.Errorf("get user: %d", resp.StatusCode)
}
return slices.Contains(attrValues(u.Attributes, AttrOrgBlocked), tenantID), nil
}
// RemoveMember implements Adapter. It drops the organization membership,
// clears the tenant-context attributes when they name tenantID, removes
// tenantID from org_blocked, and — only with deleteIfOrphan — deletes the
// account when it belongs to no other organization. A membership that is
// already gone is not an error.
func (a *HTTPAdapter) RemoveMember(ctx context.Context, slug, tenantID, userID string, deleteIfOrphan bool) (bool, error) {
orgID, err := a.findOrgByAlias(ctx, slug)
if err != nil {
return false, err
}
if err := a.deleteResource(ctx, fmt.Sprintf("/organizations/%s/members/%s", orgID, url.PathEscape(userID))); err != nil {
return false, fmt.Errorf("remove member: %w", err)
}
if deleteIfOrphan {
var orgs []memberOrgRepresentation
resp, err := a.adminCall(ctx, http.MethodGet, "/organizations/members/"+url.PathEscape(userID)+"/organizations", nil, &orgs)
if err != nil {
return false, err
}
_ = resp.Body.Close()
if resp.StatusCode/100 == 2 && len(orgs) == 0 {
if err := a.deleteResource(ctx, "/users/"+url.PathEscape(userID)); err != nil {
return false, fmt.Errorf("delete user: %w", err)
}
return true, nil
}
}
err = a.updateUserAttributes(ctx, userID, func(attrs map[string][]string) bool {
changed := false
if attrValue(attrs, "tenant_id") == tenantID {
for _, k := range tenantAttrs {
if _, ok := attrs[k]; ok {
delete(attrs, k)
changed = true
}
}
}
if cur := attrValues(attrs, AttrOrgBlocked); slices.Contains(cur, tenantID) {
next := slices.DeleteFunc(cur, func(v string) bool { return v == tenantID })
if len(next) == 0 {
delete(attrs, AttrOrgBlocked)
} else {
attrs[AttrOrgBlocked] = next
}
changed = true
}
return changed
})
return false, err
}
// LogoutUser implements Adapter: POST /users/{id}/logout ends every session
// of the user in the realm (Keycloak has no per-organization logout).
func (a *HTTPAdapter) LogoutUser(ctx context.Context, userID string) error {
resp, err := a.adminCall(ctx, http.MethodPost, "/users/"+url.PathEscape(userID)+"/logout", nil, nil)
if err != nil {
return err
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode/100 == 2 || resp.StatusCode == http.StatusNotFound {
return nil
}
body, _ := io.ReadAll(io.LimitReader(resp.Body, 256))
return fmt.Errorf("logout user: %d %s", resp.StatusCode, body)
}
// hasPassword reports whether the user has accepted the invitation: a
// password is set, or the account is linked to an identity provider. A failed lookup counts as yes: the member is shown as
// active rather than offering to revoke an invitation that may be accepted.
func (a *HTTPAdapter) hasPassword(ctx context.Context, userID string) bool {
var creds []struct {
Type string `json:"type"`
}
resp, err := a.adminCall(ctx, http.MethodGet, "/users/"+url.PathEscape(userID)+"/credentials", nil, &creds)
if err != nil {
return true
}
_ = resp.Body.Close()
if resp.StatusCode/100 != 2 {
return true
}
for _, c := range creds {
if c.Type == "password" {
return true
}
}
// No password: an account that signs in through an identity provider
// (enterprise SSO) has accepted all the same.
var links []json.RawMessage
resp, err = a.adminCall(ctx, http.MethodGet, "/users/"+url.PathEscape(userID)+"/federated-identity", nil, &links)
if err != nil {
return true
}
_ = resp.Body.Close()
return resp.StatusCode/100 != 2 || len(links) > 0
}