feat(members): team management: role, block, remove, revoke, resend #64
No files matched your search
@@ -38,6 +38,9 @@ type Principal struct {
|
||||
// OrgRoles is the `org_roles` claim (the tenant-context mapper projects
|
||||
// the Keycloak user attribute of the same name). Empty on service tokens.
|
||||
OrgRoles []string
|
||||
// OrgBlocked is the `org_blocked` claim, when a mapper projects it: the
|
||||
// tenant ids the user is blocked in (portal#74).
|
||||
OrgBlocked []string
|
||||
}
|
||||
|
||||
// IsUser reports whether the token carries a tenant context (a person
|
||||
@@ -124,11 +127,12 @@ func (v *Verifier) Verify(ctx context.Context, authorization string) (*Principal
|
||||
TenantStatus string `json:"tenant_status"`
|
||||
Email string `json:"email"`
|
||||
OrgRoles roles `json:"org_roles"`
|
||||
OrgBlocked roles `json:"org_blocked"`
|
||||
}
|
||||
_ = tok.Claims(&claims) // azp is informational; absence is not an error
|
||||
return &Principal{Subject: tok.Subject, ClientID: claims.Azp, Issuer: tok.Issuer,
|
||||
TenantID: claims.TenantID, TenantSlug: claims.TenantSlug, TenantStatus: claims.TenantStatus, Email: claims.Email,
|
||||
OrgRoles: []string(claims.OrgRoles)}, nil
|
||||
OrgRoles: []string(claims.OrgRoles), OrgBlocked: []string(claims.OrgBlocked)}, nil
|
||||
}
|
||||
|
||||
// roles decodes the org_roles claim in either shape the Keycloak mapper
|
||||
|
||||
@@ -148,6 +148,13 @@ func TestVerifier(t *testing.T) {
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("org_blocked claim", func(t *testing.T) {
|
||||
p, err := v.Verify(ctx, "Bearer "+iss.sign(t, iss.claims(map[string]any{"org_blocked": "t-1##t-2", "tenant_id": "t-1"})))
|
||||
if err != nil || len(p.OrgBlocked) != 2 || p.OrgBlocked[1] != "t-2" {
|
||||
t.Errorf("org_blocked: err=%v p=%+v", err, p)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("service token is never a tenant admin", func(t *testing.T) {
|
||||
p, err := v.Verify(ctx, "Bearer "+iss.sign(t, iss.claims(map[string]any{"org_roles": []string{"OWNER"}})))
|
||||
if err != nil || p.IsUser() || p.IsTenantAdmin() {
|
||||
|
||||
@@ -76,6 +76,36 @@ type OrgMember struct {
|
||||
OrgRoles []string `json:"org_roles"`
|
||||
Enabled bool `json:"enabled"`
|
||||
CreatedAt *time.Time `json:"created_at"`
|
||||
// Pending: the invitation is not accepted yet (no password set, no
|
||||
// identity-provider link). Filled by ListOrgMembers.
|
||||
Pending bool `json:"pending"`
|
||||
// Status is "invited", "active" or "blocked" for the tenant the list was
|
||||
// read for; the registry sets it (see MemberStatus), the adapter does not.
|
||||
Status string `json:"status,omitempty"`
|
||||
// BlockedTenants is the user's org_blocked attribute: the tenant ids the
|
||||
// member is blocked in. Internal; the API exposes Status.
|
||||
BlockedTenants []string `json:"-"`
|
||||
}
|
||||
|
||||
// Member status values (portal#74).
|
||||
const (
|
||||
MemberInvited = "invited"
|
||||
MemberActive = "active"
|
||||
MemberBlocked = "blocked"
|
||||
)
|
||||
|
||||
// MemberStatus is the member's status in tenantID: blocked wins over a
|
||||
// pending invitation.
|
||||
func (m OrgMember) MemberStatus(tenantID string) string {
|
||||
for _, t := range m.BlockedTenants {
|
||||
if t == tenantID {
|
||||
return MemberBlocked
|
||||
}
|
||||
}
|
||||
if m.Pending {
|
||||
return MemberInvited
|
||||
}
|
||||
return MemberActive
|
||||
}
|
||||
|
||||
// MemberInviteInput is POST /v1/tenants/{id}/invites as the adapter sees
|
||||
@@ -172,6 +202,27 @@ type Adapter interface {
|
||||
// carries only the coarse flag; entitlements stay in the registry).
|
||||
SyncTenantStatus(ctx context.Context, slug, status string) error
|
||||
|
||||
// SetMemberRole replaces the user's org_roles attribute with [role]. It
|
||||
// takes effect at the user's next login or token refresh.
|
||||
SetMemberRole(ctx context.Context, userID, role string) error
|
||||
|
||||
// SetMemberBlocked adds (blocked) or removes tenantID in the user's
|
||||
// org_blocked attribute — a per-workspace block, never enabled=false.
|
||||
SetMemberBlocked(ctx context.Context, userID, tenantID string, blocked bool) error
|
||||
|
||||
// MemberBlocked reports whether userID is blocked in tenantID.
|
||||
// ErrUserNotFound for an unknown user.
|
||||
MemberBlocked(ctx context.Context, userID, tenantID string) (bool, error)
|
||||
|
||||
// RemoveMember removes userID from the organization whose alias is slug
|
||||
// and clears its tenant-context attributes for tenantID. With
|
||||
// deleteIfOrphan the account is deleted when it belongs to no other
|
||||
// organization; the result reports whether it was.
|
||||
RemoveMember(ctx context.Context, slug, tenantID, userID string, deleteIfOrphan bool) (bool, error)
|
||||
|
||||
// LogoutUser ends all of the user's sessions in the realm.
|
||||
LogoutUser(ctx context.Context, userID string) error
|
||||
|
||||
// Health pings the admin endpoint. Used by readyz and the cluster cold-
|
||||
// start sequence (INFRASTRUCTURE.md §10 scenario F).
|
||||
Health(ctx context.Context) error
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
package keycloak
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestHTTPAdapter_ListOrgMembers_status(t *testing.T) {
|
||||
k, a := newMembersKC(t)
|
||||
k.members["org-acme"] = []string{"u-admin", "u-loose", "u-sso"}
|
||||
k.users["u-sso"] = memberRepresentation{ID: "u-sso", Email: "sso@acme.test", Enabled: true,
|
||||
Attributes: map[string][]string{AttrOrgBlocked: {"t-acme##t-other"}}}
|
||||
k.idp["u-sso"] = true
|
||||
members, err := a.ListOrgMembers(context.Background(), "acme")
|
||||
if err != nil || len(members) != 3 {
|
||||
t.Fatalf("list: %v %+v", err, members)
|
||||
}
|
||||
byID := map[string]OrgMember{}
|
||||
for _, m := range members {
|
||||
byID[m.UserID] = m
|
||||
}
|
||||
if byID["u-admin"].Pending || byID["u-admin"].MemberStatus("t-acme") != MemberActive {
|
||||
t.Errorf("password set → active: %+v", byID["u-admin"])
|
||||
}
|
||||
if !byID["u-loose"].Pending || byID["u-loose"].MemberStatus("t-acme") != MemberInvited {
|
||||
t.Errorf("no password → invited: %+v", byID["u-loose"])
|
||||
}
|
||||
sso := byID["u-sso"]
|
||||
if sso.Pending || sso.MemberStatus("t-acme") != MemberBlocked || sso.MemberStatus("t-third") != MemberActive {
|
||||
t.Errorf("idp-linked, blocked in acme: %+v", sso)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPAdapter_hasPasswordFailsTowardsAccepted(t *testing.T) {
|
||||
_, a := newMembersKC(t)
|
||||
// Unknown user: the credentials lookup 404s — counted as accepted, never
|
||||
// offered for revocation.
|
||||
if !a.hasPassword(context.Background(), "u-ghost") {
|
||||
t.Error("lookup failure must count as accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPAdapter_SetMemberRole(t *testing.T) {
|
||||
k, a := newMembersKC(t)
|
||||
ctx := context.Background()
|
||||
if err := a.SetMemberRole(ctx, "u-admin", "CXO"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := k.puts["u-admin"]["org_roles"]; !slices.Equal(got, []string{"CXO"}) {
|
||||
t.Errorf("org_roles: %v", got)
|
||||
}
|
||||
if k.puts["u-admin"]["tenant_slug"][0] != "acme" {
|
||||
t.Errorf("other attributes must survive: %v", k.puts["u-admin"])
|
||||
}
|
||||
delete(k.puts, "u-admin")
|
||||
if err := a.SetMemberRole(ctx, "u-admin", "CXO"); err != nil || k.puts["u-admin"] != nil {
|
||||
t.Errorf("same role must not write: %v %v", err, k.puts)
|
||||
}
|
||||
if err := a.SetMemberRole(ctx, "u-ghost", "CXO"); err == nil {
|
||||
t.Error("unknown user must fail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPAdapter_SetMemberBlocked(t *testing.T) {
|
||||
k, a := newMembersKC(t)
|
||||
ctx := context.Background()
|
||||
if err := a.SetMemberBlocked(ctx, "u-admin", "t-1", true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := a.SetMemberBlocked(ctx, "u-admin", "t-2", true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := k.users["u-admin"].Attributes[AttrOrgBlocked]; !slices.Equal(got, []string{"t-1", "t-2"}) {
|
||||
t.Fatalf("blocked: %v", got)
|
||||
}
|
||||
if b, err := a.MemberBlocked(ctx, "u-admin", "t-2"); err != nil || !b {
|
||||
t.Errorf("MemberBlocked t-2: %v %v", b, err)
|
||||
}
|
||||
delete(k.puts, "u-admin")
|
||||
if err := a.SetMemberBlocked(ctx, "u-admin", "t-1", true); err != nil || k.puts["u-admin"] != nil {
|
||||
t.Errorf("already blocked must not write: %v", err)
|
||||
}
|
||||
if err := a.SetMemberBlocked(ctx, "u-admin", "t-1", false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := k.users["u-admin"].Attributes[AttrOrgBlocked]; !slices.Equal(got, []string{"t-2"}) {
|
||||
t.Errorf("after unblock t-1: %v", got)
|
||||
}
|
||||
if err := a.SetMemberBlocked(ctx, "u-admin", "t-2", false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, ok := k.users["u-admin"].Attributes[AttrOrgBlocked]; ok {
|
||||
t.Errorf("empty org_blocked must be dropped: %v", k.users["u-admin"].Attributes)
|
||||
}
|
||||
delete(k.puts, "u-admin")
|
||||
if err := a.SetMemberBlocked(ctx, "u-admin", "t-9", false); err != nil || k.puts["u-admin"] != nil {
|
||||
t.Errorf("not blocked, unblock must not write: %v", err)
|
||||
}
|
||||
if b, err := a.MemberBlocked(ctx, "u-admin", "t-2"); err != nil || b {
|
||||
t.Errorf("MemberBlocked after unblock: %v %v", b, err)
|
||||
}
|
||||
if _, err := a.MemberBlocked(ctx, "u-ghost", "t-2"); !errors.Is(err, ErrUserNotFound) {
|
||||
t.Errorf("unknown user: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPAdapter_RemoveMember(t *testing.T) {
|
||||
k, a := newMembersKC(t)
|
||||
ctx := context.Background()
|
||||
k.users["u-fin"] = memberRepresentation{ID: "u-fin", Email: "fin@acme.test", Attributes: map[string][]string{
|
||||
"tenant_id": {"t-acme"}, "tenant_slug": {"acme"}, "org_roles": {"FINANCE"}, "tenant_status": {"active"},
|
||||
AttrOrgBlocked: {"t-acme", "t-other"}, "locale": {"de"},
|
||||
}}
|
||||
k.members["org-acme"] = append(k.members["org-acme"], "u-fin")
|
||||
deleted, err := a.RemoveMember(ctx, "acme", "t-acme", "u-fin", false)
|
||||
if err != nil || deleted {
|
||||
t.Fatalf("remove: %v %v", deleted, err)
|
||||
}
|
||||
if slices.Contains(k.members["org-acme"], "u-fin") {
|
||||
t.Error("membership not removed")
|
||||
}
|
||||
attrs := k.users["u-fin"].Attributes
|
||||
for _, key := range []string{"tenant_id", "tenant_slug", "org_roles", "tenant_status"} {
|
||||
if _, ok := attrs[key]; ok {
|
||||
t.Errorf("%s must be cleared: %v", key, attrs)
|
||||
}
|
||||
}
|
||||
if !slices.Equal(attrs[AttrOrgBlocked], []string{"t-other"}) || attrs["locale"][0] != "de" {
|
||||
t.Errorf("unrelated attributes must stay: %v", attrs)
|
||||
}
|
||||
if len(k.deleted) != 0 {
|
||||
t.Errorf("account deleted without deleteIfOrphan: %v", k.deleted)
|
||||
}
|
||||
|
||||
// Attributes naming another tenant stay; a lone block entry is dropped.
|
||||
k.users["u-two"] = memberRepresentation{ID: "u-two", Attributes: map[string][]string{"tenant_id": {"t-other"}, AttrOrgBlocked: {"t-acme"}}}
|
||||
k.members["org-acme"] = append(k.members["org-acme"], "u-two")
|
||||
if _, err := a.RemoveMember(ctx, "acme", "t-acme", "u-two", false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := k.users["u-two"].Attributes; got["tenant_id"][0] != "t-other" || got[AttrOrgBlocked] != nil {
|
||||
t.Errorf("other tenant attributes: %v", got)
|
||||
}
|
||||
|
||||
if _, err := a.RemoveMember(ctx, "ghost", "t", "u-two", false); !errors.Is(err, ErrOrgNotFound) {
|
||||
t.Errorf("missing org: %v", err)
|
||||
}
|
||||
k.failWrite = http.StatusForbidden
|
||||
if _, err := a.RemoveMember(ctx, "acme", "t-acme", "u-admin", false); err == nil || !strings.Contains(err.Error(), "remove member") {
|
||||
t.Errorf("member delete failure: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPAdapter_RemoveMember_deleteIfOrphan(t *testing.T) {
|
||||
k, a := newMembersKC(t)
|
||||
ctx := context.Background()
|
||||
k.users["u-inv"] = memberRepresentation{ID: "u-inv", Email: "inv@acme.test"}
|
||||
k.members["org-acme"] = append(k.members["org-acme"], "u-inv")
|
||||
k.orgs["other"] = "org-other"
|
||||
k.members["org-other"] = []string{"u-inv"}
|
||||
|
||||
// Still in another org: the account stays.
|
||||
deleted, err := a.RemoveMember(ctx, "acme", "t-acme", "u-inv", true)
|
||||
if err != nil || deleted || len(k.deleted) != 0 {
|
||||
t.Fatalf("other org: %v %v %v", deleted, err, k.deleted)
|
||||
}
|
||||
// Orphaned: deleted.
|
||||
deleted, err = a.RemoveMember(ctx, "other", "t-other", "u-inv", true)
|
||||
if err != nil || !deleted || !slices.Equal(k.deleted, []string{"u-inv"}) {
|
||||
t.Fatalf("orphan: %v %v %v", deleted, err, k.deleted)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPAdapter_LogoutUser(t *testing.T) {
|
||||
k, a := newMembersKC(t)
|
||||
if err := a.LogoutUser(context.Background(), "u-admin"); err != nil || !slices.Equal(k.logouts, []string{"u-admin"}) {
|
||||
t.Fatalf("logout: %v %v", err, k.logouts)
|
||||
}
|
||||
k.failWrite = http.StatusInternalServerError
|
||||
if err := a.LogoutUser(context.Background(), "u-admin"); err == nil {
|
||||
t.Error("logout failure must surface")
|
||||
}
|
||||
k.failWrite = http.StatusNotFound
|
||||
if err := a.LogoutUser(context.Background(), "u-gone"); err != nil {
|
||||
t.Errorf("gone user is not an error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMemberships_skipsBlockedOrgs(t *testing.T) {
|
||||
users := map[string]userRepresentation{
|
||||
"u-1": {ID: "u-1", Enabled: true, Attributes: map[string][]string{"org_roles": {"USER"}, AttrOrgBlocked: {"t-b", "legacy"}}},
|
||||
}
|
||||
orgs := map[string][]memberOrgRepresentation{"u-1": {
|
||||
{ID: "o-a", Alias: "alpha", Enabled: true, Attributes: map[string][]string{"tenant_id": {"t-a"}}},
|
||||
{ID: "o-b", Alias: "beta", Enabled: true, Attributes: map[string][]string{"tenant_id": {"t-b"}}},
|
||||
{ID: "o-l", Alias: "legacy", Enabled: true},
|
||||
}}
|
||||
a := usersAdapter(stubUsersKC(t, users, orgs))
|
||||
got, err := a.Memberships(context.Background(), "u-1")
|
||||
if err != nil || len(got) != 1 || got[0].TenantSlug != "alpha" {
|
||||
t.Fatalf("memberships: %v %+v", err, got)
|
||||
}
|
||||
}
|
||||
@@ -37,13 +37,14 @@ func (m memberRepresentation) toOrgMember() OrgMember {
|
||||
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,
|
||||
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),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,7 +76,9 @@ func (a *HTTPAdapter) ListOrgMembers(ctx context.Context, slug string) ([]OrgMem
|
||||
_ = resp.Body.Close()
|
||||
}
|
||||
}
|
||||
out = append(out, m.toOrgMember())
|
||||
om := m.toOrgMember()
|
||||
om.Pending = !a.hasPassword(ctx, m.ID)
|
||||
out = append(out, om)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
@@ -26,6 +26,11 @@ type membersKC struct {
|
||||
puts map[string]map[string][]string // user id → attributes PUT
|
||||
createErr int // non-zero: POST /users answers this status
|
||||
nextID int
|
||||
creds map[string][]string // user id → credential types
|
||||
idp map[string]bool // user id → linked to an identity provider
|
||||
logouts []string // user ids logged out
|
||||
deleted []string // user ids deleted
|
||||
failWrite int // non-zero: member DELETE / logout answer this status
|
||||
}
|
||||
|
||||
// orgName is the display name the registry gives an organization: the company
|
||||
@@ -47,7 +52,9 @@ func newMembersKC(t *testing.T) (*membersKC, *HTTPAdapter) {
|
||||
"u-loose": {ID: "u-loose", Username: "loose@acme.test", Email: "loose@acme.test", Enabled: true,
|
||||
Attributes: map[string][]string{"tenant_id": {"other"}}},
|
||||
},
|
||||
puts: map[string]map[string][]string{},
|
||||
puts: map[string]map[string][]string{},
|
||||
creds: map[string][]string{"u-admin": {"otp", "password"}},
|
||||
idp: map[string]bool{},
|
||||
}
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/realms/test-realm/protocol/openid-connect/token", tokenOK)
|
||||
@@ -181,6 +188,75 @@ func newMembersKC(t *testing.T) (*membersKC, *HTTPAdapter) {
|
||||
k.mails = append(k.mails, r.PathValue("id"))
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
})
|
||||
mux.HandleFunc("GET /admin/realms/test-realm/users/{id}/credentials", func(w http.ResponseWriter, r *http.Request) {
|
||||
k.mu.Lock()
|
||||
defer k.mu.Unlock()
|
||||
if _, ok := k.users[r.PathValue("id")]; !ok {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
out := []map[string]string{}
|
||||
for _, typ := range k.creds[r.PathValue("id")] {
|
||||
out = append(out, map[string]string{"type": typ})
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(out)
|
||||
})
|
||||
mux.HandleFunc("GET /admin/realms/test-realm/users/{id}/federated-identity", func(w http.ResponseWriter, r *http.Request) {
|
||||
k.mu.Lock()
|
||||
defer k.mu.Unlock()
|
||||
out := []map[string]string{}
|
||||
if k.idp[r.PathValue("id")] {
|
||||
out = append(out, map[string]string{"identityProvider": "company-sso"})
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(out)
|
||||
})
|
||||
mux.HandleFunc("DELETE /admin/realms/test-realm/organizations/{id}/members/{uid}", func(w http.ResponseWriter, r *http.Request) {
|
||||
k.mu.Lock()
|
||||
defer k.mu.Unlock()
|
||||
if k.failWrite != 0 {
|
||||
w.WriteHeader(k.failWrite)
|
||||
return
|
||||
}
|
||||
org := r.PathValue("id")
|
||||
for i, m := range k.members[org] {
|
||||
if m == r.PathValue("uid") {
|
||||
k.members[org] = append(k.members[org][:i], k.members[org][i+1:]...)
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
}
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
})
|
||||
mux.HandleFunc("GET /admin/realms/test-realm/organizations/members/{uid}/organizations", func(w http.ResponseWriter, r *http.Request) {
|
||||
k.mu.Lock()
|
||||
defer k.mu.Unlock()
|
||||
out := []memberOrgRepresentation{}
|
||||
for alias, org := range k.orgs {
|
||||
for _, m := range k.members[org] {
|
||||
if m == r.PathValue("uid") {
|
||||
out = append(out, memberOrgRepresentation{ID: org, Alias: alias, Enabled: true})
|
||||
}
|
||||
}
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(out)
|
||||
})
|
||||
mux.HandleFunc("DELETE /admin/realms/test-realm/users/{id}", func(w http.ResponseWriter, r *http.Request) {
|
||||
k.mu.Lock()
|
||||
defer k.mu.Unlock()
|
||||
delete(k.users, r.PathValue("id"))
|
||||
k.deleted = append(k.deleted, r.PathValue("id"))
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
})
|
||||
mux.HandleFunc("POST /admin/realms/test-realm/users/{id}/logout", func(w http.ResponseWriter, r *http.Request) {
|
||||
k.mu.Lock()
|
||||
defer k.mu.Unlock()
|
||||
if k.failWrite != 0 {
|
||||
w.WriteHeader(k.failWrite)
|
||||
return
|
||||
}
|
||||
k.logouts = append(k.logouts, r.PathValue("id"))
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
})
|
||||
srv := httptest.NewServer(mux)
|
||||
t.Cleanup(srv.Close)
|
||||
a := NewHTTPAdapter(HTTPConfig{
|
||||
|
||||
@@ -3,6 +3,7 @@ package keycloak
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -28,6 +29,13 @@ type Mock struct {
|
||||
Resent []string // every ResendInvite call that found the member
|
||||
Purged []string // every PurgeTenant call, by slug
|
||||
Created []InviteInput // every successful CreateOrgAndInvite call
|
||||
|
||||
// Team management (portal#74).
|
||||
Blocked map[string][]string // userID → tenant ids the user is blocked in
|
||||
RoleSet map[string]string // userID → last SetMemberRole
|
||||
Removed []string // every RemoveMember call, by user id
|
||||
Deleted []string // accounts RemoveMember deleted
|
||||
LoggedOut []string // every LogoutUser call
|
||||
}
|
||||
|
||||
func NewMock() *Mock {
|
||||
@@ -37,9 +45,109 @@ func NewMock() *Mock {
|
||||
Claims: map[string]Claims{},
|
||||
Status: map[string]string{},
|
||||
Members: map[string][]OrgMember{},
|
||||
Blocked: map[string][]string{},
|
||||
RoleSet: map[string]string{},
|
||||
}
|
||||
}
|
||||
|
||||
// failNext returns and clears FailNext. Callers hold m.mu.
|
||||
func (m *Mock) failNext() error {
|
||||
err := m.FailNext
|
||||
m.FailNext = nil
|
||||
return err
|
||||
}
|
||||
|
||||
// SetMemberRole implements Adapter: the role lands on every org membership
|
||||
// of the user (org_roles is a user attribute).
|
||||
func (m *Mock) SetMemberRole(_ context.Context, userID, role string) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if err := m.failNext(); err != nil {
|
||||
return err
|
||||
}
|
||||
m.RoleSet[userID] = role
|
||||
for slug, members := range m.Members {
|
||||
for i := range members {
|
||||
if members[i].UserID == userID {
|
||||
m.Members[slug][i].OrgRoles = []string{role}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetMemberBlocked implements Adapter.
|
||||
func (m *Mock) SetMemberBlocked(_ context.Context, userID, tenantID string, blocked bool) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if err := m.failNext(); err != nil {
|
||||
return err
|
||||
}
|
||||
cur := slices.DeleteFunc(slices.Clone(m.Blocked[userID]), func(v string) bool { return v == tenantID })
|
||||
if blocked {
|
||||
cur = append(cur, tenantID)
|
||||
}
|
||||
m.Blocked[userID] = cur
|
||||
return nil
|
||||
}
|
||||
|
||||
// MemberBlocked implements Adapter. Unknown users are not blocked.
|
||||
func (m *Mock) MemberBlocked(_ context.Context, userID, tenantID string) (bool, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if err := m.failNext(); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return slices.Contains(m.Blocked[userID], tenantID), nil
|
||||
}
|
||||
|
||||
// RemoveMember implements Adapter.
|
||||
func (m *Mock) RemoveMember(_ context.Context, slug, tenantID, userID string, deleteIfOrphan bool) (bool, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if err := m.failNext(); err != nil {
|
||||
return false, err
|
||||
}
|
||||
members, ok := m.Members[slug]
|
||||
if !ok {
|
||||
return false, ErrOrgNotFound
|
||||
}
|
||||
var email string
|
||||
m.Members[slug] = slices.DeleteFunc(slices.Clone(members), func(mem OrgMember) bool {
|
||||
if mem.UserID == userID {
|
||||
email = mem.Email
|
||||
return true
|
||||
}
|
||||
return false
|
||||
})
|
||||
m.Blocked[userID] = slices.DeleteFunc(m.Blocked[userID], func(v string) bool { return v == tenantID })
|
||||
m.Removed = append(m.Removed, userID)
|
||||
if !deleteIfOrphan {
|
||||
return false, nil
|
||||
}
|
||||
for _, other := range m.Members {
|
||||
for _, mem := range other {
|
||||
if mem.UserID == userID {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
delete(m.Users, email)
|
||||
m.Deleted = append(m.Deleted, userID)
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// LogoutUser implements Adapter.
|
||||
func (m *Mock) LogoutUser(_ context.Context, userID string) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if err := m.failNext(); err != nil {
|
||||
return err
|
||||
}
|
||||
m.LoggedOut = append(m.LoggedOut, userID)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Mock) ListOrgMembers(_ context.Context, slug string) ([]OrgMember, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
@@ -54,6 +162,9 @@ func (m *Mock) ListOrgMembers(_ context.Context, slug string) ([]OrgMember, erro
|
||||
}
|
||||
out := make([]OrgMember, len(members))
|
||||
copy(out, members)
|
||||
for i := range out {
|
||||
out[i].BlockedTenants = slices.Clone(m.Blocked[out[i].UserID])
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
@@ -176,6 +287,9 @@ func (m *Mock) Memberships(_ context.Context, userID string) ([]Claims, error) {
|
||||
if !ok {
|
||||
return nil, ErrUserNotFound
|
||||
}
|
||||
if slices.Contains(m.Blocked[userID], c.TenantID) {
|
||||
return []Claims{}, nil
|
||||
}
|
||||
return []Claims{c}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -93,3 +93,56 @@ func TestMock_userExists(t *testing.T) {
|
||||
t.Error("unknown user found")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMock_teamManagement(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
m := NewMock()
|
||||
m.Members["acme"] = []OrgMember{{UserID: "u-1", Email: "a@acme.test", OrgRoles: []string{"USER"}}}
|
||||
m.Members["beta"] = []OrgMember{{UserID: "u-1", Email: "a@acme.test"}}
|
||||
m.Users["a@acme.test"] = "u-1"
|
||||
m.Claims["u-1"] = Claims{TenantID: "t-acme", TenantSlug: "acme"}
|
||||
|
||||
if err := m.SetMemberRole(ctx, "u-1", "CXO"); err != nil || m.Members["acme"][0].OrgRoles[0] != "CXO" {
|
||||
t.Fatalf("role: %v %+v", err, m.Members)
|
||||
}
|
||||
if err := m.SetMemberBlocked(ctx, "u-1", "t-acme", true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if b, _ := m.MemberBlocked(ctx, "u-1", "t-acme"); !b {
|
||||
t.Error("blocked")
|
||||
}
|
||||
if c, _ := m.Memberships(ctx, "u-1"); len(c) != 0 {
|
||||
t.Errorf("blocked membership listed: %+v", c)
|
||||
}
|
||||
if l, _ := m.ListOrgMembers(ctx, "acme"); l[0].MemberStatus("t-acme") != MemberBlocked {
|
||||
t.Errorf("list: %+v", l)
|
||||
}
|
||||
if err := m.SetMemberBlocked(ctx, "u-1", "t-acme", false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := m.LogoutUser(ctx, "u-1"); err != nil || len(m.LoggedOut) != 1 {
|
||||
t.Errorf("logout: %v", err)
|
||||
}
|
||||
// Still in beta: not deleted.
|
||||
if del, err := m.RemoveMember(ctx, "acme", "t-acme", "u-1", true); err != nil || del {
|
||||
t.Errorf("remove (other org): %v %v", del, err)
|
||||
}
|
||||
if del, err := m.RemoveMember(ctx, "beta", "t-beta", "u-1", true); err != nil || !del || m.Users["a@acme.test"] != "" {
|
||||
t.Errorf("remove (orphan): %v %v", del, err)
|
||||
}
|
||||
if _, err := m.RemoveMember(ctx, "ghost", "t", "u-1", false); !errors.Is(err, ErrOrgNotFound) {
|
||||
t.Errorf("ghost org: %v", err)
|
||||
}
|
||||
for _, call := range []func() error{
|
||||
func() error { return m.SetMemberRole(ctx, "u", "USER") },
|
||||
func() error { return m.SetMemberBlocked(ctx, "u", "t", true) },
|
||||
func() error { _, err := m.MemberBlocked(ctx, "u", "t"); return err },
|
||||
func() error { _, err := m.RemoveMember(ctx, "acme", "t", "u", false); return err },
|
||||
func() error { return m.LogoutUser(ctx, "u") },
|
||||
} {
|
||||
m.FailNext = ErrUnavailable
|
||||
if err := call(); !errors.Is(err, ErrUnavailable) {
|
||||
t.Errorf("FailNext not honoured: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -41,7 +42,9 @@ type memberOrgRepresentation struct {
|
||||
// tenant_status) that SyncClaims maintains.
|
||||
// 2. GET /organizations/members/{id}/organizations — the memberships.
|
||||
//
|
||||
// One Claims entry per ENABLED organization: TenantID = org attribute
|
||||
// One Claims entry per ENABLED organization the user is not blocked in
|
||||
// (org_blocked lists tenant ids; an org without a tenant_id attribute is
|
||||
// matched by alias): TenantID = org attribute
|
||||
// "tenant_id" (registry UUID), TenantSlug = org alias. A disabled org
|
||||
// grants no membership. A user in no organization has zero memberships —
|
||||
// the legacy user-attribute tenant projection is NO LONGER consulted for
|
||||
@@ -74,11 +77,17 @@ func (a *HTTPAdapter) Memberships(ctx context.Context, userID string) ([]Claims,
|
||||
return nil, fmt.Errorf("keycloak member organizations: %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
blocked := attrValues(u.Attributes, AttrOrgBlocked)
|
||||
claims := []Claims{}
|
||||
for _, org := range orgs {
|
||||
if !org.Enabled {
|
||||
continue
|
||||
}
|
||||
// A member blocked in this workspace (portal#74) has no membership
|
||||
// here, whatever the token mappers project.
|
||||
if tid := attrValue(org.Attributes, "tenant_id"); (tid != "" && slices.Contains(blocked, tid)) || slices.Contains(blocked, org.Alias) {
|
||||
continue
|
||||
}
|
||||
claims = append(claims, Claims{
|
||||
TenantID: attrValue(org.Attributes, "tenant_id"),
|
||||
TenantSlug: org.Alias,
|
||||
|
||||
@@ -146,6 +146,7 @@ func (s *Server) adminGetTenant(w http.ResponseWriter, r *http.Request) {
|
||||
members, merr := s.Keycloak.ListOrgMembers(ctx, t.Slug)
|
||||
switch {
|
||||
case merr == nil:
|
||||
decorateMembers(members, t.ID)
|
||||
out.Members = members
|
||||
case errors.Is(merr, keycloak.ErrOrgNotFound):
|
||||
out.MembersError = "no organization yet"
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/keycloak"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/store"
|
||||
)
|
||||
|
||||
@@ -13,6 +14,9 @@ type entitlementCheckReq struct {
|
||||
TenantID string `json:"tenant_id"`
|
||||
Product string `json:"product"`
|
||||
Addon string `json:"addon,omitempty"`
|
||||
// UserID (optional): the Keycloak user acting. A member blocked in the
|
||||
// tenant is not allowed (portal#74), whatever the tenant is entitled to.
|
||||
UserID string `json:"user_id,omitempty"`
|
||||
}
|
||||
|
||||
// EntitlementCheck is the answer products cache for ≤ 60 s
|
||||
@@ -44,6 +48,17 @@ func (s *Server) checkEntitlement(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, http.StatusInternalServerError, "internal", err.Error())
|
||||
return
|
||||
}
|
||||
if in.UserID != "" && res.Allowed {
|
||||
blocked, berr := s.memberBlocked(ctx, in.UserID, in.TenantID)
|
||||
switch {
|
||||
case errors.Is(berr, keycloak.ErrUserNotFound):
|
||||
res = EntitlementCheck{Status: res.Status, Reason: "user_unknown"}
|
||||
case berr != nil:
|
||||
s.Log.Warn("member block check failed; allowing", "user_id", in.UserID, "tenant_id", in.TenantID, "err", berr)
|
||||
case blocked:
|
||||
res = EntitlementCheck{Status: res.Status, Reason: "member_blocked"}
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, res)
|
||||
}
|
||||
|
||||
|
||||
@@ -110,6 +110,7 @@ func (s *Server) listTenantMembers(w http.ResponseWriter, r *http.Request) {
|
||||
if members == nil {
|
||||
members = []keycloak.OrgMember{}
|
||||
}
|
||||
decorateMembers(members, t.ID)
|
||||
writeJSON(w, http.StatusOK, membersResp{Members: members})
|
||||
}
|
||||
|
||||
|
||||
@@ -48,6 +48,12 @@ func TestOpenAPISpec_loadsAndIsConsistent(t *testing.T) {
|
||||
{"GET", "/v1/tenants?limit=10"},
|
||||
{"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/members"},
|
||||
{"POST", "/v1/tenants/00000000-0000-0000-0000-000000000001/invites"},
|
||||
{"PATCH", "/v1/tenants/00000000-0000-0000-0000-000000000001/members/u-1"},
|
||||
{"DELETE", "/v1/tenants/00000000-0000-0000-0000-000000000001/members/u-1"},
|
||||
{"POST", "/v1/tenants/00000000-0000-0000-0000-000000000001/members/u-1/resend"},
|
||||
{"PATCH", "/v1/admin/tenants/00000000-0000-0000-0000-000000000001/members/u-1"},
|
||||
{"DELETE", "/v1/admin/tenants/00000000-0000-0000-0000-000000000001/members/u-1"},
|
||||
{"POST", "/v1/admin/tenants/00000000-0000-0000-0000-000000000001/members/u-1/resend"},
|
||||
{"GET", "/v1/admin/tenants?q=acme"},
|
||||
{"GET", "/v1/admin/tenants/00000000-0000-0000-0000-000000000001"},
|
||||
{"POST", "/v1/admin/tenants/00000000-0000-0000-0000-000000000001/trial"},
|
||||
|
||||
@@ -39,6 +39,8 @@ type Server struct {
|
||||
Objects storage.Objects // nil ⇒ document routes answer 503 (F2)
|
||||
Mail mail.Sender // nil ⇒ notifications queue up unsent (F3)
|
||||
Now func() time.Time // injectable clock (tests); nil ⇒ time.Now
|
||||
|
||||
blocks blockCache // MemberBlocked answers for user tokens (team.go)
|
||||
}
|
||||
|
||||
func (s *Server) now() time.Time {
|
||||
@@ -111,6 +113,10 @@ func NewRouter(s *Server) http.Handler {
|
||||
// the two coexist and the lookup keeps winning for its own prefix.
|
||||
mux.HandleFunc("GET /v1/tenants/{id}/{sub}", s.tenantSubresource)
|
||||
mux.HandleFunc("POST /v1/tenants/{id}/invites", s.inviteTenantMember)
|
||||
// Team management (portal#74): role, block, remove/revoke, resend.
|
||||
mux.HandleFunc("PATCH /v1/tenants/{id}/members/{uid}", s.patchTenantMember)
|
||||
mux.HandleFunc("DELETE /v1/tenants/{id}/members/{uid}", s.deleteTenantMember)
|
||||
mux.HandleFunc("POST /v1/tenants/{id}/members/{uid}/resend", s.resendTenantMember)
|
||||
// Trial signup (portal#64): offer, confirmation/activation, new link; the
|
||||
// contract documents of a tenant.
|
||||
mux.HandleFunc("POST /v1/trial-offers", s.createTrialOffer)
|
||||
@@ -167,6 +173,9 @@ func NewRouter(s *Server) http.Handler {
|
||||
mux.HandleFunc("GET /v1/admin/tenants/{id}", s.adminGetTenant)
|
||||
mux.HandleFunc("POST /v1/admin/tenants/{id}/trial", s.adminExtendTrial)
|
||||
mux.HandleFunc("POST /v1/admin/tenants/{id}/invites/resend", s.adminResendInvite)
|
||||
mux.HandleFunc("PATCH /v1/admin/tenants/{id}/members/{uid}", s.adminPatchMember)
|
||||
mux.HandleFunc("DELETE /v1/admin/tenants/{id}/members/{uid}", s.adminDeleteMember)
|
||||
mux.HandleFunc("POST /v1/admin/tenants/{id}/members/{uid}/resend", s.adminResendMember)
|
||||
mux.HandleFunc("POST /v1/admin/tenants/{id}/reprovision", s.adminReprovision)
|
||||
mux.HandleFunc("DELETE /v1/admin/tenants/{id}", s.adminPurgeTenant)
|
||||
mux.HandleFunc("GET /v1/admin/audit", s.listAudit)
|
||||
@@ -188,7 +197,7 @@ func NewRouter(s *Server) http.Handler {
|
||||
// Tenant documents (F2): the list is a {sub} of tenantSubresource.
|
||||
mux.HandleFunc("GET /v1/tenants/{id}/documents/{doc}/download", s.downloadTenantDocument)
|
||||
|
||||
root.Handle("/", s.requireAuth(s.requireAuthz(mux)))
|
||||
root.Handle("/", s.requireAuth(s.requireMember(s.requireAuthz(mux))))
|
||||
return logRequest(s.Log)(root)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,490 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/authn"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/keycloak"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/store"
|
||||
)
|
||||
|
||||
// Team management (portal#74): change a member's role, block or unblock
|
||||
// them in this workspace, remove them or revoke a pending invitation, and
|
||||
// resend an invitation.
|
||||
//
|
||||
// PATCH /v1/tenants/{id}/members/{uid} {"role"} | {"blocked"}
|
||||
// DELETE /v1/tenants/{id}/members/{uid} remove / revoke invitation
|
||||
// POST /v1/tenants/{id}/members/{uid}/resend
|
||||
//
|
||||
// and the same three under /v1/admin/tenants/{id}/members/{uid} for staff
|
||||
// (route group "admin"; the portal lets only BREAKPILOT_ADMIN write).
|
||||
//
|
||||
// Who may: a user token needs IT_ADMIN/OWNER in its own tenant; a service
|
||||
// client needs tenants.write. The portal calls as its service client and
|
||||
// names the person in X-Portal-User-Subject / X-Portal-User-Email (staff:
|
||||
// X-Staff-*), which the guards and the audit trail use.
|
||||
//
|
||||
// Guards (409): nobody acts on themselves ("self"); the last active
|
||||
// IT_ADMIN/OWNER is never demoted, blocked or removed ("last_admin").
|
||||
//
|
||||
// Block is per workspace: the tenant id goes into the member's org_blocked
|
||||
// attribute (keycloak.AttrOrgBlocked), never enabled=false — a person can
|
||||
// belong to several workspaces. Remove and block end the member's Keycloak
|
||||
// sessions (realm-wide: Keycloak has no per-organization logout).
|
||||
|
||||
const headerPortalUserSubject = "X-Portal-User-Subject"
|
||||
|
||||
// teamRoles are the org roles a member can be given.
|
||||
var teamRoles = []string{authn.RoleITAdmin, authn.RoleOwner, "CXO", "FINANCE", "LEGAL", "USER"}
|
||||
|
||||
func isAdminRole(roles []string) bool {
|
||||
return slices.Contains(roles, authn.RoleITAdmin) || slices.Contains(roles, authn.RoleOwner)
|
||||
}
|
||||
|
||||
type memberPatchReq struct {
|
||||
Role *string `json:"role"`
|
||||
Blocked *bool `json:"blocked"`
|
||||
}
|
||||
|
||||
type memberActionResp struct {
|
||||
// Status: role_changed | unchanged | blocked | unblocked | removed |
|
||||
// invite_revoked | invite_resent.
|
||||
Status string `json:"status"`
|
||||
Member *keycloak.OrgMember `json:"member,omitempty"`
|
||||
// UserDeleted: revoking the invitation also deleted the account (it was
|
||||
// created by the invitation and belongs to no other workspace).
|
||||
UserDeleted bool `json:"user_deleted,omitempty"`
|
||||
// SessionsEnded: the member's Keycloak sessions were ended.
|
||||
SessionsEnded bool `json:"sessions_ended,omitempty"`
|
||||
// APIKeys: the member's active API keys in this tenant, offered for
|
||||
// revocation after a remove or block — never revoked silently.
|
||||
APIKeys []store.APIKey `json:"api_keys,omitempty"`
|
||||
}
|
||||
|
||||
// teamActor is who performs a team action, for the guards and the audit.
|
||||
type teamActor struct {
|
||||
ID, Email, Type string
|
||||
}
|
||||
|
||||
func (s *Server) teamActor(r *http.Request) teamActor {
|
||||
if sub, email, ok := s.staffActor(r); ok {
|
||||
return teamActor{ID: sub, Email: email, Type: "staff"}
|
||||
}
|
||||
p, _ := authn.PrincipalFrom(r.Context())
|
||||
if p.IsUser() {
|
||||
return teamActor{ID: p.Subject, Email: p.Email, Type: "user"}
|
||||
}
|
||||
// The portal acting for a signed-in tenant admin.
|
||||
if sub := strings.TrimSpace(r.Header.Get(headerPortalUserSubject)); sub != "" {
|
||||
return teamActor{ID: sub, Email: strings.TrimSpace(r.Header.Get(headerPortalUserEmail)), Type: "user"}
|
||||
}
|
||||
a := teamActor{Type: "service"}
|
||||
if p != nil {
|
||||
a.ID = p.Subject
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
func (a teamActor) is(m keycloak.OrgMember) bool {
|
||||
return (a.ID != "" && a.ID == m.UserID) || (a.Email != "" && strings.EqualFold(a.Email, m.Email))
|
||||
}
|
||||
|
||||
// teamTenantFromUser resolves the tenant for the tenant-scoped routes: a
|
||||
// user token needs a tenant-admin role and its own tenant.
|
||||
func (s *Server) teamTenantFromUser(ctx context.Context, w http.ResponseWriter, r *http.Request) (*store.Tenant, bool) {
|
||||
if p, _ := authn.PrincipalFrom(r.Context()); p.IsUser() && !p.IsTenantAdmin() {
|
||||
writeError(w, http.StatusForbidden, "FORBIDDEN_ROLE", "managing users requires the IT_ADMIN or OWNER org role")
|
||||
return nil, false
|
||||
}
|
||||
return s.tenantInScope(ctx, w, r)
|
||||
}
|
||||
|
||||
// teamTenantFromAdmin resolves the tenant for the staff routes.
|
||||
func (s *Server) teamTenantFromAdmin(ctx context.Context, w http.ResponseWriter, r *http.Request) (*store.Tenant, bool) {
|
||||
t, err := s.Store.GetTenant(ctx, r.PathValue("id"))
|
||||
if err != nil {
|
||||
if !mapStoreError(w, err) {
|
||||
writeError(w, http.StatusInternalServerError, "internal", err.Error())
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
return t, true
|
||||
}
|
||||
|
||||
type tenantResolver func(context.Context, http.ResponseWriter, *http.Request) (*store.Tenant, bool)
|
||||
|
||||
// teamTarget loads the tenant, its members and the member the path names.
|
||||
func (s *Server) teamTarget(ctx context.Context, w http.ResponseWriter, r *http.Request, resolve tenantResolver) (*store.Tenant, []keycloak.OrgMember, *keycloak.OrgMember, bool) {
|
||||
t, ok := resolve(ctx, w, r)
|
||||
if !ok {
|
||||
return nil, nil, nil, false
|
||||
}
|
||||
members, err := s.Keycloak.ListOrgMembers(ctx, t.Slug)
|
||||
if err != nil && !errors.Is(err, keycloak.ErrOrgNotFound) {
|
||||
s.writeKeycloakError(w, t.ID, "list members", err)
|
||||
return nil, nil, nil, false
|
||||
}
|
||||
decorateMembers(members, t.ID)
|
||||
uid := r.PathValue("uid")
|
||||
for i := range members {
|
||||
if members[i].UserID == uid {
|
||||
return t, members, &members[i], true
|
||||
}
|
||||
}
|
||||
writeError(w, http.StatusNotFound, "not_a_member", "no such member in this tenant")
|
||||
return nil, nil, nil, false
|
||||
}
|
||||
|
||||
// decorateMembers sets each member's status for tenantID.
|
||||
func decorateMembers(members []keycloak.OrgMember, tenantID string) {
|
||||
for i := range members {
|
||||
members[i].Status = members[i].MemberStatus(tenantID)
|
||||
}
|
||||
}
|
||||
|
||||
// lastActiveAdmin reports whether target is the only active (accepted, not
|
||||
// blocked) IT_ADMIN/OWNER of the tenant.
|
||||
func lastActiveAdmin(members []keycloak.OrgMember, target *keycloak.OrgMember) bool {
|
||||
if target.Status != keycloak.MemberActive || !isAdminRole(target.OrgRoles) {
|
||||
return false
|
||||
}
|
||||
for _, m := range members {
|
||||
if m.UserID != target.UserID && m.Status == keycloak.MemberActive && isAdminRole(m.OrgRoles) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Server) teamAudit(ctx context.Context, r *http.Request, t *store.Tenant, actor teamActor, action string, m *keycloak.OrgMember, meta map[string]interface{}) {
|
||||
if meta == nil {
|
||||
meta = map[string]interface{}{}
|
||||
}
|
||||
meta["user_id"] = m.UserID
|
||||
s.emitAudit(ctx, r, store.AuditEvent{
|
||||
TenantID: t.ID, Action: action,
|
||||
ActorID: actor.ID, ActorName: actor.Email, ActorType: actor.Type,
|
||||
TargetID: m.Email, TargetType: "user", TargetName: m.Email,
|
||||
Metadata: meta,
|
||||
})
|
||||
}
|
||||
|
||||
// memberAPIKeys lists the tenant's active API keys created by the member.
|
||||
func (s *Server) memberAPIKeys(ctx context.Context, tenantID string, m *keycloak.OrgMember) []store.APIKey {
|
||||
keys, err := s.Store.ListAPIKeys(ctx, tenantID)
|
||||
if err != nil {
|
||||
s.Log.Warn("api keys not listed", "tenant_id", tenantID, "err", err)
|
||||
return nil
|
||||
}
|
||||
out := []store.APIKey{}
|
||||
for _, k := range keys {
|
||||
if k.RevokedAt == nil && k.CreatedBy != "" && (k.CreatedBy == m.UserID || strings.EqualFold(k.CreatedBy, m.Email)) {
|
||||
out = append(out, k)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// endSessions logs the member out; a failure is logged, not fatal (the
|
||||
// block or removal already holds, the session dies at token expiry).
|
||||
func (s *Server) endSessions(ctx context.Context, tenantID, userID string) bool {
|
||||
if err := s.Keycloak.LogoutUser(ctx, userID); err != nil {
|
||||
s.Log.Warn("member sessions not ended", "tenant_id", tenantID, "user_id", userID, "err", err)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Server) patchTenantMember(w http.ResponseWriter, r *http.Request) {
|
||||
s.patchMember(w, r, s.teamTenantFromUser)
|
||||
}
|
||||
|
||||
func (s *Server) adminPatchMember(w http.ResponseWriter, r *http.Request) {
|
||||
s.patchMember(w, r, s.teamTenantFromAdmin)
|
||||
}
|
||||
|
||||
func (s *Server) patchMember(w http.ResponseWriter, r *http.Request, resolve tenantResolver) {
|
||||
var in memberPatchReq
|
||||
if !decodeJSON(w, r, &in) {
|
||||
return
|
||||
}
|
||||
if (in.Role == nil) == (in.Blocked == nil) {
|
||||
writeError(w, http.StatusBadRequest, "invalid_input", "send exactly one of role or blocked")
|
||||
return
|
||||
}
|
||||
role := ""
|
||||
if in.Role != nil {
|
||||
role = strings.ToUpper(strings.TrimSpace(*in.Role))
|
||||
if !slices.Contains(teamRoles, role) {
|
||||
writeError(w, http.StatusBadRequest, "invalid_role", "role must be one of "+strings.Join(teamRoles, ", "))
|
||||
return
|
||||
}
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
|
||||
defer cancel()
|
||||
t, members, m, ok := s.teamTarget(ctx, w, r, resolve)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
actor := s.teamActor(r)
|
||||
if actor.is(*m) {
|
||||
writeError(w, http.StatusConflict, "self", "you cannot change your own membership")
|
||||
return
|
||||
}
|
||||
|
||||
if in.Role != nil {
|
||||
s.changeRole(ctx, w, r, t, actor, members, m, role)
|
||||
return
|
||||
}
|
||||
s.setBlocked(ctx, w, r, t, actor, members, m, *in.Blocked)
|
||||
}
|
||||
|
||||
func (s *Server) changeRole(ctx context.Context, w http.ResponseWriter, r *http.Request, t *store.Tenant, actor teamActor, members []keycloak.OrgMember, m *keycloak.OrgMember, role string) {
|
||||
old := slices.Clone(m.OrgRoles)
|
||||
if len(old) == 1 && old[0] == role {
|
||||
writeJSON(w, http.StatusOK, memberActionResp{Status: "unchanged", Member: m})
|
||||
return
|
||||
}
|
||||
if !isAdminRole([]string{role}) && lastActiveAdmin(members, m) {
|
||||
writeError(w, http.StatusConflict, "last_admin", "the last IT_ADMIN of a workspace cannot be demoted")
|
||||
return
|
||||
}
|
||||
if err := s.Keycloak.SetMemberRole(ctx, m.UserID, role); err != nil {
|
||||
s.writeKeycloakError(w, t.ID, "set member role", err)
|
||||
return
|
||||
}
|
||||
m.OrgRoles = []string{role}
|
||||
s.teamAudit(ctx, r, t, actor, "user.role_changed", m, map[string]interface{}{"from": old, "to": role})
|
||||
writeJSON(w, http.StatusOK, memberActionResp{Status: "role_changed", Member: m})
|
||||
}
|
||||
|
||||
func (s *Server) setBlocked(ctx context.Context, w http.ResponseWriter, r *http.Request, t *store.Tenant, actor teamActor, members []keycloak.OrgMember, m *keycloak.OrgMember, blocked bool) {
|
||||
if blocked == (m.Status == keycloak.MemberBlocked) {
|
||||
writeJSON(w, http.StatusOK, memberActionResp{Status: "unchanged", Member: m})
|
||||
return
|
||||
}
|
||||
if blocked && lastActiveAdmin(members, m) {
|
||||
writeError(w, http.StatusConflict, "last_admin", "the last IT_ADMIN of a workspace cannot be blocked")
|
||||
return
|
||||
}
|
||||
if err := s.Keycloak.SetMemberBlocked(ctx, m.UserID, t.ID, blocked); err != nil {
|
||||
s.writeKeycloakError(w, t.ID, "set member blocked", err)
|
||||
return
|
||||
}
|
||||
s.blocks.forget(m.UserID)
|
||||
if !blocked {
|
||||
m.BlockedTenants = slices.DeleteFunc(m.BlockedTenants, func(v string) bool { return v == t.ID })
|
||||
m.Status = m.MemberStatus(t.ID)
|
||||
s.teamAudit(ctx, r, t, actor, "user.unblocked", m, nil)
|
||||
writeJSON(w, http.StatusOK, memberActionResp{Status: "unblocked", Member: m})
|
||||
return
|
||||
}
|
||||
m.BlockedTenants = append(m.BlockedTenants, t.ID)
|
||||
m.Status = keycloak.MemberBlocked
|
||||
ended := s.endSessions(ctx, t.ID, m.UserID)
|
||||
keys := s.memberAPIKeys(ctx, t.ID, m)
|
||||
s.teamAudit(ctx, r, t, actor, "user.blocked", m, map[string]interface{}{"sessions_ended": ended, "api_keys": len(keys)})
|
||||
writeJSON(w, http.StatusOK, memberActionResp{Status: "blocked", Member: m, SessionsEnded: ended, APIKeys: keys})
|
||||
}
|
||||
|
||||
func (s *Server) deleteTenantMember(w http.ResponseWriter, r *http.Request) {
|
||||
s.deleteMember(w, r, s.teamTenantFromUser)
|
||||
}
|
||||
|
||||
func (s *Server) adminDeleteMember(w http.ResponseWriter, r *http.Request) {
|
||||
s.deleteMember(w, r, s.teamTenantFromAdmin)
|
||||
}
|
||||
|
||||
// deleteMember removes an accepted member, or revokes a pending invitation.
|
||||
func (s *Server) deleteMember(w http.ResponseWriter, r *http.Request, resolve tenantResolver) {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
|
||||
defer cancel()
|
||||
t, members, m, ok := s.teamTarget(ctx, w, r, resolve)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
actor := s.teamActor(r)
|
||||
if actor.is(*m) {
|
||||
writeError(w, http.StatusConflict, "self", "you cannot remove yourself")
|
||||
return
|
||||
}
|
||||
if lastActiveAdmin(members, m) {
|
||||
writeError(w, http.StatusConflict, "last_admin", "the last IT_ADMIN of a workspace cannot be removed")
|
||||
return
|
||||
}
|
||||
|
||||
if m.Status == keycloak.MemberInvited {
|
||||
created := s.inviteCreatedUser(ctx, t.ID, m.UserID)
|
||||
deleted, err := s.Keycloak.RemoveMember(ctx, t.Slug, t.ID, m.UserID, created)
|
||||
if err != nil {
|
||||
s.writeKeycloakError(w, t.ID, "revoke invitation", err)
|
||||
return
|
||||
}
|
||||
s.blocks.forget(m.UserID)
|
||||
s.teamAudit(ctx, r, t, actor, "user.invite_revoked", m, map[string]interface{}{"user_deleted": deleted})
|
||||
writeJSON(w, http.StatusOK, memberActionResp{Status: "invite_revoked", UserDeleted: deleted})
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := s.Keycloak.RemoveMember(ctx, t.Slug, t.ID, m.UserID, false); err != nil {
|
||||
s.writeKeycloakError(w, t.ID, "remove member", err)
|
||||
return
|
||||
}
|
||||
s.blocks.forget(m.UserID)
|
||||
ended := s.endSessions(ctx, t.ID, m.UserID)
|
||||
keys := s.memberAPIKeys(ctx, t.ID, m)
|
||||
s.teamAudit(ctx, r, t, actor, "user.removed", m, map[string]interface{}{"roles": m.OrgRoles, "sessions_ended": ended, "api_keys": len(keys)})
|
||||
writeJSON(w, http.StatusOK, memberActionResp{Status: "removed", SessionsEnded: ended, APIKeys: keys})
|
||||
}
|
||||
|
||||
// inviteCreatedUser reports whether a user.invited entry of this tenant
|
||||
// records that the invitation created the Keycloak account userID. Only
|
||||
// then may revoking the invitation delete the account.
|
||||
func (s *Server) inviteCreatedUser(ctx context.Context, tenantID, userID string) bool {
|
||||
f := store.AuditFilter{TenantID: tenantID, Action: "user.invited", Limit: 500}
|
||||
for range 20 {
|
||||
items, next, err := s.Store.ListAudit(ctx, f)
|
||||
if err != nil {
|
||||
s.Log.Warn("invite audit not read", "tenant_id", tenantID, "err", err)
|
||||
return false
|
||||
}
|
||||
for _, ev := range items {
|
||||
if ev.Metadata["user_id"] == userID && ev.Metadata["user_created"] == true {
|
||||
return true
|
||||
}
|
||||
}
|
||||
if next == 0 {
|
||||
return false
|
||||
}
|
||||
f.Cursor = next
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *Server) resendTenantMember(w http.ResponseWriter, r *http.Request) {
|
||||
s.resendMember(w, r, s.teamTenantFromUser)
|
||||
}
|
||||
|
||||
func (s *Server) adminResendMember(w http.ResponseWriter, r *http.Request) {
|
||||
s.resendMember(w, r, s.teamTenantFromAdmin)
|
||||
}
|
||||
|
||||
func (s *Server) resendMember(w http.ResponseWriter, r *http.Request, resolve tenantResolver) {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
|
||||
defer cancel()
|
||||
t, _, m, ok := s.teamTarget(ctx, w, r, resolve)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if m.Status != keycloak.MemberInvited {
|
||||
writeError(w, http.StatusConflict, "not_pending", "the member has already accepted the invitation")
|
||||
return
|
||||
}
|
||||
if err := s.Keycloak.ResendInvite(ctx, t.Slug, m.Email); err != nil {
|
||||
s.writeKeycloakError(w, t.ID, "resend invite", err)
|
||||
return
|
||||
}
|
||||
s.teamAudit(ctx, r, t, s.teamActor(r), "user.invite_resent", m, nil)
|
||||
writeJSON(w, http.StatusAccepted, memberActionResp{Status: "invite_resent", Member: m})
|
||||
}
|
||||
|
||||
// ─── blocked members at the door ────────────────────────────────────────
|
||||
|
||||
// blockTTL bounds how long a block decision is cached per (user, tenant).
|
||||
// Blocks made through this registry instance take effect at once (forget).
|
||||
const blockTTL = 30 * time.Second
|
||||
|
||||
type blockEntry struct {
|
||||
blocked bool
|
||||
until time.Time
|
||||
}
|
||||
|
||||
// blockCache remembers MemberBlocked answers for user tokens.
|
||||
type blockCache struct {
|
||||
mu sync.Mutex
|
||||
m map[string]blockEntry
|
||||
}
|
||||
|
||||
func (c *blockCache) get(key string, now time.Time) (bool, bool) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
e, ok := c.m[key]
|
||||
if !ok || now.After(e.until) {
|
||||
return false, false
|
||||
}
|
||||
return e.blocked, true
|
||||
}
|
||||
|
||||
func (c *blockCache) put(key string, blocked bool, now time.Time) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if c.m == nil {
|
||||
c.m = map[string]blockEntry{}
|
||||
}
|
||||
c.m[key] = blockEntry{blocked: blocked, until: now.Add(blockTTL)}
|
||||
}
|
||||
|
||||
// forget drops every cached decision for userID.
|
||||
func (c *blockCache) forget(userID string) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
for k := range c.m {
|
||||
if strings.HasPrefix(k, userID+"|") {
|
||||
delete(c.m, k)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// requireMember rejects user tokens of a member blocked in the token's
|
||||
// tenant (portal#74): by the org_blocked claim when a mapper projects it,
|
||||
// and — independent of any mapper — by the user's org_blocked attribute in
|
||||
// Keycloak (cached for blockTTL). Service tokens pass. A Keycloak outage
|
||||
// does not lock everyone out: the lookup then fails open and logs.
|
||||
func (s *Server) requireMember(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
p, _ := authn.PrincipalFrom(r.Context())
|
||||
if !p.IsUser() {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
if slices.Contains(p.OrgBlocked, p.TenantID) {
|
||||
writeError(w, http.StatusForbidden, "MEMBER_BLOCKED", "your access to this workspace is blocked")
|
||||
return
|
||||
}
|
||||
blocked, err := s.memberBlocked(r.Context(), p.Subject, p.TenantID)
|
||||
switch {
|
||||
case errors.Is(err, keycloak.ErrUserNotFound):
|
||||
writeError(w, http.StatusForbidden, "USER_UNKNOWN", "the account no longer exists")
|
||||
return
|
||||
case err != nil:
|
||||
s.Log.Warn("member block check failed; allowing", "user_id", p.Subject, "tenant_id", p.TenantID, "err", err)
|
||||
case blocked:
|
||||
writeError(w, http.StatusForbidden, "MEMBER_BLOCKED", "your access to this workspace is blocked")
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// memberBlocked is Keycloak.MemberBlocked behind the blockCache.
|
||||
func (s *Server) memberBlocked(ctx context.Context, userID, tenantID string) (bool, error) {
|
||||
key := userID + "|" + tenantID
|
||||
now := s.now()
|
||||
if v, ok := s.blocks.get(key, now); ok {
|
||||
return v, nil
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
v, err := s.Keycloak.MemberBlocked(ctx, userID, tenantID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
s.blocks.put(key, v, now)
|
||||
return v, nil
|
||||
}
|
||||
@@ -0,0 +1,524 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/authn"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/keycloak"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/store"
|
||||
)
|
||||
|
||||
// teamFixture: tenant "acme" with an active IT_ADMIN (u-admin), an active
|
||||
// FINANCE member (u-fin) and a pending CXO invitation (u-inv).
|
||||
type teamFixture struct {
|
||||
s *Server
|
||||
h http.Handler
|
||||
kc *keycloak.Mock
|
||||
tenant *store.Tenant
|
||||
}
|
||||
|
||||
func newTeamFixture(t *testing.T, p *authn.Principal, rules ...string) *teamFixture {
|
||||
t.Helper()
|
||||
mem := store.NewMemory()
|
||||
tenant, _ := mem.GetTenantBySlug(context.Background(), "acme")
|
||||
kc := keycloak.NewMock()
|
||||
kc.Members["acme"] = []keycloak.OrgMember{
|
||||
{UserID: "u-admin", Email: "admin@acme.test", OrgRoles: []string{"IT_ADMIN"}, Enabled: true},
|
||||
{UserID: "u-fin", Email: "fin@acme.test", OrgRoles: []string{"FINANCE"}, Enabled: true},
|
||||
{UserID: "u-inv", Email: "inv@acme.test", OrgRoles: []string{"CXO"}, Enabled: true, Pending: true},
|
||||
}
|
||||
kc.Users["inv@acme.test"] = "u-inv"
|
||||
s := &Server{Log: slog.New(slog.NewTextHandler(io.Discard, nil)), Store: mem, Keycloak: kc}
|
||||
if len(rules) > 0 {
|
||||
s.Authz = ParseAuthzRules(rules[0])
|
||||
}
|
||||
router := NewRouter(s)
|
||||
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if p != nil {
|
||||
r = r.WithContext(authn.WithPrincipal(r.Context(), p))
|
||||
}
|
||||
router.ServeHTTP(w, r)
|
||||
})
|
||||
return &teamFixture{s: s, h: h, kc: kc, tenant: tenant}
|
||||
}
|
||||
|
||||
// portal is the portal's service client acting for the signed-in admin.
|
||||
var portal = &authn.Principal{Subject: "svc-portal", ClientID: "portal-svc"}
|
||||
|
||||
func (f *teamFixture) call(t *testing.T, method, path, body string, hdr map[string]string) (int, memberActionResp, string) {
|
||||
t.Helper()
|
||||
var rd io.Reader
|
||||
if body != "" {
|
||||
rd = strings.NewReader(body)
|
||||
}
|
||||
req := httptest.NewRequest(method, path, rd)
|
||||
for k, v := range hdr {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
rr := httptest.NewRecorder()
|
||||
f.h.ServeHTTP(rr, req)
|
||||
var out memberActionResp
|
||||
_ = json.Unmarshal(rr.Body.Bytes(), &out)
|
||||
return rr.Code, out, rr.Body.String()
|
||||
}
|
||||
|
||||
func (f *teamFixture) memberPath(uid string) string {
|
||||
return "/v1/tenants/" + f.tenant.ID + "/members/" + uid
|
||||
}
|
||||
|
||||
func (f *teamFixture) audit(t *testing.T, action string) []store.AuditEvent {
|
||||
t.Helper()
|
||||
items, _, err := f.s.Store.ListAudit(context.Background(), store.AuditFilter{TenantID: f.tenant.ID, Action: action})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
var asAdmin = map[string]string{headerPortalUserSubject: "u-admin", headerPortalUserEmail: "admin@acme.test"}
|
||||
|
||||
func TestTeam_changeRole(t *testing.T) {
|
||||
f := newTeamFixture(t, portal)
|
||||
code, out, raw := f.call(t, http.MethodPatch, f.memberPath("u-fin"), `{"role":"cxo"}`, asAdmin)
|
||||
if code != http.StatusOK || out.Status != "role_changed" || out.Member == nil || out.Member.OrgRoles[0] != "CXO" {
|
||||
t.Fatalf("role change: %d %s", code, raw)
|
||||
}
|
||||
if f.kc.RoleSet["u-fin"] != "CXO" {
|
||||
t.Errorf("keycloak role: %v", f.kc.RoleSet)
|
||||
}
|
||||
ev := f.audit(t, "user.role_changed")
|
||||
if len(ev) != 1 || ev[0].ActorID != "u-admin" || ev[0].ActorName != "admin@acme.test" || ev[0].ActorType != "user" ||
|
||||
ev[0].TargetName != "fin@acme.test" || ev[0].Metadata["to"] != "CXO" {
|
||||
t.Fatalf("audit: %+v", ev)
|
||||
}
|
||||
if from, _ := ev[0].Metadata["from"].([]string); !slices.Equal(from, []string{"FINANCE"}) {
|
||||
t.Errorf("audit from: %#v", ev[0].Metadata["from"])
|
||||
}
|
||||
|
||||
// Same role again: unchanged, no second audit entry.
|
||||
code, out, _ = f.call(t, http.MethodPatch, f.memberPath("u-fin"), `{"role":"CXO"}`, asAdmin)
|
||||
if code != http.StatusOK || out.Status != "unchanged" || len(f.audit(t, "user.role_changed")) != 1 {
|
||||
t.Fatalf("unchanged: %d %+v", code, out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTeam_patchValidation(t *testing.T) {
|
||||
f := newTeamFixture(t, portal)
|
||||
for _, body := range []string{`{}`, `{"role":"CXO","blocked":true}`, `{"role":"GOD"}`, `nope`} {
|
||||
if code, _, raw := f.call(t, http.MethodPatch, f.memberPath("u-fin"), body, asAdmin); code != http.StatusBadRequest {
|
||||
t.Errorf("%s: %d %s", body, code, raw)
|
||||
}
|
||||
}
|
||||
if code, _, raw := f.call(t, http.MethodPatch, f.memberPath("u-ghost"), `{"role":"CXO"}`, asAdmin); code != http.StatusNotFound || !strings.Contains(raw, "not_a_member") {
|
||||
t.Errorf("unknown member: %d %s", code, raw)
|
||||
}
|
||||
if code, _, _ := f.call(t, http.MethodPatch, "/v1/tenants/00000000-0000-0000-0000-0000000000ff/members/u-fin", `{"role":"CXO"}`, asAdmin); code != http.StatusNotFound {
|
||||
t.Errorf("unknown tenant: %d", code)
|
||||
}
|
||||
f.kc.FailNext = keycloak.ErrUnavailable
|
||||
if code, _, _ := f.call(t, http.MethodPatch, f.memberPath("u-fin"), `{"role":"CXO"}`, asAdmin); code != http.StatusServiceUnavailable {
|
||||
t.Errorf("kc down on list: %d", code)
|
||||
}
|
||||
delete(f.kc.Members, "acme")
|
||||
if code, _, _ := f.call(t, http.MethodPatch, f.memberPath("u-fin"), `{"role":"CXO"}`, asAdmin); code != http.StatusNotFound {
|
||||
t.Errorf("no org: %d", code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTeam_guards(t *testing.T) {
|
||||
f := newTeamFixture(t, portal)
|
||||
// Nobody acts on themselves — by subject or by e-mail.
|
||||
for _, c := range []struct{ method, body string }{
|
||||
{http.MethodPatch, `{"role":"USER"}`},
|
||||
{http.MethodPatch, `{"blocked":true}`},
|
||||
{http.MethodDelete, ``},
|
||||
} {
|
||||
code, _, raw := f.call(t, c.method, f.memberPath("u-admin"), c.body, asAdmin)
|
||||
if code != http.StatusConflict || !strings.Contains(raw, `"self"`) {
|
||||
t.Errorf("self %s %s: %d %s", c.method, c.body, code, raw)
|
||||
}
|
||||
}
|
||||
byMail := map[string]string{headerPortalUserSubject: "other-id", headerPortalUserEmail: "ADMIN@acme.test"}
|
||||
if code, _, raw := f.call(t, http.MethodDelete, f.memberPath("u-admin"), "", byMail); code != http.StatusConflict || !strings.Contains(raw, `"self"`) {
|
||||
t.Errorf("self by mail: %d %s", code, raw)
|
||||
}
|
||||
|
||||
// The last active IT_ADMIN: staff (no self) still cannot demote, block or
|
||||
// remove them. The pending CXO does not count as an admin.
|
||||
staff := map[string]string{headerStaffSubject: "staff-1", headerStaffEmail: "ops@breakpilot.test"}
|
||||
for _, c := range []struct{ method, body string }{
|
||||
{http.MethodPatch, `{"role":"USER"}`},
|
||||
{http.MethodPatch, `{"blocked":true}`},
|
||||
{http.MethodDelete, ``},
|
||||
} {
|
||||
code, _, raw := f.call(t, c.method, f.memberPath("u-admin"), c.body, staff)
|
||||
if code != http.StatusConflict || !strings.Contains(raw, "last_admin") {
|
||||
t.Errorf("last admin %s %s: %d %s", c.method, c.body, code, raw)
|
||||
}
|
||||
}
|
||||
// Admin → OWNER keeps an admin role: allowed.
|
||||
if code, _, raw := f.call(t, http.MethodPatch, f.memberPath("u-admin"), `{"role":"OWNER"}`, staff); code != http.StatusOK {
|
||||
t.Errorf("admin to owner: %d %s", code, raw)
|
||||
}
|
||||
// With a second active admin the first may be demoted.
|
||||
if code, _, raw := f.call(t, http.MethodPatch, f.memberPath("u-fin"), `{"role":"IT_ADMIN"}`, staff); code != http.StatusOK {
|
||||
t.Fatalf("promote: %d %s", code, raw)
|
||||
}
|
||||
if code, _, raw := f.call(t, http.MethodPatch, f.memberPath("u-admin"), `{"role":"USER"}`, staff); code != http.StatusOK {
|
||||
t.Errorf("demote with second admin: %d %s", code, raw)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTeam_blockAndUnblock(t *testing.T) {
|
||||
f := newTeamFixture(t, portal)
|
||||
ctx := context.Background()
|
||||
mine, _ := f.s.Store.CreateAPIKey(ctx, store.APIKeyCreate{TenantID: f.tenant.ID, Name: "ci", Prefix: "bp_aaaa1", Hash: "h1", CreatedBy: "fin@acme.test"})
|
||||
_, _ = f.s.Store.CreateAPIKey(ctx, store.APIKeyCreate{TenantID: f.tenant.ID, Name: "other", Prefix: "bp_aaaa2", Hash: "h2", CreatedBy: "admin@acme.test"})
|
||||
gone, _ := f.s.Store.CreateAPIKey(ctx, store.APIKeyCreate{TenantID: f.tenant.ID, Name: "old", Prefix: "bp_aaaa3", Hash: "h3", CreatedBy: "u-fin"})
|
||||
_ = f.s.Store.RevokeAPIKey(ctx, gone.ID)
|
||||
|
||||
code, out, raw := f.call(t, http.MethodPatch, f.memberPath("u-fin"), `{"blocked":true}`, asAdmin)
|
||||
if code != http.StatusOK || out.Status != "blocked" || out.Member.Status != "blocked" || !out.SessionsEnded {
|
||||
t.Fatalf("block: %d %s", code, raw)
|
||||
}
|
||||
if len(out.APIKeys) != 1 || out.APIKeys[0].ID != mine.ID {
|
||||
t.Errorf("api keys offered: %+v", out.APIKeys)
|
||||
}
|
||||
if !slices.Contains(f.kc.Blocked["u-fin"], f.tenant.ID) || !slices.Equal(f.kc.LoggedOut, []string{"u-fin"}) {
|
||||
t.Errorf("keycloak: blocked=%v logout=%v", f.kc.Blocked, f.kc.LoggedOut)
|
||||
}
|
||||
if ev := f.audit(t, "user.blocked"); len(ev) != 1 || ev[0].Metadata["sessions_ended"] != true {
|
||||
t.Errorf("audit: %+v", ev)
|
||||
}
|
||||
// The key is listed, not revoked.
|
||||
if keys, _ := f.s.Store.ListAPIKeys(ctx, f.tenant.ID); keys[0].RevokedAt != nil && keys[0].ID == mine.ID {
|
||||
t.Error("api key was revoked silently")
|
||||
}
|
||||
|
||||
// The list shows the status.
|
||||
rr := httptest.NewRecorder()
|
||||
f.h.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, "/v1/tenants/"+f.tenant.ID+"/members", nil))
|
||||
if !strings.Contains(rr.Body.String(), `"status":"blocked"`) || !strings.Contains(rr.Body.String(), `"status":"invited"`) {
|
||||
t.Errorf("list statuses: %s", rr.Body.String())
|
||||
}
|
||||
|
||||
// Blocking again is a no-op.
|
||||
if code, out, _ := f.call(t, http.MethodPatch, f.memberPath("u-fin"), `{"blocked":true}`, asAdmin); code != http.StatusOK || out.Status != "unchanged" {
|
||||
t.Errorf("block twice: %d %+v", code, out)
|
||||
}
|
||||
|
||||
code, out, raw = f.call(t, http.MethodPatch, f.memberPath("u-fin"), `{"blocked":false}`, asAdmin)
|
||||
if code != http.StatusOK || out.Status != "unblocked" || out.Member.Status != "active" {
|
||||
t.Fatalf("unblock: %d %s", code, raw)
|
||||
}
|
||||
if slices.Contains(f.kc.Blocked["u-fin"], f.tenant.ID) || len(f.audit(t, "user.unblocked")) != 1 {
|
||||
t.Errorf("unblock state: %v", f.kc.Blocked)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTeam_blockLogoutFailureIsNotFatal(t *testing.T) {
|
||||
f := newTeamFixture(t, portal)
|
||||
f.kc.LoggedOut = nil
|
||||
// FailNext hits the first Keycloak call; make the logout the one that fails
|
||||
// by blocking through a mock that fails only LogoutUser.
|
||||
kc := &logoutFails{Mock: f.kc}
|
||||
f.s.Keycloak = kc
|
||||
code, out, raw := f.call(t, http.MethodPatch, f.memberPath("u-fin"), `{"blocked":true}`, asAdmin)
|
||||
if code != http.StatusOK || out.SessionsEnded {
|
||||
t.Fatalf("block with failed logout: %d %s", code, raw)
|
||||
}
|
||||
}
|
||||
|
||||
type logoutFails struct{ *keycloak.Mock }
|
||||
|
||||
func (l *logoutFails) LogoutUser(context.Context, string) error { return keycloak.ErrUnavailable }
|
||||
|
||||
func TestTeam_removeAndRevoke(t *testing.T) {
|
||||
f := newTeamFixture(t, portal)
|
||||
code, out, raw := f.call(t, http.MethodDelete, f.memberPath("u-fin"), "", asAdmin)
|
||||
if code != http.StatusOK || out.Status != "removed" || !out.SessionsEnded || len(out.APIKeys) != 0 {
|
||||
t.Fatalf("remove: %d %s", code, raw)
|
||||
}
|
||||
if !slices.Equal(f.kc.Removed, []string{"u-fin"}) || len(f.kc.Deleted) != 0 || !slices.Equal(f.kc.LoggedOut, []string{"u-fin"}) {
|
||||
t.Errorf("keycloak: removed=%v deleted=%v logout=%v", f.kc.Removed, f.kc.Deleted, f.kc.LoggedOut)
|
||||
}
|
||||
if len(f.audit(t, "user.removed")) != 1 {
|
||||
t.Error("user.removed not audited")
|
||||
}
|
||||
|
||||
// A pending invitation the tenant's invite did NOT create: membership only.
|
||||
code, out, raw = f.call(t, http.MethodDelete, f.memberPath("u-inv"), "", asAdmin)
|
||||
if code != http.StatusOK || out.Status != "invite_revoked" || out.UserDeleted {
|
||||
t.Fatalf("revoke (existing account): %d %s", code, raw)
|
||||
}
|
||||
if ev := f.audit(t, "user.invite_revoked"); len(ev) != 1 || ev[0].Metadata["user_deleted"] != false {
|
||||
t.Errorf("audit: %+v", ev)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTeam_revokeDeletesAccountTheInviteCreated(t *testing.T) {
|
||||
f := newTeamFixture(t, portal)
|
||||
f.s.emitAudit(context.Background(), nil, store.AuditEvent{TenantID: f.tenant.ID, Action: "user.invited", TargetID: "inv@acme.test",
|
||||
Metadata: map[string]interface{}{"user_id": "u-inv", "user_created": true}})
|
||||
code, out, raw := f.call(t, http.MethodDelete, f.memberPath("u-inv"), "", asAdmin)
|
||||
if code != http.StatusOK || out.Status != "invite_revoked" || !out.UserDeleted {
|
||||
t.Fatalf("revoke: %d %s", code, raw)
|
||||
}
|
||||
if !slices.Equal(f.kc.Deleted, []string{"u-inv"}) || len(f.kc.LoggedOut) != 0 {
|
||||
t.Errorf("keycloak: deleted=%v logout=%v", f.kc.Deleted, f.kc.LoggedOut)
|
||||
}
|
||||
|
||||
// Member of another org too: the account stays.
|
||||
g := newTeamFixture(t, portal)
|
||||
g.kc.Members["other"] = []keycloak.OrgMember{{UserID: "u-inv", Email: "inv@acme.test"}}
|
||||
g.s.emitAudit(context.Background(), nil, store.AuditEvent{TenantID: g.tenant.ID, Action: "user.invited",
|
||||
Metadata: map[string]interface{}{"user_id": "u-inv", "user_created": true}})
|
||||
if _, out, raw := g.call(t, http.MethodDelete, g.memberPath("u-inv"), "", asAdmin); out.UserDeleted || out.Status != "invite_revoked" {
|
||||
t.Fatalf("revoke (other org): %s", raw)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTeam_resend(t *testing.T) {
|
||||
f := newTeamFixture(t, portal)
|
||||
code, out, raw := f.call(t, http.MethodPost, f.memberPath("u-inv")+"/resend", "", asAdmin)
|
||||
if code != http.StatusAccepted || out.Status != "invite_resent" || !slices.Equal(f.kc.Resent, []string{"inv@acme.test"}) {
|
||||
t.Fatalf("resend: %d %s", code, raw)
|
||||
}
|
||||
if len(f.audit(t, "user.invite_resent")) != 1 {
|
||||
t.Error("resend not audited")
|
||||
}
|
||||
if code, _, raw := f.call(t, http.MethodPost, f.memberPath("u-fin")+"/resend", "", asAdmin); code != http.StatusConflict || !strings.Contains(raw, "not_pending") {
|
||||
t.Errorf("resend to active member: %d %s", code, raw)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTeam_keycloakFailures(t *testing.T) {
|
||||
f := newTeamFixture(t, portal)
|
||||
kc := &failAfterList{Mock: f.kc}
|
||||
f.s.Keycloak = kc
|
||||
for _, c := range []struct{ method, path, body string }{
|
||||
{http.MethodPatch, f.memberPath("u-fin"), `{"role":"CXO"}`},
|
||||
{http.MethodPatch, f.memberPath("u-fin"), `{"blocked":true}`},
|
||||
{http.MethodDelete, f.memberPath("u-fin"), ``},
|
||||
{http.MethodDelete, f.memberPath("u-inv"), ``},
|
||||
{http.MethodPost, f.memberPath("u-inv") + "/resend", ``},
|
||||
} {
|
||||
if code, _, raw := f.call(t, c.method, c.path, c.body, asAdmin); code != http.StatusBadGateway {
|
||||
t.Errorf("%s %s %s: %d %s", c.method, c.path, c.body, code, raw)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// failAfterList lists members normally and fails every write.
|
||||
type failAfterList struct{ *keycloak.Mock }
|
||||
|
||||
func (k *failAfterList) SetMemberRole(context.Context, string, string) error {
|
||||
return io.ErrUnexpectedEOF
|
||||
}
|
||||
func (k *failAfterList) SetMemberBlocked(context.Context, string, string, bool) error {
|
||||
return io.ErrUnexpectedEOF
|
||||
}
|
||||
func (k *failAfterList) RemoveMember(context.Context, string, string, string, bool) (bool, error) {
|
||||
return false, io.ErrUnexpectedEOF
|
||||
}
|
||||
func (k *failAfterList) ResendInvite(context.Context, string, string) error {
|
||||
return io.ErrUnexpectedEOF
|
||||
}
|
||||
|
||||
func TestTeam_userTokens(t *testing.T) {
|
||||
tenantID := "00000000-0000-0000-0000-000000000001"
|
||||
// A plain member may not manage the team.
|
||||
user := &authn.Principal{Subject: "u-fin", ClientID: "cli", TenantID: tenantID, Email: "fin@acme.test", OrgRoles: []string{"FINANCE"}}
|
||||
f := newTeamFixture(t, user)
|
||||
if code, _, raw := f.call(t, http.MethodPatch, f.memberPath("u-inv"), `{"role":"USER"}`, nil); code != http.StatusForbidden || !strings.Contains(raw, "FORBIDDEN_ROLE") {
|
||||
t.Errorf("plain user: %d %s", code, raw)
|
||||
}
|
||||
// An IT_ADMIN token acts with its own identity; the portal header is ignored.
|
||||
admin := &authn.Principal{Subject: "u-admin", ClientID: "cli", TenantID: tenantID, Email: "admin@acme.test", OrgRoles: []string{"IT_ADMIN"}}
|
||||
f = newTeamFixture(t, admin)
|
||||
if code, _, raw := f.call(t, http.MethodDelete, f.memberPath("u-admin"), "", map[string]string{headerPortalUserSubject: "someone"}); code != http.StatusConflict {
|
||||
t.Errorf("admin token self: %d %s", code, raw)
|
||||
}
|
||||
if code, _, raw := f.call(t, http.MethodPatch, f.memberPath("u-fin"), `{"role":"LEGAL"}`, nil); code != http.StatusOK {
|
||||
t.Errorf("admin token: %d %s", code, raw)
|
||||
}
|
||||
if ev := f.audit(t, "user.role_changed"); len(ev) != 1 || ev[0].ActorID != "u-admin" || ev[0].ActorType != "user" {
|
||||
t.Errorf("audit actor: %+v", ev)
|
||||
}
|
||||
// Another tenant's admin: 404.
|
||||
other := &authn.Principal{Subject: "u-x", ClientID: "cli", TenantID: "11111111-1111-1111-1111-111111111111", OrgRoles: []string{"IT_ADMIN"}}
|
||||
f = newTeamFixture(t, other)
|
||||
if code, _, _ := f.call(t, http.MethodDelete, f.memberPath("u-fin"), "", nil); code != http.StatusNotFound {
|
||||
t.Errorf("cross tenant: %d", code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTeam_serviceWithoutPortalUser(t *testing.T) {
|
||||
f := newTeamFixture(t, portal)
|
||||
if code, _, raw := f.call(t, http.MethodPatch, f.memberPath("u-fin"), `{"role":"USER"}`, nil); code != http.StatusOK {
|
||||
t.Fatalf("service: %d %s", code, raw)
|
||||
}
|
||||
if ev := f.audit(t, "user.role_changed"); len(ev) != 1 || ev[0].ActorType != "service" || ev[0].ActorID != "svc-portal" {
|
||||
t.Errorf("audit actor: %+v", ev)
|
||||
}
|
||||
// Auth disabled: no principal at all.
|
||||
g := newTeamFixture(t, nil)
|
||||
if code, _, raw := g.call(t, http.MethodPatch, g.memberPath("u-fin"), `{"role":"USER"}`, nil); code != http.StatusOK {
|
||||
t.Fatalf("no principal: %d %s", code, raw)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTeam_adminRoutes(t *testing.T) {
|
||||
const rules = "portal-svc:tenants,admin;pruefwerk-svc:tenants.read"
|
||||
f := newTeamFixture(t, portal, rules)
|
||||
staff := map[string]string{headerStaffSubject: "staff-1", headerStaffEmail: "ops@breakpilot.test"}
|
||||
base := "/v1/admin/tenants/" + f.tenant.ID + "/members/"
|
||||
if code, _, raw := f.call(t, http.MethodPatch, base+"u-fin", `{"blocked":true}`, staff); code != http.StatusOK {
|
||||
t.Fatalf("staff block: %d %s", code, raw)
|
||||
}
|
||||
if ev := f.audit(t, "user.blocked"); len(ev) != 1 || ev[0].ActorType != "staff" || ev[0].ActorID != "staff-1" || ev[0].ActorName != "ops@breakpilot.test" {
|
||||
t.Errorf("audit actor: %+v", ev)
|
||||
}
|
||||
if code, _, raw := f.call(t, http.MethodPost, base+"u-inv/resend", "", staff); code != http.StatusAccepted {
|
||||
t.Errorf("staff resend: %d %s", code, raw)
|
||||
}
|
||||
if code, _, raw := f.call(t, http.MethodDelete, base+"u-fin", "", staff); code != http.StatusOK {
|
||||
t.Errorf("staff remove: %d %s", code, raw)
|
||||
}
|
||||
if code, _, _ := f.call(t, http.MethodDelete, "/v1/admin/tenants/00000000-0000-0000-0000-0000000000ff/members/u-fin", "", staff); code != http.StatusNotFound {
|
||||
t.Errorf("unknown tenant: %d", code)
|
||||
}
|
||||
// The detail page carries the statuses.
|
||||
rr := httptest.NewRecorder()
|
||||
f.h.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, "/v1/admin/tenants/"+f.tenant.ID, nil))
|
||||
if !strings.Contains(rr.Body.String(), `"status":"invited"`) {
|
||||
t.Errorf("admin detail statuses: %s", rr.Body.String())
|
||||
}
|
||||
|
||||
// A read-only product client may neither manage nor reach admin routes.
|
||||
ro := newTeamFixture(t, &authn.Principal{Subject: "svc2", ClientID: "pruefwerk-svc"}, rules)
|
||||
if code, _, _ := ro.call(t, http.MethodPatch, ro.memberPath("u-fin"), `{"role":"USER"}`, nil); code != http.StatusForbidden {
|
||||
t.Errorf("read client patch: %d", code)
|
||||
}
|
||||
if code, _, _ := ro.call(t, http.MethodDelete, "/v1/admin/tenants/"+ro.tenant.ID+"/members/u-fin", "", nil); code != http.StatusForbidden {
|
||||
t.Errorf("read client admin: %d", code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequireMember(t *testing.T) {
|
||||
tenantID := "00000000-0000-0000-0000-000000000001"
|
||||
user := &authn.Principal{Subject: "u-fin", ClientID: "cli", TenantID: tenantID, Email: "fin@acme.test", OrgRoles: []string{"FINANCE"}}
|
||||
f := newTeamFixture(t, user)
|
||||
now := time.Date(2026, 10, 5, 12, 0, 0, 0, time.UTC)
|
||||
f.s.Now = func() time.Time { return now }
|
||||
get := func() (int, string) {
|
||||
rr := httptest.NewRecorder()
|
||||
f.h.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, "/v1/tenants/"+tenantID+"/members", nil))
|
||||
return rr.Code, rr.Body.String()
|
||||
}
|
||||
if code, raw := get(); code != http.StatusOK {
|
||||
t.Fatalf("member: %d %s", code, raw)
|
||||
}
|
||||
// Blocked behind the registry's back: the cached "not blocked" holds for
|
||||
// blockTTL, then the block bites.
|
||||
f.kc.Blocked["u-fin"] = []string{tenantID}
|
||||
if code, _ := get(); code != http.StatusOK {
|
||||
t.Errorf("cached decision: %d", code)
|
||||
}
|
||||
now = now.Add(blockTTL + time.Second)
|
||||
if code, raw := get(); code != http.StatusForbidden || !strings.Contains(raw, "MEMBER_BLOCKED") {
|
||||
t.Errorf("blocked: %d %s", code, raw)
|
||||
}
|
||||
// A block made through the registry is effective at once.
|
||||
f.kc.Blocked["u-fin"] = nil
|
||||
f.s.blocks.forget("u-fin")
|
||||
if code, _ := get(); code != http.StatusOK {
|
||||
t.Errorf("unblocked: %d", code)
|
||||
}
|
||||
|
||||
// The org_blocked claim alone is enough.
|
||||
claimed := *user
|
||||
claimed.OrgBlocked = []string{tenantID}
|
||||
g := newTeamFixture(t, &claimed)
|
||||
rr := httptest.NewRecorder()
|
||||
g.h.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, "/v1/tenants/"+tenantID+"/members", nil))
|
||||
if rr.Code != http.StatusForbidden {
|
||||
t.Errorf("claim: %d", rr.Code)
|
||||
}
|
||||
|
||||
// Deleted account: refused. Keycloak down: allowed (fails open, logged).
|
||||
g = newTeamFixture(t, user)
|
||||
g.kc.FailNext = keycloak.ErrUserNotFound
|
||||
rr = httptest.NewRecorder()
|
||||
g.h.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, "/v1/tenants/"+tenantID+"/members", nil))
|
||||
if rr.Code != http.StatusForbidden || !strings.Contains(rr.Body.String(), "USER_UNKNOWN") {
|
||||
t.Errorf("deleted user: %d %s", rr.Code, rr.Body.String())
|
||||
}
|
||||
g.kc.FailNext = keycloak.ErrUnavailable
|
||||
rr = httptest.NewRecorder()
|
||||
g.h.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, "/v1/tenants/"+tenantID+"/members", nil))
|
||||
if rr.Code != http.StatusOK {
|
||||
t.Errorf("kc down: %d %s", rr.Code, rr.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestEntitlementCheck_blockedMember(t *testing.T) {
|
||||
f := newTeamFixture(t, portal)
|
||||
ctx := context.Background()
|
||||
tp := store.TenantProduct{TenantID: f.tenant.ID, Product: "pruefwerk", Enabled: true, Config: map[string]interface{}{}}
|
||||
if _, err := f.s.Store.UpsertTenantProduct(ctx, tp); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
check := func(user string) EntitlementCheck {
|
||||
t.Helper()
|
||||
body := `{"tenant_id":"` + f.tenant.ID + `","product":"pruefwerk","user_id":"` + user + `"}`
|
||||
rr := httptest.NewRecorder()
|
||||
f.h.ServeHTTP(rr, httptest.NewRequest(http.MethodPost, "/v1/internal/entitlements/check", strings.NewReader(body)))
|
||||
var out EntitlementCheck
|
||||
_ = json.Unmarshal(rr.Body.Bytes(), &out)
|
||||
return out
|
||||
}
|
||||
if got := check("u-fin"); !got.Allowed {
|
||||
t.Fatalf("member: %+v", got)
|
||||
}
|
||||
f.kc.Blocked["u-blocked"] = []string{f.tenant.ID}
|
||||
if got := check("u-blocked"); got.Allowed || got.Reason != "member_blocked" {
|
||||
t.Errorf("blocked: %+v", got)
|
||||
}
|
||||
f.kc.FailNext = keycloak.ErrUserNotFound
|
||||
if got := check("u-gone"); got.Allowed || got.Reason != "user_unknown" {
|
||||
t.Errorf("unknown: %+v", got)
|
||||
}
|
||||
f.kc.FailNext = keycloak.ErrUnavailable
|
||||
if got := check("u-down"); !got.Allowed {
|
||||
t.Errorf("kc down fails open: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserMemberships_excludeBlocked(t *testing.T) {
|
||||
f := newTeamFixture(t, portal)
|
||||
f.kc.Claims["u-fin"] = keycloak.Claims{TenantID: f.tenant.ID, TenantSlug: "acme", OrgRoles: []string{"FINANCE"}}
|
||||
get := func() string {
|
||||
rr := httptest.NewRecorder()
|
||||
f.h.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, "/v1/users/u-fin/memberships", nil))
|
||||
return rr.Body.String()
|
||||
}
|
||||
if !strings.Contains(get(), `"tenant_slug":"acme"`) {
|
||||
t.Fatal("membership missing")
|
||||
}
|
||||
if code, _, _ := f.call(t, http.MethodPatch, f.memberPath("u-fin"), `{"blocked":true}`, asAdmin); code != http.StatusOK {
|
||||
t.Fatal(code)
|
||||
}
|
||||
if raw := get(); strings.Contains(raw, "acme") {
|
||||
t.Errorf("blocked membership listed: %s", raw)
|
||||
}
|
||||
}
|
||||
+175
-1
@@ -407,6 +407,85 @@ paths:
|
||||
"403": { $ref: "#/components/responses/Forbidden" }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
|
||||
/v1/tenants/{id}/members/{uid}:
|
||||
patch:
|
||||
summary: Change a member's role, or block / unblock the member in this workspace.
|
||||
description: |
|
||||
User tokens need IT_ADMIN or OWNER in their own tenant; service clients the `tenants.write` route group. The portal names the acting person in `X-Portal-User-Subject` / `X-Portal-User-Email`.
|
||||
Send exactly one of `role` or `blocked`. A role change rewrites the
|
||||
member's `org_roles` attribute and takes effect at the member's next
|
||||
login or token refresh. A block is per workspace: the tenant id is
|
||||
added to the member's `org_blocked` user attribute (never
|
||||
`enabled=false`), the member's Keycloak sessions are ended (realm
|
||||
wide) and their active API keys are listed for revocation, not
|
||||
revoked. Guards (409): `self` — nobody changes their own membership;
|
||||
`last_admin` — the last active IT_ADMIN/OWNER cannot be demoted or
|
||||
blocked. Audit: `user.role_changed` (from → to), `user.blocked`,
|
||||
`user.unblocked`.
|
||||
parameters:
|
||||
- { in: path, name: id, required: true, schema: { type: string, format: uuid } }
|
||||
- { in: path, name: uid, required: true, schema: { type: string }, description: Keycloak user id of the member }
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
role: { type: string, enum: [IT_ADMIN, OWNER, CXO, FINANCE, LEGAL, USER] }
|
||||
blocked: { type: boolean }
|
||||
responses:
|
||||
"200":
|
||||
description: Done (or `unchanged`).
|
||||
content:
|
||||
application/json: { schema: { $ref: "#/components/schemas/MemberAction" } }
|
||||
"400": { $ref: "#/components/responses/BadRequest" }
|
||||
"403": { $ref: "#/components/responses/Forbidden" }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
"409": { $ref: "#/components/responses/Conflict" }
|
||||
delete:
|
||||
summary: Remove a member, or revoke a pending invitation.
|
||||
description: |
|
||||
User tokens need IT_ADMIN or OWNER in their own tenant; service clients the `tenants.write` route group. The portal names the acting person in `X-Portal-User-Subject` / `X-Portal-User-Email`.
|
||||
An accepted member loses the organization membership and the
|
||||
workspace attributes; their sessions are ended and their active API
|
||||
keys are listed for revocation (`user.removed`). A pending invitation
|
||||
(no password set yet) is revoked: the membership goes, and the
|
||||
Keycloak account is deleted only when this tenant's invitation created
|
||||
it and it belongs to no other organization — which also voids the
|
||||
link in the invitation mail (`user.invite_revoked`). Guards as for
|
||||
PATCH.
|
||||
parameters:
|
||||
- { in: path, name: id, required: true, schema: { type: string, format: uuid } }
|
||||
- { in: path, name: uid, required: true, schema: { type: string }, description: Keycloak user id of the member }
|
||||
responses:
|
||||
"200":
|
||||
description: Removed or revoked.
|
||||
content:
|
||||
application/json: { schema: { $ref: "#/components/schemas/MemberAction" } }
|
||||
"403": { $ref: "#/components/responses/Forbidden" }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
"409": { $ref: "#/components/responses/Conflict" }
|
||||
|
||||
/v1/tenants/{id}/members/{uid}/resend:
|
||||
post:
|
||||
summary: Send a pending member's invitation mail again.
|
||||
description: |
|
||||
User tokens need IT_ADMIN or OWNER in their own tenant; service clients the `tenants.write` route group. The portal names the acting person in `X-Portal-User-Subject` / `X-Portal-User-Email`.
|
||||
409 `not_pending` when the member has already accepted. Audit:
|
||||
`user.invite_resent`.
|
||||
parameters:
|
||||
- { in: path, name: id, required: true, schema: { type: string, format: uuid } }
|
||||
- { in: path, name: uid, required: true, schema: { type: string }, description: Keycloak user id of the member }
|
||||
responses:
|
||||
"202":
|
||||
description: Sent.
|
||||
content:
|
||||
application/json: { schema: { $ref: "#/components/schemas/MemberAction" } }
|
||||
"403": { $ref: "#/components/responses/Forbidden" }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
"409": { $ref: "#/components/responses/Conflict" }
|
||||
|
||||
/v1/admin/tenants:
|
||||
get:
|
||||
summary: Staff tenant list with search and 30-day activity.
|
||||
@@ -531,6 +610,85 @@ paths:
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
"409": { $ref: "#/components/responses/Conflict" }
|
||||
|
||||
/v1/admin/tenants/{id}/members/{uid}:
|
||||
patch:
|
||||
summary: Change a member's role, or block / unblock the member in this workspace.
|
||||
description: |
|
||||
Staff (route group `admin`); attributed to `X-Staff-Subject` / `X-Staff-Email`.
|
||||
Send exactly one of `role` or `blocked`. A role change rewrites the
|
||||
member's `org_roles` attribute and takes effect at the member's next
|
||||
login or token refresh. A block is per workspace: the tenant id is
|
||||
added to the member's `org_blocked` user attribute (never
|
||||
`enabled=false`), the member's Keycloak sessions are ended (realm
|
||||
wide) and their active API keys are listed for revocation, not
|
||||
revoked. Guards (409): `self` — nobody changes their own membership;
|
||||
`last_admin` — the last active IT_ADMIN/OWNER cannot be demoted or
|
||||
blocked. Audit: `user.role_changed` (from → to), `user.blocked`,
|
||||
`user.unblocked`.
|
||||
parameters:
|
||||
- { in: path, name: id, required: true, schema: { type: string, format: uuid } }
|
||||
- { in: path, name: uid, required: true, schema: { type: string }, description: Keycloak user id of the member }
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
role: { type: string, enum: [IT_ADMIN, OWNER, CXO, FINANCE, LEGAL, USER] }
|
||||
blocked: { type: boolean }
|
||||
responses:
|
||||
"200":
|
||||
description: Done (or `unchanged`).
|
||||
content:
|
||||
application/json: { schema: { $ref: "#/components/schemas/MemberAction" } }
|
||||
"400": { $ref: "#/components/responses/BadRequest" }
|
||||
"403": { $ref: "#/components/responses/Forbidden" }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
"409": { $ref: "#/components/responses/Conflict" }
|
||||
delete:
|
||||
summary: Remove a member, or revoke a pending invitation.
|
||||
description: |
|
||||
Staff (route group `admin`); attributed to `X-Staff-Subject` / `X-Staff-Email`.
|
||||
An accepted member loses the organization membership and the
|
||||
workspace attributes; their sessions are ended and their active API
|
||||
keys are listed for revocation (`user.removed`). A pending invitation
|
||||
(no password set yet) is revoked: the membership goes, and the
|
||||
Keycloak account is deleted only when this tenant's invitation created
|
||||
it and it belongs to no other organization — which also voids the
|
||||
link in the invitation mail (`user.invite_revoked`). Guards as for
|
||||
PATCH.
|
||||
parameters:
|
||||
- { in: path, name: id, required: true, schema: { type: string, format: uuid } }
|
||||
- { in: path, name: uid, required: true, schema: { type: string }, description: Keycloak user id of the member }
|
||||
responses:
|
||||
"200":
|
||||
description: Removed or revoked.
|
||||
content:
|
||||
application/json: { schema: { $ref: "#/components/schemas/MemberAction" } }
|
||||
"403": { $ref: "#/components/responses/Forbidden" }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
"409": { $ref: "#/components/responses/Conflict" }
|
||||
|
||||
/v1/admin/tenants/{id}/members/{uid}/resend:
|
||||
post:
|
||||
summary: Send a pending member's invitation mail again.
|
||||
description: |
|
||||
Staff (route group `admin`); attributed to `X-Staff-Subject` / `X-Staff-Email`.
|
||||
409 `not_pending` when the member has already accepted. Audit:
|
||||
`user.invite_resent`.
|
||||
parameters:
|
||||
- { in: path, name: id, required: true, schema: { type: string, format: uuid } }
|
||||
- { in: path, name: uid, required: true, schema: { type: string }, description: Keycloak user id of the member }
|
||||
responses:
|
||||
"202":
|
||||
description: Sent.
|
||||
content:
|
||||
application/json: { schema: { $ref: "#/components/schemas/MemberAction" } }
|
||||
"403": { $ref: "#/components/responses/Forbidden" }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
"409": { $ref: "#/components/responses/Conflict" }
|
||||
|
||||
/v1/admin/tenants/{id}/reprovision:
|
||||
post:
|
||||
summary: Repair a tenant's sign-in when its Keycloak organization or admin account is missing.
|
||||
@@ -825,6 +983,7 @@ paths:
|
||||
tenant_id: { type: string, format: uuid }
|
||||
product: { type: string }
|
||||
addon: { type: string, description: "add-on id from the catalog, e.g. werkbank" }
|
||||
user_id: { type: string, description: "optional Keycloak user id; a member blocked in the tenant gets reason member_blocked (portal#74)" }
|
||||
responses:
|
||||
"200":
|
||||
description: Decision.
|
||||
@@ -1460,7 +1619,7 @@ components:
|
||||
status: { $ref: "#/components/schemas/TenantStatus" }
|
||||
limits: { type: object, additionalProperties: true, description: "tenant_products.config — purchased limits" }
|
||||
expires_at: { type: string, format: date-time, nullable: true }
|
||||
reason: { type: string, enum: [unknown_product, unknown_addon, tenant_not_found, tenant_archived, tenant_halted, entitlement_disabled, entitlement_expired, addon_not_purchased, not_entitled] }
|
||||
reason: { type: string, enum: [unknown_product, unknown_addon, tenant_not_found, tenant_archived, tenant_halted, entitlement_disabled, entitlement_expired, addon_not_purchased, not_entitled, member_blocked, user_unknown] }
|
||||
|
||||
ProductAddon:
|
||||
type: object
|
||||
@@ -1609,6 +1768,21 @@ components:
|
||||
items: { type: string }
|
||||
enabled: { type: boolean }
|
||||
created_at: { type: string, format: date-time, nullable: true }
|
||||
pending: { type: boolean, description: "invitation not accepted yet (no password, no identity-provider link)" }
|
||||
status: { type: string, enum: [invited, active, blocked], description: "status in this tenant (portal#74)" }
|
||||
|
||||
MemberAction:
|
||||
type: object
|
||||
required: [status]
|
||||
properties:
|
||||
status: { type: string, enum: [role_changed, unchanged, blocked, unblocked, removed, invite_revoked, invite_resent] }
|
||||
member: { $ref: "#/components/schemas/OrgMember" }
|
||||
user_deleted: { type: boolean, description: "revoking the invitation also deleted the account" }
|
||||
sessions_ended: { type: boolean }
|
||||
api_keys:
|
||||
type: array
|
||||
description: The member's active API keys in this tenant, offered for revocation.
|
||||
items: { $ref: "#/components/schemas/APIKey" }
|
||||
|
||||
Invite:
|
||||
type: object
|
||||
|
||||
Reference in new issue
Block a user