feat: replace hardcoded permission map with direct OAuth2 scope checks

Remove role-to-permission mapping (usePermissions, RequirePermission) and replace
with direct scope reads from the Logto access token JWT. OrgResolver decodes the
scope claim after /api/me resolves and stores scopes in Zustand. RequireScope and
useScopes replace the old hooks/components across all pages.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
hsiegeln
2026-04-05 14:04:06 +02:00
parent 277d5ea638
commit 9c2a1d27b7
13 changed files with 87 additions and 97 deletions

View File

@@ -1,21 +1,23 @@
import { useEffect } from 'react'; import { useEffect } from 'react';
import { useLogto } from '@logto/react';
import { Spinner } from '@cameleer/design-system'; import { Spinner } from '@cameleer/design-system';
import { useMe } from '../api/hooks'; import { useMe } from '../api/hooks';
import { useOrgStore } from './useOrganization'; import { useOrgStore } from './useOrganization';
import { fetchConfig } from '../config';
/** /**
* Fetches /api/me and populates the org store with platform admin status * Fetches /api/me and populates the org store with tenant-to-org mapping.
* and tenant-to-org mapping. Renders children once resolved. * Also reads OAuth2 scopes from the access token and stores them.
* Renders children once resolved.
*/ */
export function OrgResolver({ children }: { children: React.ReactNode }) { export function OrgResolver({ children }: { children: React.ReactNode }) {
const { data: me, isLoading, isError } = useMe(); const { data: me, isLoading, isError } = useMe();
const { setIsPlatformAdmin, setOrganizations, setCurrentOrg, currentOrgId } = useOrgStore(); const { getAccessToken } = useLogto();
const { setOrganizations, setCurrentOrg, setScopes, currentOrgId } = useOrgStore();
useEffect(() => { useEffect(() => {
if (!me) return; if (!me) return;
setIsPlatformAdmin(me.isPlatformAdmin);
// Map tenants: logtoOrgId is the org ID for token scoping, id is the DB UUID // Map tenants: logtoOrgId is the org ID for token scoping, id is the DB UUID
const orgEntries = me.tenants.map((t) => ({ const orgEntries = me.tenants.map((t) => ({
id: t.logtoOrgId, id: t.logtoOrgId,
@@ -29,6 +31,21 @@ export function OrgResolver({ children }: { children: React.ReactNode }) {
if (orgEntries.length === 1 && !currentOrgId) { if (orgEntries.length === 1 && !currentOrgId) {
setCurrentOrg(orgEntries[0].id); setCurrentOrg(orgEntries[0].id);
} }
// Read scopes from the access token JWT payload
fetchConfig().then((config) => {
if (!config.logtoResource) return;
getAccessToken(config.logtoResource).then((token) => {
if (!token) return;
try {
const payload = JSON.parse(atob(token.split('.')[1]));
const scopeStr = (payload.scope as string) ?? '';
setScopes(new Set(scopeStr.split(' ').filter(Boolean)));
} catch {
setScopes(new Set());
}
}).catch(() => setScopes(new Set()));
});
}, [me]); }, [me]);
if (isLoading) { if (isLoading) {

View File

@@ -4,7 +4,7 @@ import { useOrgStore } from './useOrganization';
export function useAuth() { export function useAuth() {
const { isAuthenticated, isLoading, signOut, signIn } = useLogto(); const { isAuthenticated, isLoading, signOut, signIn } = useLogto();
const { currentTenantId, isPlatformAdmin } = useOrgStore(); const { currentTenantId } = useOrgStore();
const logout = useCallback(() => { const logout = useCallback(() => {
signOut(window.location.origin + '/login'); signOut(window.location.origin + '/login');
@@ -14,7 +14,6 @@ export function useAuth() {
isAuthenticated, isAuthenticated,
isLoading, isLoading,
tenantId: currentTenantId, tenantId: currentTenantId,
isPlatformAdmin,
logout, logout,
signIn, signIn,
}; };

View File

@@ -8,23 +8,20 @@ export interface OrgInfo {
} }
interface OrgState { interface OrgState {
currentOrgId: string | null; // Logto org ID — used for getAccessToken(resource, orgId) currentOrgId: string | null; // Logto org ID — used for getAccessToken(resource, orgId)
currentTenantId: string | null; // DB UUID — used for API calls like /api/tenants/{id} currentTenantId: string | null; // DB UUID — used for API calls like /api/tenants/{id}
currentOrgRoles: string[] | null; // Logto org roles for the current org (e.g. 'admin', 'member')
organizations: OrgInfo[]; organizations: OrgInfo[];
isPlatformAdmin: boolean; scopes: Set<string>;
setCurrentOrg: (orgId: string | null) => void; setCurrentOrg: (orgId: string | null) => void;
setOrganizations: (orgs: OrgInfo[]) => void; setOrganizations: (orgs: OrgInfo[]) => void;
setIsPlatformAdmin: (value: boolean) => void; setScopes: (scopes: Set<string>) => void;
setCurrentOrgRoles: (roles: string[] | null) => void;
} }
export const useOrgStore = create<OrgState>((set, get) => ({ export const useOrgStore = create<OrgState>((set, get) => ({
currentOrgId: null, currentOrgId: null,
currentTenantId: null, currentTenantId: null,
currentOrgRoles: null,
organizations: [], organizations: [],
isPlatformAdmin: false, scopes: new Set(),
setCurrentOrg: (orgId) => { setCurrentOrg: (orgId) => {
const org = get().organizations.find((o) => o.id === orgId); const org = get().organizations.find((o) => o.id === orgId);
set({ currentOrgId: orgId, currentTenantId: org?.tenantId ?? null }); set({ currentOrgId: orgId, currentTenantId: org?.tenantId ?? null });
@@ -38,6 +35,5 @@ export const useOrgStore = create<OrgState>((set, get) => ({
currentTenantId: match?.tenantId ?? get().currentTenantId, currentTenantId: match?.tenantId ?? get().currentTenantId,
}); });
}, },
setIsPlatformAdmin: (value) => set({ isPlatformAdmin: value }), setScopes: (scopes) => set({ scopes }),
setCurrentOrgRoles: (roles) => set({ currentOrgRoles: roles }),
})); }));

5
ui/src/auth/useScopes.ts Normal file
View File

@@ -0,0 +1,5 @@
import { useOrgStore } from './useOrganization';
export function useScopes() {
return useOrgStore((state) => state.scopes);
}

View File

@@ -6,6 +6,7 @@ import {
TopBar, TopBar,
} from '@cameleer/design-system'; } from '@cameleer/design-system';
import { useAuth } from '../auth/useAuth'; import { useAuth } from '../auth/useAuth';
import { useScopes } from '../auth/useScopes';
import { EnvironmentTree } from './EnvironmentTree'; import { EnvironmentTree } from './EnvironmentTree';
// Simple SVG logo mark for the sidebar header // Simple SVG logo mark for the sidebar header
@@ -100,7 +101,8 @@ function PlatformIcon() {
export function Layout() { export function Layout() {
const navigate = useNavigate(); const navigate = useNavigate();
const { logout, isPlatformAdmin } = useAuth(); const { logout } = useAuth();
const scopes = useScopes();
const [envSectionOpen, setEnvSectionOpen] = useState(true); const [envSectionOpen, setEnvSectionOpen] = useState(true);
const [collapsed, setCollapsed] = useState(false); const [collapsed, setCollapsed] = useState(false);
@@ -144,7 +146,7 @@ export function Layout() {
</Sidebar.Section> </Sidebar.Section>
{/* Platform Admin section */} {/* Platform Admin section */}
{isPlatformAdmin && ( {scopes.has('platform:admin') && (
<Sidebar.Section <Sidebar.Section
icon={<PlatformIcon />} icon={<PlatformIcon />}
label="Platform" label="Platform"

View File

@@ -1,13 +0,0 @@
import { usePermissions } from '../hooks/usePermissions';
interface Props {
permission: string;
children: React.ReactNode;
fallback?: React.ReactNode;
}
export function RequirePermission({ permission, children, fallback }: Props) {
const { has } = usePermissions();
if (!has(permission)) return fallback ? <>{fallback}</> : null;
return <>{children}</>;
}

View File

@@ -0,0 +1,13 @@
import { useScopes } from '../auth/useScopes';
interface Props {
scope: string;
children: React.ReactNode;
fallback?: React.ReactNode;
}
export function RequireScope({ scope, children, fallback }: Props) {
const scopes = useScopes();
if (!scopes.has(scope)) return fallback ? <>{fallback}</> : null;
return <>{children}</>;
}

View File

@@ -1,30 +0,0 @@
import { useOrgStore } from '../auth/useOrganization';
const ROLE_PERMISSIONS: Record<string, string[]> = {
'admin': [
'tenant:manage', 'billing:manage', 'team:manage', 'apps:manage',
'apps:deploy', 'secrets:manage', 'observe:read', 'observe:debug',
'settings:manage',
],
'member': ['apps:deploy', 'observe:read', 'observe:debug'],
};
export function usePermissions() {
const { currentOrgRoles } = useOrgStore();
const roles = currentOrgRoles ?? [];
const permissions = new Set<string>();
for (const role of roles) {
const perms = ROLE_PERMISSIONS[role];
if (perms) perms.forEach((p) => permissions.add(p));
}
return {
has: (permission: string) => permissions.has(permission),
canManageApps: permissions.has('apps:manage'),
canDeploy: permissions.has('apps:deploy'),
canManageTenant: permissions.has('tenant:manage'),
canViewObservability: permissions.has('observe:read'),
roles,
};
}

View File

@@ -32,9 +32,9 @@ import {
useLogs, useLogs,
useCreateApp, useCreateApp,
} from '../api/hooks'; } from '../api/hooks';
import { RequirePermission } from '../components/RequirePermission'; import { RequireScope } from '../components/RequireScope';
import { DeploymentStatusBadge } from '../components/DeploymentStatusBadge'; import { DeploymentStatusBadge } from '../components/DeploymentStatusBadge';
import { usePermissions } from '../hooks/usePermissions'; import { useScopes } from '../auth/useScopes';
import type { DeploymentResponse } from '../types/api'; import type { DeploymentResponse } from '../types/api';
// ─── Types ─────────────────────────────────────────────────────────────────── // ─── Types ───────────────────────────────────────────────────────────────────
@@ -119,7 +119,9 @@ export function AppDetailPage() {
const navigate = useNavigate(); const navigate = useNavigate();
const { toast } = useToast(); const { toast } = useToast();
const { tenantId } = useAuth(); const { tenantId } = useAuth();
const { canManageApps, canDeploy } = usePermissions(); const scopes = useScopes();
const canManageApps = scopes.has('apps:manage');
const canDeploy = scopes.has('apps:deploy');
// Active tab // Active tab
const [activeTab, setActiveTab] = useState('overview'); const [activeTab, setActiveTab] = useState('overview');
@@ -399,7 +401,7 @@ export function AppDetailPage() {
{/* Action bar */} {/* Action bar */}
<Card title="Actions"> <Card title="Actions">
<div className="flex flex-wrap gap-2 py-2"> <div className="flex flex-wrap gap-2 py-2">
<RequirePermission permission="apps:deploy"> <RequireScope scope="apps:deploy">
<Button <Button
variant="primary" variant="primary"
size="sm" size="sm"
@@ -408,9 +410,9 @@ export function AppDetailPage() {
> >
Deploy Deploy
</Button> </Button>
</RequirePermission> </RequireScope>
<RequirePermission permission="apps:deploy"> <RequireScope scope="apps:deploy">
<Button <Button
variant="secondary" variant="secondary"
size="sm" size="sm"
@@ -420,9 +422,9 @@ export function AppDetailPage() {
> >
Restart Restart
</Button> </Button>
</RequirePermission> </RequireScope>
<RequirePermission permission="apps:deploy"> <RequireScope scope="apps:deploy">
<Button <Button
variant="secondary" variant="secondary"
size="sm" size="sm"
@@ -431,9 +433,9 @@ export function AppDetailPage() {
> >
Stop Stop
</Button> </Button>
</RequirePermission> </RequireScope>
<RequirePermission permission="apps:deploy"> <RequireScope scope="apps:deploy">
<Button <Button
variant="secondary" variant="secondary"
size="sm" size="sm"
@@ -445,9 +447,9 @@ export function AppDetailPage() {
> >
Re-upload JAR Re-upload JAR
</Button> </Button>
</RequirePermission> </RequireScope>
<RequirePermission permission="apps:manage"> <RequireScope scope="apps:manage">
<Button <Button
variant="danger" variant="danger"
size="sm" size="sm"
@@ -455,7 +457,7 @@ export function AppDetailPage() {
> >
Delete App Delete App
</Button> </Button>
</RequirePermission> </RequireScope>
</div> </div>
</Card> </Card>
@@ -552,11 +554,11 @@ export function AppDetailPage() {
</div> </div>
)} )}
</div> </div>
<RequirePermission permission="apps:manage"> <RequireScope scope="apps:manage">
<Button variant="secondary" size="sm" onClick={openRoutingModal}> <Button variant="secondary" size="sm" onClick={openRoutingModal}>
Edit Routing Edit Routing
</Button> </Button>
</RequirePermission> </RequireScope>
</div> </div>
</Card> </Card>
</div> </div>

View File

@@ -10,7 +10,7 @@ import {
} from '@cameleer/design-system'; } from '@cameleer/design-system';
import { useAuth } from '../auth/useAuth'; import { useAuth } from '../auth/useAuth';
import { useTenant, useEnvironments, useApps } from '../api/hooks'; import { useTenant, useEnvironments, useApps } from '../api/hooks';
import { RequirePermission } from '../components/RequirePermission'; import { RequireScope } from '../components/RequireScope';
import type { EnvironmentResponse, AppResponse } from '../types/api'; import type { EnvironmentResponse, AppResponse } from '../types/api';
// Helper: fetches apps for one environment and reports data upward via effect // Helper: fetches apps for one environment and reports data upward via effect
@@ -126,7 +126,7 @@ export function DashboardPage() {
)} )}
</div> </div>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<RequirePermission permission="apps:manage"> <RequireScope scope="apps:manage">
<Button <Button
variant="secondary" variant="secondary"
size="sm" size="sm"
@@ -134,7 +134,7 @@ export function DashboardPage() {
> >
New Environment New Environment
</Button> </Button>
</RequirePermission> </RequireScope>
<Button <Button
variant="primary" variant="primary"
size="sm" size="sm"
@@ -193,11 +193,11 @@ export function DashboardPage() {
title="No environments yet" title="No environments yet"
description="Create your first environment to get started deploying Camel applications." description="Create your first environment to get started deploying Camel applications."
action={ action={
<RequirePermission permission="apps:manage"> <RequireScope scope="apps:manage">
<Button variant="primary" onClick={() => navigate('/environments/new')}> <Button variant="primary" onClick={() => navigate('/environments/new')}>
Create Environment Create Environment
</Button> </Button>
</RequirePermission> </RequireScope>
} }
/> />
)} )}

View File

@@ -23,7 +23,7 @@ import {
useApps, useApps,
useCreateApp, useCreateApp,
} from '../api/hooks'; } from '../api/hooks';
import { RequirePermission } from '../components/RequirePermission'; import { RequireScope } from '../components/RequireScope';
import { DeploymentStatusBadge } from '../components/DeploymentStatusBadge'; import { DeploymentStatusBadge } from '../components/DeploymentStatusBadge';
import type { AppResponse } from '../types/api'; import type { AppResponse } from '../types/api';
@@ -188,7 +188,7 @@ export function EnvironmentDetailPage() {
{/* Header */} {/* Header */}
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<RequirePermission <RequireScope
permission="apps:manage" permission="apps:manage"
fallback={ fallback={
<h1 className="text-2xl font-semibold text-white"> <h1 className="text-2xl font-semibold text-white">
@@ -201,7 +201,7 @@ export function EnvironmentDetailPage() {
onSave={handleRename} onSave={handleRename}
placeholder="Environment name" placeholder="Environment name"
/> />
</RequirePermission> </RequireScope>
<Badge label={environment.slug} color="primary" variant="outlined" /> <Badge label={environment.slug} color="primary" variant="outlined" />
<Badge <Badge
label={environment.status} label={environment.status}
@@ -209,12 +209,12 @@ export function EnvironmentDetailPage() {
/> />
</div> </div>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<RequirePermission permission="apps:deploy"> <RequireScope scope="apps:deploy">
<Button variant="primary" size="sm" onClick={openNewApp}> <Button variant="primary" size="sm" onClick={openNewApp}>
New App New App
</Button> </Button>
</RequirePermission> </RequireScope>
<RequirePermission permission="apps:manage"> <RequireScope scope="apps:manage">
<Button <Button
variant="danger" variant="danger"
size="sm" size="sm"
@@ -224,7 +224,7 @@ export function EnvironmentDetailPage() {
> >
Delete Environment Delete Environment
</Button> </Button>
</RequirePermission> </RequireScope>
</div> </div>
</div> </div>
@@ -234,11 +234,11 @@ export function EnvironmentDetailPage() {
title="No apps yet" title="No apps yet"
description="Deploy your first Camel application to this environment." description="Deploy your first Camel application to this environment."
action={ action={
<RequirePermission permission="apps:deploy"> <RequireScope scope="apps:deploy">
<Button variant="primary" onClick={openNewApp}> <Button variant="primary" onClick={openNewApp}>
New App New App
</Button> </Button>
</RequirePermission> </RequireScope>
} }
/> />
) : ( ) : (

View File

@@ -15,7 +15,7 @@ import {
import type { Column } from '@cameleer/design-system'; import type { Column } from '@cameleer/design-system';
import { useAuth } from '../auth/useAuth'; import { useAuth } from '../auth/useAuth';
import { useEnvironments, useCreateEnvironment } from '../api/hooks'; import { useEnvironments, useCreateEnvironment } from '../api/hooks';
import { RequirePermission } from '../components/RequirePermission'; import { RequireScope } from '../components/RequireScope';
import type { EnvironmentResponse } from '../types/api'; import type { EnvironmentResponse } from '../types/api';
interface TableRow { interface TableRow {
@@ -120,11 +120,11 @@ export function EnvironmentsPage() {
{/* Page header */} {/* Page header */}
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<h1 className="text-2xl font-semibold text-white">Environments</h1> <h1 className="text-2xl font-semibold text-white">Environments</h1>
<RequirePermission permission="apps:manage"> <RequireScope scope="apps:manage">
<Button variant="primary" size="sm" onClick={openModal}> <Button variant="primary" size="sm" onClick={openModal}>
Create Environment Create Environment
</Button> </Button>
</RequirePermission> </RequireScope>
</div> </div>
{/* Table / empty state */} {/* Table / empty state */}
@@ -133,11 +133,11 @@ export function EnvironmentsPage() {
title="No environments yet" title="No environments yet"
description="Create your first environment to start deploying Camel applications." description="Create your first environment to start deploying Camel applications."
action={ action={
<RequirePermission permission="apps:manage"> <RequireScope scope="apps:manage">
<Button variant="primary" onClick={openModal}> <Button variant="primary" onClick={openModal}>
Create Environment Create Environment
</Button> </Button>
</RequirePermission> </RequireScope>
} }
/> />
) : ( ) : (

View File

@@ -86,7 +86,6 @@ export interface LogEntry {
export interface MeResponse { export interface MeResponse {
userId: string; userId: string;
isPlatformAdmin: boolean;
tenants: Array<{ tenants: Array<{
id: string; id: string;
name: string; name: string;