Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions apps/editor/src/app/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import type { CaseVersion } from '@/application/framework/mappers/case/CasePacka
import type { CFAssociationGrouping, CFItemType, CFLicense, CFSubject, CFConcept, CFDefinition } from '@/domain/case/types'
import { extractCfDefinitions, preferFrameworkDefinitions } from '@/application/framework/mappers/case/frameworkDefinitions'
import LoginScreen from '@/ui/auth/LoginScreen'
import { ensureDefaultMembership } from '@/app/ensureDefaultMembership'
import { detectTopology } from '@/ui/editor/layout/detectTopology'
import { applyInitialLayout } from '@/ui/editor/layout/applyInitialLayout'

Expand All @@ -38,7 +39,7 @@ export default function App() {
}

function AppInner() {
const { completeSignIn, getAccessToken, status: authStatus, tenantId } = useAuth()
const { completeSignIn, getAccessToken, refreshAccessToken, status: authStatus, tenantId } = useAuth()
const cfg = getAppConfig()
const api = useMemo(() => new CaseApiClient(createFetchHttpClient(cfg.opencaseBaseUrl, { getAccessToken })), [cfg.opencaseBaseUrl, getAccessToken])

Expand Down Expand Up @@ -195,18 +196,17 @@ function AppInner() {
setRoute('login')
}, [authStatus, route])

// SSO: ensure default tenant membership when org_id claim matches (idempotent).
// First login: give the user the default role (idempotent) and refresh their token if it did.
const ensureSelfAttempted = useRef<string | null>(null)
useEffect(() => {
if (authStatus !== 'authenticated' || !tenantId) return
const key = tenantId
if (ensureSelfAttempted.current === key) return
ensureSelfAttempted.current = key
void api.ensureSelfMembership({ tenantId }).catch((err: unknown) => {
// Expected when org_id claim is absent (non-SSO / local users).
console.debug('[App] ensure-self skipped or failed:', err)
ensureDefaultMembership(api, tenantId, refreshAccessToken).catch((err: unknown) => {
console.warn('[App] ensure-self failed:', err)
})
}, [authStatus, tenantId, api])
}, [authStatus, tenantId, api, refreshAccessToken])

// Fetch the full definitions catalogue from the management endpoint once authenticated.
useEffect(() => {
Expand Down
6 changes: 3 additions & 3 deletions apps/editor/src/app/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ type AppConfig = {
opencaseBaseUrl: string
oidcAuthority: string
oidcClientIdPrefix: string
/** When set, skip tenant lookup and sign in directly with this tenant. */
defaultTenantId: string | null
/** The OpenCASE tenant users sign in to; `system` unless VITE_DEFAULT_TENANT_ID overrides it. */
defaultTenantId: string
}

function readRequiredEnv(key: keyof ImportMetaEnv, fallback?: string): string {
Expand All @@ -23,7 +23,7 @@ export function getAppConfig(): AppConfig {
opencaseBaseUrl: readRequiredEnv('VITE_OPENCASE_BASE_URL', 'http://localhost:8080'),
oidcAuthority: readRequiredEnv('VITE_OIDC_AUTHORITY', 'http://localhost:8081/realms/opencase'),
oidcClientIdPrefix: readRequiredEnv('VITE_OIDC_CLIENT_ID_PREFIX', 'tenant-'),
defaultTenantId: readOptionalEnv('VITE_DEFAULT_TENANT_ID'),
defaultTenantId: readOptionalEnv('VITE_DEFAULT_TENANT_ID') ?? 'system',
}
}

23 changes: 23 additions & 0 deletions apps/editor/src/app/ensureDefaultMembership.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { describe, expect, it, vi } from 'vitest'
import { ensureDefaultMembership } from './ensureDefaultMembership'

describe('ensureDefaultMembership', () => {
it('refreshes the access token when the default role was assigned', async () => {
const api = { ensureSelfMembership: vi.fn().mockResolvedValue({ status: 'assigned', role: 'author' }) }
const refreshAccessToken = vi.fn().mockResolvedValue(undefined)

await ensureDefaultMembership(api, 'system', refreshAccessToken)

expect(api.ensureSelfMembership).toHaveBeenCalledWith({ tenantId: 'system' })
expect(refreshAccessToken).toHaveBeenCalledTimes(1)
})

it('leaves the access token alone when nothing changed', async () => {
const api = { ensureSelfMembership: vi.fn().mockResolvedValue({ status: 'unchanged', role: 'viewer' }) }
const refreshAccessToken = vi.fn().mockResolvedValue(undefined)

await ensureDefaultMembership(api, 'system', refreshAccessToken)

expect(refreshAccessToken).not.toHaveBeenCalled()
})
})
14 changes: 14 additions & 0 deletions apps/editor/src/app/ensureDefaultMembership.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import type { CaseApiClient } from '@/infrastructure/caseApi/CaseApiClient'

/**
* First login: ask the server to give the signed-in user the default role, and refresh
* their own access token when it did, so the new role applies without signing in again.
*/
export async function ensureDefaultMembership (
api: Pick<CaseApiClient, 'ensureSelfMembership'>,
tenantId: string,
refreshAccessToken: () => Promise<void>,
): Promise<void> {
const result = await api.ensureSelfMembership({ tenantId })
if (result.status === 'assigned') await refreshAccessToken()
}
10 changes: 9 additions & 1 deletion apps/editor/src/app/providers/AuthProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ type AuthContextValue = {
completeSignIn: (_callbackUrl?: string) => Promise<void>
signOut: () => Promise<void>
getAccessToken: () => Promise<string | null>
/** Fetch a new access token silently, e.g. after the user's own roles changed. */
refreshAccessToken: () => Promise<void>
/**
* Redirect to Keycloak's password change form via kc_action=UPDATE_PASSWORD.
* Null for federated users (external IdP) who do not have a Keycloak-managed password.
Expand Down Expand Up @@ -245,6 +247,11 @@ export function AuthProvider({ children }: Readonly<{ children: ReactNode }>) {
return u.access_token
}, [userManager])

const refreshAccessToken = useCallback(async () => {
// The userLoaded event handler above stores the renewed user.
await userManager.signinSilent()
}, [userManager])

const changePasswordFn = useCallback(async () => {
await userManager.signinRedirect({
extraQueryParams: { kc_action: 'UPDATE_PASSWORD' },
Expand All @@ -266,9 +273,10 @@ export function AuthProvider({ children }: Readonly<{ children: ReactNode }>) {
completeSignIn,
signOut,
getAccessToken,
refreshAccessToken,
changePassword,
}),
[status, tenantId, user, userName, accessToken, error, setTenantId, signIn, completeSignIn, signOut, getAccessToken, changePassword],
[status, tenantId, user, userName, accessToken, error, setTenantId, signIn, completeSignIn, signOut, getAccessToken, refreshAccessToken, changePassword],
)

return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>
Expand Down
4 changes: 2 additions & 2 deletions apps/editor/src/infrastructure/caseApi/CaseApiClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,8 @@ export class CaseApiClient {
}

/**
* SSO first-login: assign default author roles when org_id claim matches tenant.
* Idempotent. Caller should re-authenticate if status is `assigned`.
* First login: assign the default author role to a user who has never had a role.
* Idempotent. Caller should refresh its access token if status is `assigned`.
*/
async ensureSelfMembership(params: { tenantId: string }): Promise<{
status: string
Expand Down
7 changes: 4 additions & 3 deletions apps/editor/src/ui/home/MembersDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ const ROLE_OPTIONS: { value: TenantMemberRole; label: string; hint: string }[] =
]

function roleLabel (role: TenantMemberRole | null): string {
if (!role) return '—'
if (!role) return 'No role'
return ROLE_OPTIONS.find((o) => o.value === role)?.label ?? role
}

Expand Down Expand Up @@ -112,7 +112,7 @@ export default function MembersDialog({
}, [api, tenantId, email, role, loadMembers])

const handleRoleChange = useCallback(async (member: TenantMember, nextRole: TenantMemberRole) => {
if (!member.role || member.role === nextRole) return
if (member.role === nextRole) return
setUpdatingUserId(member.userId)
setError(null)
try {
Expand Down Expand Up @@ -227,11 +227,12 @@ export default function MembersDialog({
</div>
<select
className="rounded-md border border-gray-200 bg-white px-2 py-1.5 text-xs text-gray-700"
value={m.role ?? 'viewer'}
value={m.role ?? ''}
disabled={updatingUserId === m.userId}
onChange={(e) => void handleRoleChange(m, e.target.value as TenantMemberRole)}
aria-label={`Role for ${m.email ?? m.userId}`}
>
{m.role ? null : <option value="" disabled>No role</option>}
{ROLE_OPTIONS.map((o) => (
<option key={o.value} value={o.value}>{o.label}</option>
))}
Expand Down
10 changes: 6 additions & 4 deletions apps/opencase/docs/DEVELOPER.md
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ Keycloak-issued access tokens are JWTs containing:
- `aud` / `azp` - Audience / authorized party (must match the tenant client id)
- `tenantId` - Tenant identifier (injected by Keycloak mapper, required for tenant-scoped operations)
- `scope` - Space-separated list of granted scopes (from client roles)
- `org_id` - Optional SSO org claim (must equal `tenantId` for ensure-self); claim name configurable via `SSO_ORG_CLAIM`
- `org_id` - Optional SSO org claim; unused (CASE Global does not need it) and a candidate for removal; claim name configurable via `SSO_ORG_CLAIM`
- `sub` - Subject (user ID for authorization_code flow, client ID for client_credentials)

### Tenancy model
Expand Down Expand Up @@ -322,6 +322,8 @@ GET /management/tenants/{tenantId}/members
Authorization: Bearer {access_token}
```

Lists every user in the realm. Users without a role on this tenant have `role: null` and `scopes: []`.

**Add member:**
```bash
POST /management/tenants/{tenantId}/members
Expand All @@ -345,19 +347,19 @@ Content-Type: application/json
{ "role": "admin" }
```

**Remove member** (removes this tenant’s client roles only):
**Remove member** (removes this tenant’s client roles only; the user stays listed with no role and ensure-self won't give them one back):
```bash
DELETE /management/tenants/{tenantId}/members/{userId}
Authorization: Bearer {access_token}
```

**SSO ensure-self** (no `case.*` scope; requires access-token `org_id` === `tenantId`):
**ensure-self** (no `case.*` scope; only in the `DEFAULT_TENANT_ID` tenant, `system` by default):
```bash
POST /management/tenants/{tenantId}/members/ensure-self
Authorization: Bearer {access_token}
```

Assigns default `author` roles on first login when the org claim matches. Re-authenticate afterward so the JWT includes the new scopes.
Assigns default `author` roles on first login to a user who has no role and has never had one (tracked in the `opencaseRoleProvisioned` user attribute). Returns `status: "assigned"` when it did; the caller should then refresh its access token so the JWT includes the new scopes.

#### OpenCASE API Keys

Expand Down
7 changes: 6 additions & 1 deletion apps/opencase/src/infrastructure/config/Config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,12 @@ export interface AppConfig {
// Keycloak realm SSL enforcement ('none' for HTTP dev, 'external' for production HTTPS)
keycloakRealmSslRequired: 'none' | 'external' | 'all';

/** The OpenCASE tenant (the part after the client id prefix in Keycloak). */
defaultTenantId: string;

/**
* Access-token claim from federated IdP (Auth0) carrying the organization id.
* Convention: claim value equals OpenCASE tenantId (1:1).
* Unused: CASE Global identifies the org from its API key, not this claim. Candidate for removal.
*/
ssoOrgClaim: string;

Expand Down Expand Up @@ -100,6 +103,8 @@ export function loadConfig(): AppConfig {

keycloakRealmSslRequired: (process.env.KEYCLOAK_SSL_REQUIRED ?? (isProduction ? 'external' : 'none')) as 'none' | 'external' | 'all',

defaultTenantId: process.env.DEFAULT_TENANT_ID?.trim() || 'system',

ssoOrgClaim: process.env.SSO_ORG_CLAIM ?? 'org_id',

cgeTokenUrl: process.env.CGE_TOKEN_URL ?? '',
Expand Down
12 changes: 12 additions & 0 deletions apps/opencase/src/infrastructure/config/__tests__/Config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ describe('Config', () => {
delete process.env.KEYCLOAK_BOOTSTRAP_SYSTEM_ADMIN;
delete process.env.KEYCLOAK_SYSTEM_ADMIN_EMAIL;
delete process.env.KEYCLOAK_SYSTEM_ADMIN_PASSWORD;
delete process.env.DEFAULT_TENANT_ID;

const config = loadConfig();

Expand All @@ -49,6 +50,7 @@ describe('Config', () => {
expect(config.keycloakBootstrapSystemAdmin).toBe(true);
expect(config.keycloakSystemAdminEmail).toBe('system-admin@local');
expect(config.keycloakSystemAdminPassword).toBe('admin');
expect(config.defaultTenantId).toBe('system');
expect(config.ssoOrgClaim).toBe('org_id');
expect(config.cgeTokenUrl).toBe('');
expect(config.cgeApiBaseUrl).toBe('');
Expand Down Expand Up @@ -79,6 +81,7 @@ describe('Config', () => {
process.env.KEYCLOAK_BOOTSTRAP_SYSTEM_ADMIN = 'true';
process.env.KEYCLOAK_SYSTEM_ADMIN_EMAIL = 'sys@local';
process.env.KEYCLOAK_SYSTEM_ADMIN_PASSWORD = 'pw';
process.env.DEFAULT_TENANT_ID = 'acme';

const config = loadConfig();

Expand All @@ -95,6 +98,15 @@ describe('Config', () => {
expect(config.keycloakBootstrapSystemAdmin).toBe(true);
expect(config.keycloakSystemAdminEmail).toBe('sys@local');
expect(config.keycloakSystemAdminPassword).toBe('pw');
expect(config.defaultTenantId).toBe('acme');
});

it('should fall back to the system tenant when DEFAULT_TENANT_ID is blank', () => {
process.env.DEFAULT_TENANT_ID = ' ';

const config = loadConfig();

expect(config.defaultTenantId).toBe('system');
});

it('should convert PORT string to number', () => {
Expand Down
73 changes: 73 additions & 0 deletions apps/opencase/src/infrastructure/keycloak/KeycloakAdminClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ export interface KeycloakAdminClientConfig {
password?: string
}

/** User attribute marking that OpenCASE has managed this user's member role at least once. */
export const MEMBER_ROLE_PROVISIONED_ATTRIBUTE = 'opencaseRoleProvisioned'

type TokenResponse = {
access_token: string
expires_in: number
Expand Down Expand Up @@ -218,6 +221,55 @@ export class KeycloakAdminClient {

if (toRemove.length > 0) await this.removeClientRoles(userId, clientUuid, toRemove)
if (toAdd.length > 0) await this.assignClientRoles(userId, clientUuid, toAdd)
await this.markMemberRoleProvisioned(userId)
}

/**
* Declare the role-provisioned user attribute in the realm user profile (idempotent).
* Keycloak 24+ silently drops attributes the user profile does not declare.
*/
async ensureMemberRoleProvisionedAttribute (): Promise<void> {
const path = `/admin/realms/${encodeURIComponent(this.cfg.realm)}/users/profile`
const profile = await this.requestJson('GET', path)
const attributes = Array.isArray(profile?.attributes) ? profile.attributes : []
if (attributes.some((a: any) => a?.name === MEMBER_ROLE_PROVISIONED_ATTRIBUTE)) return

await this.requestJson('PUT', path, {
...profile,
attributes: [
...attributes,
{
name: MEMBER_ROLE_PROVISIONED_ATTRIBUTE,
displayName: 'OpenCASE role provisioned',
permissions: { view: ['admin'], edit: ['admin'] },
multivalued: false
}
]
})
logger.info({ realm: this.cfg.realm }, 'Declared member-role-provisioned user profile attribute')
}

/**
* True once OpenCASE has set (or removed) this user's member role, so a user whose
* roles were deliberately removed is not given the default role again on next login.
*/
async isMemberRoleProvisioned (userId: string): Promise<boolean> {
const user = await this.requestJson('GET', `/admin/realms/${encodeURIComponent(this.cfg.realm)}/users/${encodeURIComponent(userId)}`)
const values = user?.attributes?.[MEMBER_ROLE_PROVISIONED_ATTRIBUTE]
return Array.isArray(values) && values.includes('true')
}

async markMemberRoleProvisioned (userId: string): Promise<void> {
const path = `/admin/realms/${encodeURIComponent(this.cfg.realm)}/users/${encodeURIComponent(userId)}`
const user = await this.requestJson('GET', path)
if (!user?.id) throw new Error(`Keycloak user '${userId}' not found`)
if (user.attributes?.[MEMBER_ROLE_PROVISIONED_ATTRIBUTE]?.includes('true')) return

// PUT replaces the whole user: a partial body would clear email, names, and other attributes.
await this.requestJson('PUT', path, {
...user,
attributes: { ...(user.attributes ?? {}), [MEMBER_ROLE_PROVISIONED_ATTRIBUTE]: ['true'] }
})
}

async ensureProtocolMapper (clientUuid: string, mapper: any): Promise<void> {
Expand Down Expand Up @@ -383,6 +435,27 @@ export class KeycloakAdminClient {
}))
}

/** List every user in the realm, paging through the Admin API. */
async listUsers (): Promise<Array<{ id: string, username?: string, email?: string }>> {
const realm = this.cfg.realm
const pageSize = 500
const users: Array<{ id: string, username?: string, email?: string }> = []

for (let first = 0; ; first += pageSize) {
const page = await this.requestJson(
'GET',
`/admin/realms/${encodeURIComponent(realm)}/users?briefRepresentation=true&first=${first}&max=${pageSize}`
)
if (!Array.isArray(page)) break
for (const u of page) {
if (u?.id) users.push({ id: u.id, username: u.username, email: u.email })
}
if (page.length < pageSize) break
}

return users
}

async findClientByClientIdPublic (clientId: string): Promise<{ id: string, clientId: string } | null> {
return await this.findClientByClientId(clientId)
}
Expand Down
Loading
Loading