auth

Main authentication module for my projects
git clone git://git.finwo.net/app/auth
Log | Files | Refs

commit 86d739d17a8a70b7fab4159a6d9ad57efaf013d3
parent 07ce0aa3a1e939e66085641df52a72975e454d94
Author: finwo <finwo@pm.me>
Date:   Wed, 28 Oct 2026 16:18:19 +0100

Added realm membership management

Diffstat:
Mapp/admin/src/assets/admin.css | 2+-
Mapp/admin/src/screen/user.tsx | 291++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Mapp/admin/src/screen/users.tsx | 183++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mapp/admin/src/util/api.ts | 41+++++++++++++++++++++++++++++++++++++++++
Mapp/admin/src/util/auth.ts | 58++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mmockup/plain/admin-user-detail.html | 84+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mmockup/plain/admin-users.html | 100+++++++++++++++++++++++++++++++++++++++++++++++--------------------------------
Mmockup/plain/global.css | 34+++++++++++++++++++++++++++++++++-
Aserver/src/controller/admin/users/create.js | 38++++++++++++++++++++++++++++++++++++++
Mserver/src/controller/admin/users/get.js | 14++++++++------
Aserver/src/controller/admin/users/lookup.js | 26++++++++++++++++++++++++++
Aserver/src/controller/admin/users/membership.js | 25+++++++++++++++++++++++++
Aserver/src/controller/admin/users/roles.js | 25+++++++++++++++++++++++++
Mserver/src/lib/admin-users.js | 659++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
Mserver/src/lib/bans.js | 9++++++++-
Mserver/src/lib/session.js | 15+++++++++++++++
Mserver/src/lib/users.js | 36++++++++++++++++++++++++++++++++++++
Mserver/test/http.test.js | 475+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
18 files changed, 1956 insertions(+), 159 deletions(-)

diff --git a/app/admin/src/assets/admin.css b/app/admin/src/assets/admin.css @@ -6,7 +6,7 @@ .realm-select > span { color: var(--muted); font-size: 0.75rem; - line-height: 1.4; + line-height: 1.15; } .realm-select select { diff --git a/app/admin/src/screen/user.tsx b/app/admin/src/screen/user.tsx @@ -6,13 +6,17 @@ import { createAdminUserBan, deleteAdminUserBan, loadAdminClients, + loadAdminRoles, loadAdminUserDetail, revokeAdminUserConsent, + updateAdminRealmMembership, + updateAdminRealmUserRoles, } from '../util/auth'; import { appUrl, type AdminClient, type AdminRealm, + type AdminRole, type AdminUserBan, type AdminUserConsent, type AdminUserDetail, @@ -51,21 +55,31 @@ function banLabel(ban: AdminUserBan) { return ban.client_id === '*' ? 'All apps' : ban.client_name || ban.client_id; } -function membershipLabel(detail: AdminUserDetail) { - const relationship = detail.user.relationship === 'home' ? 'Home realm' : 'Guest'; - const status = detail.user.membership_status; - return status && status !== 'active' ? `${relationship} ยท ${status}` : relationship; +function roleLabel(role: AdminRole) { + return role.name || role.slug; +} + +function changedRoles(current: string[], selected: string[]) { + return current.length !== selected.length || current.some((role) => !selected.includes(role)); +} + +function changedAdminRole(current: string[], selected: string[]) { + return current.includes('realm-admin') !== selected.includes('realm-admin'); +} + +function membershipActionLabel(status: string | null) { + return status === 'suspended' ? 'Reactivate member' : 'Suspend member'; +} + +function membershipStatusLabel(status: string | null) { + if (!status) return 'Not a member'; + return status[0].toUpperCase() + status.slice(1); } function statusLabel(detail: AdminUserDetail) { if (detail.user.status !== 'active') { return detail.user.status === 'disabled' ? 'Disabled' : detail.user.status; } - if (detail.user.membership_status && detail.user.membership_status !== 'active') { - const status = detail.user.membership_status; - return status[0].toUpperCase() + status.slice(1); - } - if (detail.user.banned) return 'Banned'; return 'Active'; } @@ -76,10 +90,16 @@ export const UserPage: m.Component<UserAttrs> = { redirecting: false, detail: null as AdminUserDetail | null, clients: [] as AdminClient[], + roles: [] as AdminRole[], + selectedRoles: [] as string[], error: null as Error | null, notice: null as string | null, confirm: null as UserConfirm | null, pendingAction: false, + membershipConfirm: false, + membershipPending: false, + roleConfirm: false, + rolePending: false, banOpen: false, banClientId: '*', banPending: false, @@ -121,10 +141,16 @@ export const UserPage: m.Component<UserAttrs> = { this.loadedKey = key; this.detail = null; this.clients = []; + this.roles = []; + this.selectedRoles = []; this.error = null; this.notice = null; this.confirm = null; this.pendingAction = false; + this.membershipConfirm = false; + this.membershipPending = false; + this.roleConfirm = false; + this.rolePending = false; this.banOpen = false; this.banClientId = '*'; this.banPending = false; @@ -138,13 +164,16 @@ export const UserPage: m.Component<UserAttrs> = { m.redraw(); try { - const [detail, clients] = await Promise.all([ + const [detail, clients, roles] = await Promise.all([ loadAdminUserDetail(realmSlug, userId), loadAdminClients(realmSlug), + loadAdminRoles(realmSlug), ]); if (this.loadedKey === detailKey(realmSlug, userId)) { this.detail = detail; this.clients = clients; + this.roles = roles; + this.selectedRoles = [...detail.user.roles]; } } catch (e: any) { if (this.loadedKey !== detailKey(realmSlug, userId)) return; @@ -221,6 +250,86 @@ export const UserPage: m.Component<UserAttrs> = { } }, + cancelAccessActions(this: any) { + this.membershipConfirm = false; + this.roleConfirm = false; + if (this.detail) this.selectedRoles = [...this.detail.user.roles]; + m.redraw(); + }, + + applyMembershipUpdate(this: any, response: any) { + this.detail = response; + this.selectedRoles = [...response.user.roles]; + this.membershipConfirm = false; + this.notice = + response.user.membership_status === 'suspended' + ? 'Membership suspended. Existing realm access was revoked.' + : 'Membership reactivated. Previously revoked authorizations were not restored.'; + }, + + async submitMembership(this: any) { + const { realmSlug, userId } = this.attrs; + if (!realmSlug || !userId || !this.detail) return; + + const status = this.detail.user.membership_status === 'suspended' ? 'active' : 'suspended'; + this.membershipPending = true; + this.error = null; + this.notice = null; + + try { + const response = await updateAdminRealmMembership(realmSlug, userId, status); + this.applyMembershipUpdate(response); + } catch (e: any) { + if (e?.status === 401 || e?.status === 400) { + this.attrs.onAuthExpired(); + return; + } + this.error = e as Error; + } finally { + this.membershipPending = false; + m.redraw(); + } + }, + + async submitRoles(this: any) { + const { realmSlug, userId } = this.attrs; + if (!realmSlug || !userId || !this.detail) return; + + this.rolePending = true; + this.error = null; + this.notice = null; + + try { + const response = await updateAdminRealmUserRoles( + realmSlug, + userId, + [...this.selectedRoles].sort() + ); + this.detail = response; + this.selectedRoles = [...response.user.roles]; + this.roleConfirm = false; + this.notice = 'Realm roles updated.'; + } catch (e: any) { + if (e?.status === 401 || e?.status === 400) { + this.attrs.onAuthExpired(); + return; + } + this.error = e as Error; + } finally { + this.rolePending = false; + m.redraw(); + } + }, + + requestRoleSave(this: any) { + if (!this.detail) return; + if (changedAdminRole(this.detail.user.roles, this.selectedRoles)) { + this.roleConfirm = true; + } else { + this.submitRoles(); + } + }, + view(this: any) { const { realms, realmsError, realmSlug, userId } = this.attrs; const selected = @@ -308,18 +417,10 @@ export const UserPage: m.Component<UserAttrs> = { <dd>{detail.user.email || 'No verified email'}</dd> </div> <div> - <dt>Realm membership</dt> - <dd>{membershipLabel(detail)}</dd> - </div> - <div> <dt>Status</dt> <dd>{statusLabel(detail)}</dd> </div> <div> - <dt>Roles</dt> - <dd>{detail.user.roles.length ? detail.user.roles.join(', ') : 'None'}</dd> - </div> - <div> <dt>System admin</dt> <dd>{detail.user.is_system_admin ? 'Yes' : 'No'}</dd> </div> @@ -332,6 +433,106 @@ export const UserPage: m.Component<UserAttrs> = { <section class="panel"> <div class="panel-header"> + <div> + <h2>Realm access</h2> + <p class="note">Manage membership and roles in this realm.</p> + </div> + {detail.permissions.can_suspend_membership || + detail.permissions.can_reactivate_membership ? ( + <button + class={ + detail.permissions.can_suspend_membership ? 'button-danger' : 'button-secondary' + } + type="button" + disabled={this.membershipPending} + onclick={() => { + if (detail.permissions.can_reactivate_membership) { + this.submitMembership(); + } else { + this.membershipConfirm = true; + m.redraw(); + } + }} + > + {this.membershipPending + ? 'Applying' + : membershipActionLabel(detail.user.membership_status)} + </button> + ) : null} + </div> + <dl class="details"> + <div> + <dt>Relationship</dt> + <dd>{detail.user.relationship === 'home' ? 'Home realm' : 'Guest'}</dd> + </div> + <div> + <dt>Membership</dt> + <dd>{membershipStatusLabel(detail.user.membership_status)}</dd> + </div> + </dl> + {detail.permissions.last_active_realm_admin ? ( + <div class="notice"> + This is the only active realm administrator. System admins can still remove + this access. + </div> + ) : null} + <fieldset class="role-field"> + <legend>Realm roles</legend> + {this.roles.length === 0 ? ( + <p class="note">No realm roles are available.</p> + ) : ( + <div class="checkbox-list"> + {this.roles.map((role: AdminRole) => { + const checked = this.selectedRoles.includes(role.slug); + const protectedRole = + !detail.permissions.can_edit_roles || + (detail.permissions.last_active_realm_admin && + !detail.permissions.can_remove_last_realm_admin && + role.slug === 'realm-admin' && + detail.user.roles.includes(role.slug)); + return ( + <label class="checkbox-row"> + <input + type="checkbox" + checked={checked} + disabled={protectedRole} + onchange={(event: Event) => { + const selected = new Set(this.selectedRoles); + if ((event.target as HTMLInputElement).checked) { + selected.add(role.slug); + } else { + selected.delete(role.slug); + } + this.selectedRoles = [...selected].sort(); + m.redraw(); + }} + /> + <span>{roleLabel(role)}</span> + </label> + ); + })} + </div> + )} + </fieldset> + {detail.permissions.can_edit_roles ? ( + <div class="modal-actions"> + <button + class="button" + type="button" + disabled={ + this.rolePending || + !changedRoles(detail.user.roles, this.selectedRoles) + } + onclick={() => this.requestRoleSave()} + > + {this.rolePending ? 'Saving roles' : 'Save roles'} + </button> + </div> + ) : null} + </section> + + <section class="panel"> + <div class="panel-header"> <h2>Application consents</h2> </div> {detail.consents.length === 0 ? ( @@ -559,6 +760,60 @@ export const UserPage: m.Component<UserAttrs> = { </div> </Modal> ) : null} + + {this.membershipConfirm && detail ? ( + <Modal title="Suspend membership" onClose={() => this.cancelAccessActions()}> + <p class="modal-note"> + Suspending {displayName} revokes realm consents, refresh tokens and session + bindings. Reactivating the membership does not restore those authorizations. + </p> + <div class="modal-actions"> + <button + class="button-secondary" + type="button" + disabled={this.membershipPending} + onclick={() => this.cancelAccessActions()} + > + Cancel + </button> + <button + class="button-danger" + type="button" + disabled={this.membershipPending} + onclick={() => this.submitMembership()} + > + {this.membershipPending ? 'Suspending' : 'Suspend member'} + </button> + </div> + </Modal> + ) : null} + + {this.roleConfirm && detail ? ( + <Modal title="Update realm roles" onClose={() => this.cancelAccessActions()}> + <p class="modal-note"> + Realm-admin access is re-read from the realm database on each request. Changing + this role can immediately alter who can administer {selected?.display_name}. + </p> + <div class="modal-actions"> + <button + class="button-secondary" + type="button" + disabled={this.rolePending} + onclick={() => this.cancelAccessActions()} + > + Cancel + </button> + <button + class="button" + type="button" + disabled={this.rolePending} + onclick={() => this.submitRoles()} + > + {this.rolePending ? 'Saving roles' : 'Save roles'} + </button> + </div> + </Modal> + ) : null} </div> ); }, diff --git a/app/admin/src/screen/users.tsx b/app/admin/src/screen/users.tsx @@ -1,14 +1,21 @@ import { Users } from 'lucide'; import m from 'mithril'; import { Icon } from '@component/icon'; +import { Modal } from '@component/modal'; import { PageHeader } from '@component/page-header'; import { RealmSelector } from '../component/realm-selector'; -import { loadAdminGlobalUsers, loadAdminUsers } from '../util/auth'; +import { + addAdminRealmMember, + loadAdminGlobalUsers, + loadAdminUsers, + lookupAdminRealmUser, +} from '../util/auth'; import { appUrl, type AdminGlobalUser, type AdminRealm, type AdminRealmUser, + type AdminUserLookup, } from '../util/api'; interface UsersAttrs { @@ -55,6 +62,14 @@ function userHref(isGlobal: boolean, realmSlug: string | null, userId: string) { return `/users/${encodeURIComponent(realmSlug || '')}/${encodedUser}`; } +function lookupReason(result: AdminUserLookup) { + if (result.reason === 'user_disabled') return 'This global account is disabled.'; + if (result.relationship === 'home') return 'This user is already a home-realm member.'; + if (result.relationship === 'guest') return 'This user is already a guest member.'; + if (result.reason) return 'This user cannot be added to the realm.'; + return 'No membership in this realm.'; +} + export const UsersPage: m.Component<UsersAttrs> = { attrs: null as UsersAttrs | null, loadedScope: null as string | null, @@ -63,6 +78,11 @@ export const UsersPage: m.Component<UsersAttrs> = { users: null as AnyUser[] | null, search: '', error: null as Error | null, + addOpen: false, + addIdentifier: '', + addResult: null as AdminUserLookup | null, + addPending: false, + addError: null as Error | null, oninit(this: any, vnode: m.Vnode<UsersAttrs>) { this.attrs = vnode.attrs; @@ -105,10 +125,19 @@ export const UsersPage: m.Component<UsersAttrs> = { if (this.loadedScope !== scope) { this.search = ''; this.error = null; + this.resetAdd(); this.load(scope); } }, + resetAdd(this: any) { + this.addOpen = false; + this.addIdentifier = ''; + this.addResult = null; + this.addPending = false; + this.addError = null; + }, + async load(this: any, scope: string) { this.loadedScope = scope; this.loading = true; @@ -132,6 +161,63 @@ export const UsersPage: m.Component<UsersAttrs> = { } }, + async searchAdd(this: any) { + const realmSlug = this.attrs?.realmSlug; + const identifier = this.addIdentifier.trim(); + if (!realmSlug || !identifier) { + this.addError = new Error('Enter an exact email or username'); + m.redraw(); + return; + } + + this.addPending = true; + this.addError = null; + this.addResult = null; + m.redraw(); + + try { + const result = await lookupAdminRealmUser(realmSlug, identifier); + if (this.attrs?.realmSlug === realmSlug) this.addResult = result; + } catch (e: any) { + if (e?.status === 401 || e?.status === 400) { + this.attrs?.onAuthExpired(); + return; + } + this.addError = e as Error; + } finally { + this.addPending = false; + m.redraw(); + } + }, + + async submitAdd(this: any) { + const realmSlug = this.attrs?.realmSlug; + const result = this.addResult; + if (!realmSlug || !result?.can_add) return; + + this.addPending = true; + this.addError = null; + m.redraw(); + + try { + await addAdminRealmMember(realmSlug, result.id); + this.resetAdd(); + m.route.set(userHref(false, realmSlug, result.id)); + } catch (e: any) { + if (e?.status === 401 || e?.status === 400) { + this.attrs?.onAuthExpired(); + return; + } + this.addError = e as Error; + if (e?.status === 409) { + this.addResult = null; + } + } finally { + this.addPending = false; + m.redraw(); + } + }, + view(this: any) { const { realms, realmsError, isSystemAdmin, isGlobal, realmSlug } = this.attrs; const selected = isGlobal @@ -195,6 +281,21 @@ export const UsersPage: m.Component<UsersAttrs> = { }} /> </div> + {!isGlobal ? ( + <div class="table-actions"> + <button + class="button" + type="button" + onclick={() => { + this.resetAdd(); + this.addOpen = true; + m.redraw(); + }} + > + Add user + </button> + </div> + ) : null} </div> {this.loading || this.redirecting || !this.users ? ( @@ -297,6 +398,86 @@ export const UsersPage: m.Component<UsersAttrs> = { )} </div> )} + + {this.addOpen && realmSlug ? ( + <Modal title="Add user" onClose={() => this.resetAdd()}> + <form + onsubmit={(event: Event) => { + event.preventDefault(); + this.searchAdd(); + }} + > + <div class="form-field"> + <label class="field-label" for="add-user-identifier"> + Email or username + </label> + <input + id="add-user-identifier" + class="field-control" + value={this.addIdentifier} + data-modal-autofocus + oninput={(event: Event) => { + this.addIdentifier = (event.target as HTMLInputElement).value; + }} + /> + </div> + <div class="modal-actions"> + <button + class="button-secondary" + type="button" + disabled={this.addPending} + onclick={() => this.resetAdd()} + > + Cancel + </button> + <button class="button" type="submit" disabled={this.addPending}> + {this.addPending ? 'Searching' : 'Search'} + </button> + </div> + </form> + + {this.addError ? ( + <div class="alert" role="alert"> + {this.addError.message} + </div> + ) : null} + + {this.addResult ? ( + <div> + <div class="notice"> + <strong>{this.addResult.display_name || this.addResult.username}</strong> + {this.addResult.email ? ( + <span class="data-table-sub">{this.addResult.email}</span> + ) : null} + <span class="data-table-sub">{this.addResult.username}</span> + <span class="data-table-sub">{lookupReason(this.addResult)}</span> + </div> + <div class="modal-actions"> + {this.addResult.can_add ? ( + <button + class="button" + type="button" + disabled={this.addPending} + onclick={() => this.submitAdd()} + > + {this.addPending ? 'Adding user' : 'Add user'} + </button> + ) : ( + <button + class="button-secondary" + type="button" + onclick={() => + m.route.set(userHref(false, realmSlug, this.addResult.id)) + } + > + Open user + </button> + )} + </div> + </div> + ) : null} + </Modal> + ) : null} </div> ); }, diff --git a/app/admin/src/util/api.ts b/app/admin/src/util/api.ts @@ -99,6 +99,17 @@ export interface AdminUserBan { created_at: number; } +export interface AdminUserPermissions { + is_self: boolean; + can_manage_membership: boolean; + can_suspend_membership: boolean; + can_reactivate_membership: boolean; + can_edit_roles: boolean; + can_remove_last_realm_admin: boolean; + last_active_realm_admin: boolean; + reason: string | null; +} + export interface AdminUserDetail { user: { id: string; @@ -119,6 +130,36 @@ export interface AdminUserDetail { }; consents: AdminUserConsent[]; bans: AdminUserBan[]; + permissions: AdminUserPermissions; +} + +export interface AdminUserMutationResponse extends AdminUserDetail { + ok: boolean; +} + +export interface AdminUserLookup { + id: string; + username: string; + display_name: string; + email: string | null; + status: string; + is_system_admin: boolean; + home_realm_slug: string | null; + relationship: 'home' | 'guest' | 'none'; + membership_status: string | null; + roles: string[]; + can_add: boolean; + reason: string | null; +} + +export interface AdminRealmAccessRevoked { + consents: number; + refresh_tokens: number; + session_realms: number; +} + +export interface AdminUserMembershipUpdateResponse extends AdminUserMutationResponse { + revoked: AdminRealmAccessRevoked; } export interface AdminMeUser { diff --git a/app/admin/src/util/auth.ts b/app/admin/src/util/auth.ts @@ -18,6 +18,9 @@ import { type AdminSession, type AdminUserBan, type AdminUserDetail, + type AdminUserLookup, + type AdminUserMembershipUpdateResponse, + type AdminUserMutationResponse, } from './api'; export type AdminTokens = StoredTokens; @@ -220,3 +223,58 @@ export async function deleteAdminUserBan( method: 'DELETE', }); } + +export async function lookupAdminRealmUser( + realmSlug: string, + identifier: string +): Promise<AdminUserLookup> { + const realm = encodeURIComponent(realmSlug); + const query = new URLSearchParams({ identifier }); + const response = await adminJson<{ user: AdminUserLookup }>( + `/api/v1/admin/realms/${realm}/user-lookup?${query}` + ); + return response.user; +} + +export async function addAdminRealmMember( + realmSlug: string, + userId: string +): Promise<AdminUserMutationResponse> { + const realm = encodeURIComponent(realmSlug); + return adminJson<AdminUserMutationResponse>(`/api/v1/admin/realms/${realm}/users`, { + method: 'POST', + body: JSON.stringify({ user_id: userId }), + }); +} + +export async function updateAdminRealmMembership( + realmSlug: string, + userId: string, + status: 'active' | 'suspended' +): Promise<AdminUserMembershipUpdateResponse> { + const realm = encodeURIComponent(realmSlug); + const user = encodeURIComponent(userId); + return adminJson<AdminUserMembershipUpdateResponse>( + `/api/v1/admin/realms/${realm}/users/${user}/membership`, + { + method: 'PATCH', + body: JSON.stringify({ status }), + } + ); +} + +export async function updateAdminRealmUserRoles( + realmSlug: string, + userId: string, + roles: string[] +): Promise<AdminUserMutationResponse> { + const realm = encodeURIComponent(realmSlug); + const user = encodeURIComponent(userId); + return adminJson<AdminUserMutationResponse>( + `/api/v1/admin/realms/${realm}/users/${user}/roles`, + { + method: 'PUT', + body: JSON.stringify({ roles }), + } + ); +} diff --git a/mockup/plain/admin-user-detail.html b/mockup/plain/admin-user-detail.html @@ -171,6 +171,42 @@ <section class="panel"> <div class="panel-header"> + <div> + <h2>Realm access</h2> + <p class="note">Manage membership and roles in Acme.</p> + </div> + <button class="button-danger" type="button" data-dialog-open="member-suspend-dialog"> + Suspend member + </button> + </div> + <dl class="details"> + <div> + <dt>Relationship</dt> + <dd>Home realm</dd> + </div> + <div> + <dt>Membership</dt> + <dd>Active</dd> + </div> + </dl> + <fieldset class="role-field"> + <legend>Realm roles</legend> + <div class="checkbox-list"> + <label class="checkbox-row"> + <input type="checkbox" checked /> + <span>Realm administrator</span> + </label> + </div> + </fieldset> + <div class="modal-actions"> + <button class="button" type="button" data-dialog-open="role-save-dialog"> + Save roles + </button> + </div> + </section> + + <section class="panel"> + <div class="panel-header"> <h2>Application consents</h2> </div> <div class="data-table-wrap"> @@ -369,6 +405,54 @@ </div> </div> + <div id="member-suspend-dialog" class="modal-overlay" hidden> + <div class="modal" role="dialog" aria-modal="true" aria-labelledby="member-suspend-title"> + <div class="modal-header"> + <h2 id="member-suspend-title">Suspend membership</h2> + <button class="modal-close" type="button" aria-label="Close dialog" data-dialog-close> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <path d="M18 6 6 18" /> + <path d="m6 6 12 12" /> + </svg> + </button> + </div> + <div class="modal-body"> + <p class="modal-note"> + Suspending Alice revokes realm consents, refresh tokens and session bindings. + Reactivating the membership does not restore those authorizations. + </p> + <div class="modal-actions"> + <button class="button-secondary" type="button" data-dialog-close>Cancel</button> + <button class="button-danger" type="button" data-dialog-close>Suspend member</button> + </div> + </div> + </div> + </div> + + <div id="role-save-dialog" class="modal-overlay" hidden> + <div class="modal" role="dialog" aria-modal="true" aria-labelledby="role-save-title"> + <div class="modal-header"> + <h2 id="role-save-title">Update realm roles</h2> + <button class="modal-close" type="button" aria-label="Close dialog" data-dialog-close> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <path d="M18 6 6 18" /> + <path d="m6 6 12 12" /> + </svg> + </button> + </div> + <div class="modal-body"> + <p class="modal-note"> + Granting or revoking realm-admin changes the administrative access that is re-read + from the realm database on each request. + </p> + <div class="modal-actions"> + <button class="button-secondary" type="button" data-dialog-close>Cancel</button> + <button class="button" type="button" data-dialog-close>Save roles</button> + </div> + </div> + </div> + </div> + <div class="mockup-controls" aria-label="Mockup theme"> <span class="mockup-label">Mockup</span> <button class="mockup-button is-active" type="button" data-theme-target="auto">Auto</button> diff --git a/mockup/plain/admin-users.html b/mockup/plain/admin-users.html @@ -114,13 +114,13 @@ <div class="page-header page-header-row"> <div> <h1>Users</h1> - <p>All global user identities.</p> + <p>Home and guest members in this realm.</p> </div> <label class="realm-select"> <span>Realm</span> - <select class="field-control"> - <option selected>All realms</option> - <option>Acme</option> + <select> + <option>All realms</option> + <option selected>Acme</option> <option>Globex</option> </select> </label> @@ -132,6 +132,9 @@ <div class="table-search"> <input id="user-search" type="search" aria-label="Search users" placeholder="Search users" /> </div> + <div class="table-actions"> + <button class="button" type="button" data-dialog-open="user-add-dialog">Add user</button> + </div> </div> <div class="data-table-wrap"> @@ -140,13 +143,13 @@ <tr> <th class="table-icon-column" scope="col"><span class="sr-only">User</span></th> <th class="data-table-primary" scope="col">User</th> - <th scope="col">Home realm</th> - <th scope="col">Realms</th> + <th scope="col">Membership</th> + <th scope="col">Roles</th> <th scope="col">Status</th> </tr> </thead> <tbody id="user-rows"> - <tr data-row-href="./admin-user-global-detail.html" data-search="alice alice alice@acme.test acme 2 active"> + <tr data-row-href="./admin-user-detail.html" data-search="alice alice alice@acme.test home realm user active"> <td> <span class="table-icon" aria-hidden="true"> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> @@ -156,15 +159,15 @@ </span> </td> <td class="data-table-primary"> - <a href="./admin-user-global-detail.html">Alice</a> + <a href="./admin-user-detail.html">Alice</a> <span class="data-table-sub">alice@acme.test</span> <span class="data-table-sub">alice</span> </td> - <td>acme</td> - <td>2</td> + <td>Home</td> + <td>None</td> <td>Active</td> </tr> - <tr data-row-href="./admin-user-global-detail.html" data-search="acme it acme-it it@acme.test acme 1 realm-admin active"> + <tr data-row-href="./admin-user-detail.html" data-search="acme it acme-it it@acme.test home realm-admin active"> <td> <span class="table-icon" aria-hidden="true"> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> @@ -174,15 +177,15 @@ </span> </td> <td class="data-table-primary"> - <a href="./admin-user-global-detail.html">Acme IT</a> + <a href="./admin-user-detail.html">Acme IT</a> <span class="data-table-sub">it@acme.test</span> <span class="data-table-sub">acme-it</span> </td> - <td>acme <span class="data-table-status">Realm admin</span></td> - <td>1</td> + <td>Home</td> + <td><span class="data-table-status">Realm admin</span></td> <td>Active</td> </tr> - <tr data-row-href="./admin-user-global-detail.html" data-search="guest user guest guest@personal.test none 1 active"> + <tr data-row-href="./admin-user-detail.html" data-search="guest user guest guest@personal.test guest active"> <td> <span class="table-icon" aria-hidden="true"> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> @@ -192,33 +195,15 @@ </span> </td> <td class="data-table-primary"> - <a href="./admin-user-global-detail.html">Guest User</a> + <a href="./admin-user-detail.html">Guest User</a> <span class="data-table-sub">guest@personal.test</span> <span class="data-table-sub">guest</span> </td> + <td>Guest</td> <td>None</td> - <td>1</td> - <td>Active</td> - </tr> - <tr data-row-href="./admin-user-global-detail.html" data-search="contractor contractor contractor@personal.test none 1 realm-admin active"> - <td> - <span class="table-icon" aria-hidden="true"> - <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> - <path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2" /> - <circle cx="12" cy="7" r="4" /> - </svg> - </span> - </td> - <td class="data-table-primary"> - <a href="./admin-user-global-detail.html">Contractor</a> - <span class="data-table-sub">contractor@personal.test</span> - <span class="data-table-sub">contractor</span> - </td> - <td>None <span class="data-table-status">Realm admin</span></td> - <td>1</td> <td>Active</td> </tr> - <tr data-row-href="./admin-user-global-detail.html" data-search="system admin admin admin@system.test none 0 system-admin active"> + <tr data-row-href="./admin-user-detail.html" data-search="carol carol carol@example.test guest realm user active"> <td> <span class="table-icon" aria-hidden="true"> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> @@ -228,12 +213,12 @@ </span> </td> <td class="data-table-primary"> - <a href="./admin-user-global-detail.html">System Admin</a> - <span class="data-table-sub">admin@system.test</span> - <span class="data-table-sub">admin</span> + <a href="./admin-user-detail.html">Carol</a> + <span class="data-table-sub">carol@example.test</span> + <span class="data-table-sub">carol</span> </td> - <td>None <span class="data-table-status">System admin</span></td> - <td>0</td> + <td>Guest</td> + <td>None</td> <td>Active</td> </tr> </tbody> @@ -247,6 +232,39 @@ </div> </div> + <div id="user-add-dialog" class="modal-overlay" hidden> + <div class="modal" role="dialog" aria-modal="true" aria-labelledby="user-add-title"> + <div class="modal-header"> + <h2 id="user-add-title">Add user</h2> + <button class="modal-close" type="button" aria-label="Close dialog" data-dialog-close> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <path d="M18 6 6 18" /> + <path d="m6 6 12 12" /> + </svg> + </button> + </div> + <div class="modal-body"> + <label class="form-field"> + <span class="field-label">Email or username</span> + <input class="field-control" value="carol@example.test" /> + </label> + <div class="notice" role="status"> + <strong>Carol</strong> + <span class="data-table-sub">carol@example.test</span> + <span class="data-table-sub">No membership in Acme</span> + </div> + <p class="modal-note"> + Exact email or username required. Adding Carol creates a guest membership without + roles. + </p> + <div class="modal-actions"> + <button class="button-secondary" type="button" data-dialog-close>Cancel</button> + <button class="button" type="button" data-dialog-close>Add user</button> + </div> + </div> + </div> + </div> + <div class="mockup-controls" aria-label="Mockup theme"> <span class="mockup-label">Mockup</span> <button class="mockup-button is-active" type="button" data-theme-target="auto">Auto</button> diff --git a/mockup/plain/global.css b/mockup/plain/global.css @@ -503,7 +503,7 @@ body { .realm-select > span { color: var(--muted); font-size: 0.75rem; - line-height: 1.4; + line-height: 1.15; } .realm-select select { @@ -828,6 +828,38 @@ select.field-control, padding-right: 2.25rem; } +.role-field { + margin: 0; + padding: 0; + border: 0; +} + +.role-field legend { + margin-bottom: 0.5rem; + padding: 0; + color: var(--muted); + font-size: 0.75rem; + line-height: 1.4; +} + +.checkbox-list { + display: grid; + gap: 0.5rem; +} + +.checkbox-row { + display: flex; + align-items: center; + gap: 0.5rem; + font-size: 0.875rem; + line-height: 1.5; +} + +.checkbox-row input { + width: 1rem; + height: 1rem; +} + a:focus-visible, button:focus-visible, summary:focus-visible { diff --git a/server/src/controller/admin/users/create.js b/server/src/controller/admin/users/create.js @@ -0,0 +1,38 @@ +import { app } from '../../../app.js'; +import { authenticateAdminRequest } from '../../../lib/admin-auth.js'; +import { addAdminRealmMember } from '../../../lib/admin-users.js'; +import { HttpError } from '../../../lib/http/http-error.js'; + +function assertBody(body) { + if (body === null || typeof body !== 'object' || Array.isArray(body)) { + throw new HttpError(400, 'invalid_request', 'Request body must be a JSON object'); + } + for (const field of Object.keys(body)) { + if (field !== 'user_id') { + throw new HttpError(400, 'invalid_request', `Unknown field: ${field}`); + } + } +} + +export default { + method: 'post', + path: '/api/v1/admin/realms/:realm/users', + name: 'admin.users.create', + async handler(req) { + const auth = await authenticateAdminRequest(req, { + realmSlug: req.params.realm, + }); + const body = req.body || {}; + assertBody(body); + const detail = await addAdminRealmMember({ + systemDb: auth.systemDb, + realmDb: auth.realmDb, + realmId: auth.realm.id, + userId: body.user_id, + actor: auth.user, + actorRoles: auth.roles, + }); + + return new app.HttpOk({ ok: true, ...detail }, { 'cache-control': 'no-store' }); + }, +}; diff --git a/server/src/controller/admin/users/get.js b/server/src/controller/admin/users/get.js @@ -11,12 +11,14 @@ export default { const auth = await authenticateAdminRequest(req, { realmSlug: req.params.realm, }); - const detail = await getAdminRealmUserDetail( - auth.systemDb, - auth.realmDb, - auth.realm.id, - req.params.userId - ); + const detail = await getAdminRealmUserDetail({ + systemDb: auth.systemDb, + realmDb: auth.realmDb, + realmId: auth.realm.id, + userId: req.params.userId, + actor: auth.user, + actorRoles: auth.roles, + }); if (!detail) { throw new HttpError(404, 'user_not_found', 'User not found'); } diff --git a/server/src/controller/admin/users/lookup.js b/server/src/controller/admin/users/lookup.js @@ -0,0 +1,26 @@ +import { app } from '../../../app.js'; +import { authenticateAdminRequest } from '../../../lib/admin-auth.js'; +import { lookupAdminRealmUser } from '../../../lib/admin-users.js'; + +export default { + method: 'get', + path: '/api/v1/admin/realms/:realm/user-lookup', + name: 'admin.users.lookup', + async handler(req) { + const auth = await authenticateAdminRequest(req, { + realmSlug: req.params.realm, + }); + const url = new URL(req.url, 'http://localhost'); + const user = await lookupAdminRealmUser({ + systemDb: auth.systemDb, + realmDb: auth.realmDb, + realmId: auth.realm.id, + identifier: url.searchParams.get('identifier'), + }); + + return new app.HttpOk( + { ok: true, user }, + { 'cache-control': 'no-store' } + ); + }, +}; diff --git a/server/src/controller/admin/users/membership.js b/server/src/controller/admin/users/membership.js @@ -0,0 +1,25 @@ +import { app } from '../../../app.js'; +import { authenticateAdminRequest } from '../../../lib/admin-auth.js'; +import { updateAdminRealmMembership } from '../../../lib/admin-users.js'; + +export default { + method: 'patch', + path: '/api/v1/admin/realms/:realm/users/:userId/membership', + name: 'admin.users.membership', + async handler(req) { + const auth = await authenticateAdminRequest(req, { + realmSlug: req.params.realm, + }); + const result = await updateAdminRealmMembership({ + systemDb: auth.systemDb, + realmDb: auth.realmDb, + realmId: auth.realm.id, + userId: req.params.userId, + body: req.body || {}, + actor: auth.user, + actorRoles: auth.roles, + }); + + return new app.HttpOk({ ok: true, ...result }, { 'cache-control': 'no-store' }); + }, +}; diff --git a/server/src/controller/admin/users/roles.js b/server/src/controller/admin/users/roles.js @@ -0,0 +1,25 @@ +import { app } from '../../../app.js'; +import { authenticateAdminRequest } from '../../../lib/admin-auth.js'; +import { updateAdminRealmRoles } from '../../../lib/admin-users.js'; + +export default { + method: 'put', + path: '/api/v1/admin/realms/:realm/users/:userId/roles', + name: 'admin.users.roles', + async handler(req) { + const auth = await authenticateAdminRequest(req, { + realmSlug: req.params.realm, + }); + const detail = await updateAdminRealmRoles({ + systemDb: auth.systemDb, + realmDb: auth.realmDb, + realmId: auth.realm.id, + userId: req.params.userId, + body: req.body || {}, + actor: auth.user, + actorRoles: auth.roles, + }); + + return new app.HttpOk({ ok: true, ...detail }, { 'cache-control': 'no-store' }); + }, +}; diff --git a/server/src/lib/admin-users.js b/server/src/lib/admin-users.js @@ -1,13 +1,18 @@ import { HttpError } from './http/http-error.js'; import { inClause } from './db/query.js'; +import { revokeUserRealmAccess } from './bans.js'; import { splitScopes } from './consents.js'; -import { isSystemAdmin } from './policy.js'; +import { canManageUser, isRealmAdmin, isSystemAdmin } from './policy.js'; import { openRealmDatabase, realmMetadata } from './realm.js'; +import { revokeUserRealmSessions } from './session.js'; import { findUserById, + findUserByIdentifier, getMembership, getPrimaryEmail, getUserRoles, + replaceUserRoles, + setMembershipStatus, } from './users.js'; function uniqueUserIds(...groups) { @@ -40,6 +45,291 @@ function compareUsers(a, b) { return 0; } +const MEMBERSHIP_STATUSES = new Set(['active', 'suspended']); +const MAX_ROLE_COUNT = 50; + +function invalidRequest(message, code = 'invalid_request') { + return new HttpError(400, code, message); +} + +function notFound(message, code = 'user_not_found') { + return new HttpError(404, code, message); +} + +function forbidden(message) { + return new HttpError(403, 'forbidden', message); +} + +function conflict(message, code) { + return new HttpError(409, code, message); +} + +function isPlainObject(value) { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +function assertBody(body) { + if (!isPlainObject(body)) { + throw invalidRequest('Request body must be a JSON object'); + } +} + +function assertKnownFields(body, allowed) { + for (const field of Object.keys(body)) { + if (!allowed.has(field)) throw invalidRequest(`Unknown field: ${field}`); + } +} + +function relationshipFor(user, membership, realmId) { + if (user.home_realm_id === realmId) return 'home'; + return membership ? 'guest' : 'none'; +} + +function effectiveMembershipStatus(user, membership, realmId) { + if (membership) return membership.status; + return user.home_realm_id === realmId ? 'active' : null; +} + +function sameRoleSet(left, right) { + if (left.length !== right.length) return false; + const sortedLeft = [...left].sort(); + const sortedRight = [...right].sort(); + return sortedLeft.every((value, index) => value === sortedRight[index]); +} + +function normalizeRoleInput(value) { + if (!Array.isArray(value)) { + throw invalidRequest('roles must be an array'); + } + if (value.length > MAX_ROLE_COUNT) { + throw invalidRequest(`roles may contain at most ${MAX_ROLE_COUNT} entries`); + } + + const roles = new Set(); + for (const item of value) { + if (typeof item !== 'string' || !item.trim()) { + throw invalidRequest('roles must contain only non-empty strings'); + } + roles.add(item.trim()); + } + return [...roles].sort(); +} + +async function activeRealmAdminCount(systemDb, realmDb, realmId) { + const role = await realmDb.get( + "SELECT id FROM roles WHERE slug = 'realm-admin'" + ); + if (!role) return 0; + + const assignments = await realmDb.all( + 'SELECT user_id FROM membership_roles WHERE role_id = {roleId}', + { roleId: role.id } + ); + if (assignments.length === 0) return 0; + + const ids = assignments.map((row) => row.user_id); + const clause = inClause('roleIdUserId', ids); + const users = await systemDb.all( + `SELECT id, status, home_realm_id + FROM users + WHERE id IN (${clause.sql})`, + clause.params + ); + const memberships = await realmDb.all('SELECT user_id, status FROM realm_memberships'); + const membershipsByUser = new Map(memberships.map((row) => [row.user_id, row])); + + return users.filter((user) => { + if (user.status !== 'active') return false; + const membership = membershipsByUser.get(user.id) || null; + return effectiveMembershipStatus(user, membership, realmId) === 'active'; + }).length; +} + +async function getAdminRealmUserPermissions({ + systemDb, + realmDb, + realmId, + target, + membership, + roles, + actor, + actorRoles, +}) { + const manageLevel = canManageUser({ + actorRoles, + actorIsSystemAdmin: isSystemAdmin(actor), + target, + realmId, + }); + const effectiveStatus = effectiveMembershipStatus(target, membership, realmId); + const targetActive = target.status === 'active'; + const lastActiveRealmAdmin = + isRealmAdmin(roles) && + targetActive && + effectiveStatus === 'active' && + (await activeRealmAdminCount(systemDb, realmDb, realmId)) <= 1; + const lastAdminOverride = isSystemAdmin(actor); + const canReactivateMembership = + Boolean(manageLevel) && targetActive && effectiveStatus === 'suspended'; + const canSuspendMembership = + Boolean(manageLevel) && + targetActive && + effectiveStatus === 'active' && + (lastAdminOverride || !lastActiveRealmAdmin); + + let reason = null; + if (!manageLevel) { + reason = 'not_authorized'; + } else if (!targetActive) { + reason = 'target_disabled'; + } else if (effectiveStatus === 'invited') { + reason = 'membership_invited'; + } else if (effectiveStatus === 'suspended') { + reason = 'membership_suspended'; + } else if (effectiveStatus !== 'active') { + reason = 'membership_not_found'; + } else if (lastActiveRealmAdmin && !lastAdminOverride) { + reason = 'last_realm_admin'; + } + + return { + is_self: actor.id === target.id, + can_manage_membership: canSuspendMembership || canReactivateMembership, + can_suspend_membership: canSuspendMembership, + can_reactivate_membership: canReactivateMembership, + can_edit_roles: Boolean(manageLevel) && targetActive && effectiveStatus === 'active', + can_remove_last_realm_admin: + Boolean(manageLevel) && targetActive && effectiveStatus === 'active' && lastAdminOverride, + last_active_realm_admin: lastActiveRealmAdmin, + reason, + }; +} + +function serializeAdminRealmUser(user, email, membership, realmId, roles, banRows) { + const relationship = relationshipFor(user, membership, realmId); + return { + id: user.id, + username: user.username, + display_name: user.display_name, + email: email?.email || null, + status: user.status, + membership_status: effectiveMembershipStatus(user, membership, realmId), + relationship, + roles, + is_system_admin: Boolean(user.is_system_admin), + banned: banRows.length > 0, + ban_count: banRows.length, + home_realm_id: user.home_realm_id, + last_login_at: user.last_login_at, + created_at: user.created_at, + updated_at: user.updated_at, + }; +} + +async function loadAdminRealmBans(systemDb, realmDb, userId) { + const banRows = await realmDb.all( + `SELECT user_id, client_id, created_by, created_at + FROM app_bans + WHERE user_id = {userId} + ORDER BY CASE WHEN client_id = '*' THEN 0 ELSE 1 END, client_id ASC`, + { userId } + ); + const clientRows = await realmDb.all('SELECT client_id, name FROM oidc_clients'); + const creatorIds = [...new Set(banRows.map((row) => row.created_by).filter(Boolean))]; + const creatorsById = new Map(); + if (creatorIds.length > 0) { + const creatorClause = inClause('creatorId', creatorIds); + const creatorRows = await systemDb.all( + `SELECT id, username FROM users WHERE id IN (${creatorClause.sql})`, + creatorClause.params + ); + for (const creator of creatorRows) creatorsById.set(creator.id, creator.username); + } + + const clientsById = new Map(clientRows.map((row) => [row.client_id, row.name])); + return banRows.map((ban) => ({ + client_id: ban.client_id, + client_name: ban.client_id === '*' ? 'All apps' : clientsById.get(ban.client_id) || null, + created_by: ban.created_by, + created_by_username: creatorsById.get(ban.created_by) || null, + created_at: ban.created_at, + })); +} + +async function loadAdminRealmConsents(systemDb, realmDb, realmId, userId) { + const consentRows = await systemDb.all( + `SELECT user_id, realm_id, client_id, scopes, granted_via, created_at, + updated_at, revoked_at + FROM client_consents + WHERE user_id = {userId} AND realm_id = {realmId} + ORDER BY client_id ASC`, + { userId, realmId } + ); + const clientRows = await realmDb.all( + 'SELECT client_id, name, consent_mode FROM oidc_clients' + ); + const clientsById = new Map( + clientRows.map((row) => [ + row.client_id, + { name: row.name, consent_mode: row.consent_mode || 'remembered' }, + ]) + ); + + return consentRows.map((consent) => { + const client = clientsById.get(consent.client_id) || null; + return { + client_id: consent.client_id, + client_name: client?.name || null, + client_consent_mode: client?.consent_mode || null, + scopes: splitScopes(consent.scopes), + granted_via: consent.granted_via, + created_at: consent.created_at, + updated_at: consent.updated_at, + revoked_at: consent.revoked_at, + active: !consent.revoked_at, + }; + }); +} + +async function getAdminRealmUserAccessDetail({ + systemDb, + realmDb, + realmId, + user, + actor, + actorRoles, +}) { + const membership = await getMembership(realmDb, user.id); + const roles = await getUserRoles(realmDb, user.id); + const email = await systemDb.get( + `SELECT email + FROM user_emails + WHERE user_id = {userId} AND verified = 1 + ORDER BY is_primary DESC, created_at ASC + LIMIT 1`, + { userId: user.id } + ); + const bans = await loadAdminRealmBans(systemDb, realmDb, user.id); + const consents = await loadAdminRealmConsents(systemDb, realmDb, realmId, user.id); + const permissions = await getAdminRealmUserPermissions({ + systemDb, + realmDb, + realmId, + target: user, + membership, + roles, + actor, + actorRoles, + }); + + return { + user: serializeAdminRealmUser(user, email, membership, realmId, roles, bans), + consents, + bans, + permissions, + }; +} + export async function assertAdminRealmUser({ systemDb, realmDb, realmId, userId }) { const user = await findUserById(systemDb, userId); if (!user) { @@ -123,101 +413,28 @@ export async function listAdminRealmUsers(systemDb, realmDb, realmId) { .sort(compareUsers); } -export async function getAdminRealmUserDetail(systemDb, realmDb, realmId, userId) { +export async function getAdminRealmUserDetail({ + systemDb, + realmDb, + realmId, + userId, + actor, + actorRoles, +}) { const user = await findUserById(systemDb, userId); if (!user) return null; const membership = await getMembership(realmDb, userId); if (user.home_realm_id !== realmId && !membership) return null; - const roles = await getUserRoles(realmDb, userId); - const email = await systemDb.get( - `SELECT email - FROM user_emails - WHERE user_id = {userId} AND verified = 1 - ORDER BY is_primary DESC, created_at ASC - LIMIT 1`, - { userId } - ); - const consentRows = await systemDb.all( - `SELECT user_id, realm_id, client_id, scopes, granted_via, created_at, - updated_at, revoked_at - FROM client_consents - WHERE user_id = {userId} AND realm_id = {realmId} - ORDER BY client_id ASC`, - { userId, realmId } - ); - const clientRows = await realmDb.all( - 'SELECT client_id, name, consent_mode FROM oidc_clients' - ); - const banRows = await realmDb.all( - `SELECT user_id, client_id, created_by, created_at - FROM app_bans - WHERE user_id = {userId} - ORDER BY CASE WHEN client_id = '*' THEN 0 ELSE 1 END, client_id ASC`, - { userId } - ); - - const creatorIds = [...new Set(banRows.map((row) => row.created_by).filter(Boolean))]; - const creatorsById = new Map(); - if (creatorIds.length > 0) { - const creatorClause = inClause('creatorId', creatorIds); - const creatorRows = await systemDb.all( - `SELECT id, username FROM users WHERE id IN (${creatorClause.sql})`, - creatorClause.params - ); - for (const creator of creatorRows) { - creatorsById.set(creator.id, creator.username); - } - } - - const clientsById = new Map( - clientRows.map((row) => [ - row.client_id, - { name: row.name, consent_mode: row.consent_mode || 'remembered' }, - ]) - ); - - return { - user: { - id: user.id, - username: user.username, - display_name: user.display_name, - email: email?.email || null, - status: user.status, - membership_status: membership?.status || (user.home_realm_id === realmId ? 'active' : null), - relationship: user.home_realm_id === realmId ? 'home' : 'guest', - roles, - is_system_admin: Boolean(user.is_system_admin), - banned: banRows.length > 0, - ban_count: banRows.length, - home_realm_id: user.home_realm_id, - last_login_at: user.last_login_at, - created_at: user.created_at, - updated_at: user.updated_at, - }, - consents: consentRows.map((consent) => { - const client = clientsById.get(consent.client_id) || null; - return { - client_id: consent.client_id, - client_name: client?.name || null, - client_consent_mode: client?.consent_mode || null, - scopes: splitScopes(consent.scopes), - granted_via: consent.granted_via, - created_at: consent.created_at, - updated_at: consent.updated_at, - revoked_at: consent.revoked_at, - active: !consent.revoked_at, - }; - }), - bans: banRows.map((ban) => ({ - client_id: ban.client_id, - client_name: ban.client_id === '*' ? 'All apps' : clientsById.get(ban.client_id)?.name || null, - created_by: ban.created_by, - created_by_username: creatorsById.get(ban.created_by) || null, - created_at: ban.created_at, - })), - }; + return getAdminRealmUserAccessDetail({ + systemDb, + realmDb, + realmId, + user, + actor, + actorRoles, + }); } export async function getAdminCurrentUser(systemDb, user) { @@ -341,3 +558,265 @@ export async function getAdminGlobalUserOverview(systemDb, actor, userId) { memberships, }; } + +export async function lookupAdminRealmUser({ + systemDb, + realmDb, + realmId, + identifier, +}) { + if (typeof identifier !== 'string' || !identifier.trim()) { + throw invalidRequest('identifier is required'); + } + + const user = await findUserByIdentifier(systemDb, identifier); + if (!user) throw notFound(); + + const membership = await getMembership(realmDb, user.id); + const roles = await getUserRoles(realmDb, user.id); + const email = await getPrimaryEmail(systemDb, user.id); + const homeRealm = user.home_realm_id + ? await systemDb.get('SELECT slug FROM realms WHERE id = {id}', { id: user.home_realm_id }) + : null; + const relationship = relationshipFor(user, membership, realmId); + const effectiveStatus = effectiveMembershipStatus(user, membership, realmId); + + let canAdd = true; + let reason = null; + if (user.status !== 'active') { + canAdd = false; + reason = 'user_disabled'; + } else if (relationship !== 'none') { + canAdd = false; + reason = 'already_member'; + } + + return { + id: user.id, + username: user.username, + display_name: user.display_name, + email: email?.email || null, + status: user.status, + is_system_admin: Boolean(user.is_system_admin), + home_realm_slug: homeRealm?.slug || null, + relationship, + membership_status: effectiveStatus, + roles, + can_add: canAdd, + reason, + }; +} + +export async function addAdminRealmMember({ + systemDb, + realmDb, + realmId, + userId, + actor, + actorRoles, +}) { + if (typeof userId !== 'string' || !userId.trim()) { + throw invalidRequest('user_id is required'); + } + + const user = await findUserById(systemDb, userId.trim()); + if (!user) throw notFound(); + if (user.status !== 'active') throw conflict('This account is disabled', 'user_not_active'); + if (user.home_realm_id === realmId) throw conflict('User is already a member', 'already_member'); + + const existing = await getMembership(realmDb, user.id); + if (existing) throw conflict('User is already a member', 'already_member'); + + if (!canManageUser({ + actorRoles, + actorIsSystemAdmin: isSystemAdmin(actor), + target: user, + realmId, + })) { + throw forbidden('User management access is required'); + } + + const now = Date.now(); + await realmDb.transaction(async (tx) => { + const current = await tx.get( + 'SELECT user_id FROM realm_memberships WHERE user_id = {userId}', + { userId: user.id } + ); + if (current) throw conflict('User is already a member', 'already_member'); + const currentHomeRealm = await systemDb.get('SELECT id FROM realms WHERE id = {id}', { + id: user.home_realm_id, + }); + if (currentHomeRealm?.id === realmId) { + throw conflict('User is already a member', 'already_member'); + } + + await tx.run( + `INSERT INTO realm_memberships (user_id, status, created_at, updated_at) + VALUES ({userId}, 'active', {createdAt}, {updatedAt})`, + { userId: user.id, createdAt: now, updatedAt: now } + ); + }); + + return getAdminRealmUserAccessDetail({ + systemDb, + realmDb, + realmId, + user, + actor, + actorRoles, + }); +} + +export async function updateAdminRealmMembership({ + systemDb, + realmDb, + realmId, + userId, + body, + actor, + actorRoles, +}) { + assertBody(body); + assertKnownFields(body, new Set(['status'])); + if (typeof body.status !== 'string' || !MEMBERSHIP_STATUSES.has(body.status)) { + throw invalidRequest('status must be active or suspended', 'invalid_membership_status'); + } + + const user = await assertAdminRealmUser({ systemDb, realmDb, realmId, userId }); + const membership = await getMembership(realmDb, user.id); + const roles = await getUserRoles(realmDb, user.id); + const effectiveStatus = effectiveMembershipStatus(user, membership, realmId); + const manageLevel = canManageUser({ + actorRoles, + actorIsSystemAdmin: isSystemAdmin(actor), + target: user, + realmId, + }); + if (!manageLevel) throw forbidden('User management access is required'); + if (user.status !== 'active') throw conflict('This account is disabled', 'target_disabled'); + if (effectiveStatus === 'invited') { + throw conflict('Invited membership cannot be changed yet', 'membership_invited'); + } + + const nextStatus = body.status; + if (nextStatus === effectiveStatus) { + const detail = await getAdminRealmUserAccessDetail({ + systemDb, + realmDb, + realmId, + user, + actor, + actorRoles, + }); + return { + ...detail, + revoked: { consents: 0, refresh_tokens: 0, session_realms: 0 }, + }; + } + + if (nextStatus === 'suspended') { + const lastAdmin = + isRealmAdmin(roles) && + (await activeRealmAdminCount(systemDb, realmDb, realmId)) <= 1; + if (lastAdmin && !isSystemAdmin(actor)) { + throw conflict('Another active realm admin is required', 'last_realm_admin'); + } + } + + await setMembershipStatus(realmDb, user.id, nextStatus); + let revoked = { consents: 0, refresh_tokens: 0, session_realms: 0 }; + if (nextStatus === 'suspended') { + const now = Date.now(); + const access = await revokeUserRealmAccess(systemDb, { + userId: user.id, + realmId, + now, + }); + const sessionRealms = await revokeUserRealmSessions(systemDb, { + userId: user.id, + realmId, + revokedBy: actor.id, + now, + }); + revoked = { ...access, session_realms: sessionRealms }; + } + + const detail = await getAdminRealmUserAccessDetail({ + systemDb, + realmDb, + realmId, + user, + actor, + actorRoles, + }); + return { ...detail, revoked }; +} + +export async function updateAdminRealmRoles({ + systemDb, + realmDb, + realmId, + userId, + body, + actor, + actorRoles, +}) { + assertBody(body); + assertKnownFields(body, new Set(['roles'])); + const requestedRoles = normalizeRoleInput(body.roles); + + const user = await assertAdminRealmUser({ systemDb, realmDb, realmId, userId }); + const membership = await getMembership(realmDb, user.id); + const currentRoles = await getUserRoles(realmDb, user.id); + const effectiveStatus = effectiveMembershipStatus(user, membership, realmId); + const manageLevel = canManageUser({ + actorRoles, + actorIsSystemAdmin: isSystemAdmin(actor), + target: user, + realmId, + }); + if (!manageLevel) throw forbidden('User management access is required'); + if (user.status !== 'active') throw conflict('This account is disabled', 'target_disabled'); + if (effectiveStatus !== 'active') { + throw conflict('An active membership is required', 'membership_not_active'); + } + + if (requestedRoles.length > 0) { + const clause = inClause('roleSlug', requestedRoles); + const roles = await realmDb.all( + `SELECT id, slug FROM roles WHERE slug IN (${clause.sql})`, + clause.params + ); + if (roles.length !== requestedRoles.length) { + throw invalidRequest('One or more roles do not exist', 'invalid_roles'); + } + if ( + isRealmAdmin(currentRoles) && + !isRealmAdmin(requestedRoles) && + (await activeRealmAdminCount(systemDb, realmDb, realmId)) <= 1 && + !isSystemAdmin(actor) + ) { + throw conflict('Another active realm admin is required', 'last_realm_admin'); + } + + await replaceUserRoles(realmDb, user.id, roles.map((role) => role.id)); + } else { + if ( + isRealmAdmin(currentRoles) && + (await activeRealmAdminCount(systemDb, realmDb, realmId)) <= 1 && + !isSystemAdmin(actor) + ) { + throw conflict('Another active realm admin is required', 'last_realm_admin'); + } + await replaceUserRoles(realmDb, user.id, []); + } + + return getAdminRealmUserAccessDetail({ + systemDb, + realmDb, + realmId, + user, + actor, + actorRoles, + }); +} diff --git a/server/src/lib/bans.js b/server/src/lib/bans.js @@ -78,7 +78,7 @@ export async function revokeBannedClientAccess( }); } -export async function revokeBannedRealmAccess( +export async function revokeUserRealmAccess( systemDb, { userId, realmId, now = Date.now() } ) { @@ -105,3 +105,10 @@ export async function revokeBannedRealmAccess( }; }); } + +export async function revokeBannedRealmAccess( + systemDb, + { userId, realmId, now = Date.now() } +) { + return revokeUserRealmAccess(systemDb, { userId, realmId, now }); +} diff --git a/server/src/lib/session.js b/server/src/lib/session.js @@ -634,6 +634,21 @@ export async function revokeRealmSessions( return result.changes; } +export async function revokeUserRealmSessions( + systemDb, + { userId, realmId, revokedBy = null, now = Date.now() } +) { + const result = await systemDb.run( + `UPDATE session_realms + SET revoked_at = {now}, revoked_by = {revokedBy} + WHERE realm_id = {realmId} + AND revoked_at IS NULL + AND session_id IN (SELECT id FROM sessions WHERE user_id = {userId})`, + { now, revokedBy, realmId, userId } + ); + return result.changes; +} + export async function reauthenticateSession( systemDb, { sessionId, realmId, now = Date.now() } diff --git a/server/src/lib/users.js b/server/src/lib/users.js @@ -269,3 +269,39 @@ export async function assignRole(db, userId, roleSlug) { { userId, roleId: role.id } ); } + +export async function setMembershipStatus(db, userId, status, now = Date.now()) { + const existing = await db.get( + 'SELECT user_id FROM realm_memberships WHERE user_id = {userId}', + { userId } + ); + if (!existing) { + await db.run( + `INSERT INTO realm_memberships (user_id, status, created_at, updated_at) + VALUES ({userId}, {status}, {createdAt}, {updatedAt})`, + { userId, status, createdAt: now, updatedAt: now } + ); + return getMembership(db, userId); + } + + if (existing.status !== status) { + await db.run( + 'UPDATE realm_memberships SET status = {status}, updated_at = {now} WHERE user_id = {userId}', + { status, now, userId } + ); + } + return getMembership(db, userId); +} + +export async function replaceUserRoles(db, userId, roleIds, now = Date.now()) { + await db.transaction(async (tx) => { + await tx.run('DELETE FROM membership_roles WHERE user_id = {userId}', { userId }); + for (const roleId of roleIds) { + await tx.run( + 'INSERT INTO membership_roles (user_id, role_id) VALUES ({userId}, {roleId})', + { userId, roleId } + ); + } + }); + return getUserRoles(db, userId); +} diff --git a/server/test/http.test.js b/server/test/http.test.js @@ -324,6 +324,85 @@ function withRealmDatabase(env, slug, fn) { } } +function insertTestUser( + env, + { username, email = null, displayName = username, status = 'active', isSystemAdmin = false } +) { + const id = crypto.randomUUID(); + const now = Date.now(); + withSystemDatabase(env, (database) => { + database + .prepare( + `INSERT INTO users + (id, username, username_normalized, display_name, status, home_realm_id, + is_system_admin, profile, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, NULL, ?, '{}', ?, ?)` + ) + .run( + id, + username, + username.toLowerCase(), + displayName, + status, + isSystemAdmin ? 1 : 0, + now, + now + ); + if (email) { + database + .prepare( + `INSERT INTO user_emails + (id, user_id, email, email_normalized, verified, is_primary, created_at, verified_at) + VALUES (?, ?, ?, ?, 1, 1, ?, ?)` + ) + .run(crypto.randomUUID(), id, email, email.toLowerCase(), now, now); + } + }); + return id; +} + +function clearRealmMembership(env, realmSlug, membershipUserId) { + withRealmDatabase(env, realmSlug, (database) => { + database.prepare('DELETE FROM membership_roles WHERE user_id = ?').run(membershipUserId); + database.prepare('DELETE FROM realm_memberships WHERE user_id = ?').run(membershipUserId); + }); +} + +function clearUserRealmSessions(env, membershipUserId) { + withSystemDatabase(env, (database) => { + const sessions = database.prepare('SELECT id FROM sessions WHERE user_id = ?').all(membershipUserId); + for (const session of sessions) { + database.prepare('DELETE FROM session_realms WHERE session_id = ?').run(session.id); + database.prepare('DELETE FROM refresh_tokens WHERE session_id = ?').run(session.id); + } + database.prepare('DELETE FROM sessions WHERE user_id = ?').run(membershipUserId); + database + .prepare( + `DELETE FROM session_groups + WHERE id NOT IN (SELECT group_id FROM sessions)` + ) + .run(); + }); +} + +function setTestMembershipStatus(env, realmSlug, membershipUserId, status) { + const now = Date.now(); + withRealmDatabase(env, realmSlug, (database) => { + const existing = database + .prepare('SELECT user_id FROM realm_memberships WHERE user_id = ?') + .get(membershipUserId); + if (existing) { + database + .prepare('UPDATE realm_memberships SET status = ?, updated_at = ? WHERE user_id = ?') + .run(status, now, membershipUserId); + return; + } + database + .prepare('INSERT INTO realm_memberships (user_id, status, created_at, updated_at) VALUES (?, ?, ?, ?)') + .run(membershipUserId, status, now, now); + }); +} + test('HTTP realm, login, OIDC and logout flows', async (t) => { const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'auth-http-')); const port = await freePort(); @@ -3453,6 +3532,402 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { assert.equal(response.status, 401); assert.equal(response.json.error.code, 'not_authenticated'); }); + + await t.test('admin realm membership management adds existing users', async () => { + const acmeAdmin = await adminToken('it@acme.test'); + const contractor = await adminToken('contractor@personal.test'); + const carolId = insertTestUser(env, { + username: 'carol', + email: 'carol@external.test', + displayName: 'Carol', + }); + const danaId = insertTestUser(env, { + username: 'dana', + email: 'dana@external.test', + displayName: 'Dana', + status: 'disabled', + }); + const aliceId = userId(env, 'alice'); + + try { + const lookupEmail = await adminRequest(acmeAdmin, { + path: `/api/v1/admin/realms/acme/user-lookup?identifier=${encodeURIComponent('carol@external.test')}`, + }); + assert.equal(lookupEmail.status, 200); + assert.equal(lookupEmail.json.ok, true); + assert.equal(lookupEmail.json.user.id, carolId); + assert.equal(lookupEmail.json.user.username, 'carol'); + assert.equal(lookupEmail.json.user.relationship, 'none'); + assert.equal(lookupEmail.json.user.can_add, true); + assert.equal(lookupEmail.json.user.reason, null); + + const lookupUsername = await adminRequest(acmeAdmin, { + path: '/api/v1/admin/realms/acme/user-lookup?identifier=CAROL', + }); + assert.equal(lookupUsername.status, 200); + assert.equal(lookupUsername.json.user.id, carolId); + + const disabled = await adminRequest(acmeAdmin, { + path: '/api/v1/admin/realms/acme/user-lookup?identifier=dana@external.test', + }); + assert.equal(disabled.status, 200); + assert.equal(disabled.json.user.status, 'disabled'); + assert.equal(disabled.json.user.can_add, false); + assert.equal(disabled.json.user.reason, 'user_disabled'); + + const existingHome = await adminRequest(acmeAdmin, { + path: '/api/v1/admin/realms/acme/user-lookup?identifier=alice@acme.test', + }); + assert.equal(existingHome.status, 200); + assert.equal(existingHome.json.user.relationship, 'home'); + assert.equal(existingHome.json.user.can_add, false); + assert.equal(existingHome.json.user.reason, 'already_member'); + + const unknown = await adminRequest(acmeAdmin, { + path: '/api/v1/admin/realms/acme/user-lookup?identifier=missing@external.test', + }); + assert.equal(unknown.status, 404); + assert.equal(unknown.json.error.code, 'user_not_found'); + + const missingIdentifier = await adminRequest(acmeAdmin, { + path: '/api/v1/admin/realms/acme/user-lookup', + }); + assert.equal(missingIdentifier.status, 400); + assert.equal(missingIdentifier.json.error.code, 'invalid_request'); + + const foreignLookup = await identity({ + path: '/api/v1/admin/realms/acme/user-lookup?identifier=carol', + bearer: contractor.access_token, + }); + assert.equal(foreignLookup.status, 403); + + const foreignAdd = await identity({ + method: 'POST', + path: '/api/v1/admin/realms/acme/users', + bearer: contractor.access_token, + body: { user_id: carolId }, + }); + assert.equal(foreignAdd.status, 403); + + const added = await adminRequest(acmeAdmin, { + method: 'POST', + path: '/api/v1/admin/realms/acme/users', + body: { user_id: carolId }, + }); + assert.equal(added.status, 200); + assert.equal(added.json.ok, true); + assert.equal(added.json.user.id, carolId); + assert.equal(added.json.user.relationship, 'guest'); + assert.equal(added.json.user.membership_status, 'active'); + assert.equal(added.json.permissions.can_manage_membership, true); + + const list = await adminRequest(acmeAdmin, { + path: '/api/v1/admin/realms/acme/users', + }); + assert.ok(list.json.users.some((user) => user.username === 'carol')); + + const detail = await adminRequest(acmeAdmin, { + path: `/api/v1/admin/realms/acme/users/${carolId}`, + }); + assert.equal(detail.status, 200); + assert.equal(detail.json.user.username, 'carol'); + + const alreadyMember = await adminRequest(acmeAdmin, { + path: `/api/v1/admin/realms/acme/user-lookup?identifier=carol@external.test`, + }); + assert.equal(alreadyMember.json.user.relationship, 'guest'); + assert.equal(alreadyMember.json.user.can_add, false); + assert.equal(alreadyMember.json.user.reason, 'already_member'); + + const duplicate = await adminRequest(acmeAdmin, { + method: 'POST', + path: '/api/v1/admin/realms/acme/users', + body: { user_id: carolId }, + }); + assert.equal(duplicate.status, 409); + assert.equal(duplicate.json.error.code, 'already_member'); + + const disabledAdd = await adminRequest(acmeAdmin, { + method: 'POST', + path: '/api/v1/admin/realms/acme/users', + body: { user_id: danaId }, + }); + assert.equal(disabledAdd.status, 409); + assert.equal(disabledAdd.json.error.code, 'user_not_active'); + + const homeRealmAdd = await adminRequest(acmeAdmin, { + method: 'POST', + path: '/api/v1/admin/realms/acme/users', + body: { user_id: aliceId }, + }); + assert.equal(homeRealmAdd.status, 409); + assert.equal(homeRealmAdd.json.error.code, 'already_member'); + + const unknownAdd = await adminRequest(acmeAdmin, { + method: 'POST', + path: '/api/v1/admin/realms/acme/users', + body: { user_id: crypto.randomUUID() }, + }); + assert.equal(unknownAdd.status, 404); + + const unknownField = await adminRequest(acmeAdmin, { + method: 'POST', + path: '/api/v1/admin/realms/acme/users', + body: { user_id: crypto.randomUUID(), roles: [] }, + }); + assert.equal(unknownField.status, 400); + assert.equal(unknownField.json.error.code, 'invalid_request'); + } finally { + clearRealmMembership(env, 'acme', carolId); + clearRealmMembership(env, 'acme', danaId); + } + }); + + await t.test('admin membership suspension revokes realm access', async () => { + const acmeAdmin = await adminToken('it@acme.test'); + const guestId = userId(env, 'guest'); + const acmeId = realmId(env, 'acme'); + const redirectUri = `${origin('members.localhost')}/callback`; + clearConsent(env, { username: 'guest', realm: 'acme', clientId: 'acme-members-app' }); + clearBans(env, { username: 'guest', realm: 'acme' }); + clearUserRealmSessions(env, guestId); + + try { + const guest = await accessToken(acme, { + clientId: 'acme-members-app', + identifier: 'guest@personal.test', + redirectUri, + }); + const sessionId = activeSessionId(env, guest.cookie); + const refreshId = insertRefreshToken(env, { + sessionId, + userId: guestId, + realmId: acmeId, + clientId: 'acme-members-app', + }); + + const suspended = await adminRequest(acmeAdmin, { + method: 'PATCH', + path: `/api/v1/admin/realms/acme/users/${guestId}/membership`, + body: { status: 'suspended' }, + }); + assert.equal(suspended.status, 200); + assert.equal(suspended.json.user.membership_status, 'suspended'); + assert.ok(suspended.json.revoked.refresh_tokens >= 1); + assert.ok(suspended.json.revoked.consents >= 1); + assert.ok(suspended.json.revoked.session_realms >= 1); + + const consent = withSystemDatabase(env, (database) => + database + .prepare( + `SELECT revoked_at + FROM client_consents + WHERE user_id = ? AND realm_id = ? AND client_id = 'acme-members-app'` + ) + .get(guestId, acmeId) + ); + assert.ok(consent.revoked_at); + + const refresh = withSystemDatabase(env, (database) => + database.prepare('SELECT revoked_at FROM refresh_tokens WHERE id = ?').get(refreshId) + ); + assert.ok(refresh.revoked_at); + + const binding = withSystemDatabase(env, (database) => + database + .prepare('SELECT revoked_at FROM session_realms WHERE session_id = ? AND realm_id = ?') + .get(sessionId, acmeId) + ); + assert.ok(binding.revoked_at); + + const { challenge } = pkce(); + const authorizePath = + `/oidc/acme-members-app/authorize?response_type=code&client_id=acme-members-app` + + `&redirect_uri=${encodeURIComponent(redirectUri)}&scope=openid` + + `&state=suspended-membership&code_challenge=${challenge}` + + `&code_challenge_method=S256`; + const denied = await acme({ path: authorizePath, cookie: guest.cookie }); + assert.equal(denied.status, 302); + assert.equal(locationQuery(denied).searchParams.get('error'), 'access_denied'); + + const restored = await adminRequest(acmeAdmin, { + method: 'PATCH', + path: `/api/v1/admin/realms/acme/users/${guestId}/membership`, + body: { status: 'active' }, + }); + assert.equal(restored.status, 200); + assert.equal(restored.json.user.membership_status, 'active'); + assert.deepEqual(restored.json.revoked, { + consents: 0, + refresh_tokens: 0, + session_realms: 0, + }); + + const stillRevoked = withSystemDatabase(env, (database) => + database + .prepare( + `SELECT revoked_at + FROM client_consents + WHERE user_id = ? AND realm_id = ? AND client_id = 'acme-members-app'` + ) + .get(guestId, acmeId) + ); + assert.ok(stillRevoked.revoked_at); + + const invalidStatus = await adminRequest(acmeAdmin, { + method: 'PATCH', + path: `/api/v1/admin/realms/acme/users/${guestId}/membership`, + body: { status: 'invited' }, + }); + assert.equal(invalidStatus.status, 400); + assert.equal(invalidStatus.json.error.code, 'invalid_membership_status'); + } finally { + setTestMembershipStatus(env, 'acme', guestId, 'active'); + clearConsent(env, { username: 'guest', realm: 'acme', clientId: 'acme-members-app' }); + clearBans(env, { username: 'guest', realm: 'acme' }); + clearUserRealmSessions(env, guestId); + } + }); + + await t.test('admin realm roles and last active admin protection', async () => { + const acmeAdmin = await adminToken('it@acme.test'); + const systemAdmin = await adminToken(); + const guestId = userId(env, 'guest'); + const acmeItId = userId(env, 'acme-it'); + + try { + const invalidRole = await adminRequest(acmeAdmin, { + method: 'PUT', + path: `/api/v1/admin/realms/acme/users/${guestId}/roles`, + body: { roles: ['does-not-exist'] }, + }); + assert.equal(invalidRole.status, 400); + assert.equal(invalidRole.json.error.code, 'invalid_roles'); + + const invalidShape = await adminRequest(acmeAdmin, { + method: 'PUT', + path: `/api/v1/admin/realms/acme/users/${guestId}/roles`, + body: { roles: 'realm-admin' }, + }); + assert.equal(invalidShape.status, 400); + assert.equal(invalidShape.json.error.code, 'invalid_request'); + + const granted = await adminRequest(acmeAdmin, { + method: 'PUT', + path: `/api/v1/admin/realms/acme/users/${guestId}/roles`, + body: { roles: ['realm-admin'] }, + }); + assert.equal(granted.status, 200); + assert.deepEqual(granted.json.user.roles, ['realm-admin']); + + const guestAdmin = await adminToken('guest@personal.test'); + const suspendedOther = await adminRequest(guestAdmin, { + method: 'PATCH', + path: `/api/v1/admin/realms/acme/users/${acmeItId}/membership`, + body: { status: 'suspended' }, + }); + assert.equal(suspendedOther.status, 200); + assert.equal(suspendedOther.json.user.membership_status, 'suspended'); + + const deniedAdmin = await adminRequest(acmeAdmin, { + path: '/api/v1/admin/realms/acme/users', + }); + assert.equal(deniedAdmin.status, 403); + + const restored = await adminRequest(systemAdmin, { + method: 'PATCH', + path: `/api/v1/admin/realms/acme/users/${acmeItId}/membership`, + body: { status: 'active' }, + }); + assert.equal(restored.status, 200); + assert.equal(restored.json.user.membership_status, 'active'); + + const allowedAdmin = await adminRequest(acmeAdmin, { + path: '/api/v1/admin/realms/acme/users', + }); + assert.equal(allowedAdmin.status, 200); + + const removedSecondAdmin = await adminRequest(acmeAdmin, { + method: 'PUT', + path: `/api/v1/admin/realms/acme/users/${guestId}/roles`, + body: { roles: [] }, + }); + assert.equal(removedSecondAdmin.status, 200); + assert.deepEqual(removedSecondAdmin.json.user.roles, []); + + const lastAdminSuspend = await adminRequest(acmeAdmin, { + method: 'PATCH', + path: `/api/v1/admin/realms/acme/users/${acmeItId}/membership`, + body: { status: 'suspended' }, + }); + assert.equal(lastAdminSuspend.status, 409); + assert.equal(lastAdminSuspend.json.error.code, 'last_realm_admin'); + + const lastAdminDemote = await adminRequest(acmeAdmin, { + method: 'PUT', + path: `/api/v1/admin/realms/acme/users/${acmeItId}/roles`, + body: { roles: [] }, + }); + assert.equal(lastAdminDemote.status, 409); + assert.equal(lastAdminDemote.json.error.code, 'last_realm_admin'); + + const systemSuspend = await adminRequest(systemAdmin, { + method: 'PATCH', + path: `/api/v1/admin/realms/acme/users/${acmeItId}/membership`, + body: { status: 'suspended' }, + }); + assert.equal(systemSuspend.status, 200); + await adminRequest(systemAdmin, { + method: 'PATCH', + path: `/api/v1/admin/realms/acme/users/${acmeItId}/membership`, + body: { status: 'active' }, + }); + const systemDemote = await adminRequest(systemAdmin, { + method: 'PUT', + path: `/api/v1/admin/realms/acme/users/${acmeItId}/roles`, + body: { roles: [] }, + }); + assert.equal(systemDemote.status, 200); + await adminRequest(systemAdmin, { + method: 'PUT', + path: `/api/v1/admin/realms/acme/users/${acmeItId}/roles`, + body: { roles: ['realm-admin'] }, + }); + + const detail = await adminRequest(acmeAdmin, { + path: `/api/v1/admin/realms/acme/users/${acmeItId}`, + }); + assert.equal(detail.json.permissions.is_self, true); + assert.equal(detail.json.permissions.last_active_realm_admin, true); + assert.equal(detail.json.permissions.can_remove_last_realm_admin, false); + assert.equal(detail.json.permissions.can_suspend_membership, false); + assert.equal(detail.json.permissions.reason, 'last_realm_admin'); + + const systemDetail = await adminRequest(systemAdmin, { + path: `/api/v1/admin/realms/acme/users/${acmeItId}`, + }); + assert.equal(systemDetail.json.permissions.last_active_realm_admin, true); + assert.equal(systemDetail.json.permissions.can_remove_last_realm_admin, true); + assert.equal(systemDetail.json.permissions.can_suspend_membership, true); + } finally { + setTestMembershipStatus(env, 'acme', guestId, 'active'); + setTestMembershipStatus(env, 'acme', acmeItId, 'active'); + withRealmDatabase(env, 'acme', (database) => { + database.prepare('DELETE FROM membership_roles WHERE user_id = ?').run(guestId); + const role = database.prepare('SELECT id FROM roles WHERE slug = ?').get('realm-admin'); + const current = database + .prepare('SELECT role_id FROM membership_roles WHERE user_id = ? AND role_id = ?') + .get(acmeItId, role.id); + if (!current) { + database + .prepare('INSERT INTO membership_roles (user_id, role_id) VALUES (?, ?)') + .run(acmeItId, role.id); + } + }); + clearUserRealmSessions(env, guestId); + clearUserRealmSessions(env, acmeItId); + } + }); } finally { if (server) { server.kill('SIGTERM');