Files
tenant-registry/internal/keycloak/members.go
T
sharangandSharang Parnerkar 99214c088b
ci / shared (push) Successful in 13s
ci / test (push) Successful in 22m21s
ci / image (push) Successful in 25s
feat(members): tenant organization members, invites, admin email (#28)
Demonstration plan, phase D1 (registry side). The portal's Settings/Users page renders design fixtures today and its "Invite member" button posts to a route that does not exist, because the registry had no membership surface.

**`GET /v1/tenants/{id}/members`** lists the tenant's Keycloak organization members — user id, email, first/last name, `org_roles`, `enabled`, `created_at`. A tenant whose organization was never created (sales-led) answers an empty list rather than an error.

**`POST /v1/tenants/{id}/invites`** `{email, first_name?, last_name?, role?}` creates the Keycloak user if missing, adds the organization member (KC 26: the member body is the bare user id), writes the tenant-context user attributes, sends the same execute-actions mail the first admin gets, and audits `user.invited` with the caller as actor. Idempotent: an existing member answers `200 {status:"member"}` and sends no mail; a new one `202 {status:"invited"}`.

**Scope.** A user token may only touch its own tenant — another tenant's id is a 404, never a hint that it exists. Inviting needs the `IT_ADMIN` or `OWNER` org role, so `Principal` now carries the `org_roles` claim and `IsTenantAdmin()`. Service clients stay gated by `AUTHZ_RULES` route groups: members on `tenants.read`, invites on `tenants.write`.

**`admin_email` on the tenant** (migration `0006`, backfilled from the `keycloak.invite_sent` audit trail, and from `keycloak.provision_failed` metadata where the first invite failed) so Settings can show a real contact instead of an em dash. The first `IT_ADMIN`/`OWNER` invite fills it in when it was empty.

**Routing note worth keeping:** `GET /v1/tenants/{id}/members` cannot be registered — Go's ServeMux calls it a conflict with `GET /v1/tenants/by-slug/{slug}`, since both match `/v1/tenants/by-slug/members` and neither pattern is more specific. It is registered as `GET /v1/tenants/{id}/{sub}` instead, which *is* less specific than the by-slug lookup, so the two coexist; anything but `members` answers 404.

`openapi.yaml` documents both endpoints, the `OrgMember`/`Invite` schemas, `admin_email` and a `Forbidden` response.

Verified locally: `go vet ./...`, `gofmt` clean, `go test ./...` green, CI coverage command at **74.3%** (gate 70%).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
Co-authored-by: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com>
Reviewed-on: #28
2026-09-14 08:27:12 +00:00

219 lines
6.8 KiB
Go

package keycloak
import (
"context"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/url"
"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 {
var u userRepresentation
resp, err := a.adminCall(ctx, http.MethodGet, "/users/"+url.PathEscape(userID), nil, &u)
if err != nil {
return err
}
if resp.StatusCode/100 != 2 {
_ = resp.Body.Close()
return fmt.Errorf("get user: %d", resp.StatusCode)
}
existing := u.Attributes
if existing == nil {
existing = map[string][]string{}
}
changed := false
for k, v := range attrs {
if len(attrValues(existing, k)) == 0 {
existing[k] = v
changed = true
}
}
if !changed {
return nil
}
resp, err = a.adminCall(ctx, http.MethodPut, "/users/"+url.PathEscape(userID), map[string]any{"attributes": existing}, nil)
if err != nil {
return err
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode/100 != 2 {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("put user: %d %s", resp.StatusCode, body)
}
return nil
}