TT-007.1: establish module-owned authorization boundary
This commit is contained in:
@@ -15,14 +15,24 @@ router = APIRouter(prefix="/auth", tags=["Auth"])
|
||||
|
||||
|
||||
def _build_user_response(user: User, db: Session) -> dict:
|
||||
"""Build user response for /auth/me.
|
||||
|
||||
Platform is authority for:
|
||||
- User identity
|
||||
- Platform-level permissions (platform.*)
|
||||
- Module access list (which modules user can access)
|
||||
|
||||
Module is authority for:
|
||||
- Module permissions (request.*, etc.)
|
||||
- Effective policy computation
|
||||
"""
|
||||
global_roles = [ur.role.name for ur in user.user_roles if ur.role]
|
||||
mod_roles = {}
|
||||
|
||||
# Collect permissions from global roles
|
||||
# Collect PLATFORM permissions only (Platform is authority for platform.*)
|
||||
permissions = set()
|
||||
for ur in user.user_roles:
|
||||
if ur.role:
|
||||
# Map role names to permissions
|
||||
role = ur.role
|
||||
if role.name == "platform_admin":
|
||||
permissions.update([
|
||||
@@ -40,19 +50,15 @@ def _build_user_response(user: User, db: Session) -> dict:
|
||||
"platform.users.write",
|
||||
])
|
||||
|
||||
# Collect module roles
|
||||
# Collect module roles (for module access, NOT for permission computation)
|
||||
# Module permissions are computed by Module, not Platform
|
||||
module_access = []
|
||||
for umr in user.user_module_roles:
|
||||
if umr.module_role and umr.module_role.module:
|
||||
slug = umr.module_role.module.slug
|
||||
mod_roles.setdefault(slug, []).append(umr.module_role.role_name)
|
||||
# Add module permissions based on role
|
||||
role_name = umr.module_role.role_name
|
||||
if role_name == "admin":
|
||||
permissions.update([f"{slug}.read", f"{slug}.write", f"{slug}.delete"])
|
||||
elif role_name in ("support_agent", "manager"):
|
||||
permissions.update([f"{slug}.read", f"{slug}.write"])
|
||||
elif role_name == "customer":
|
||||
permissions.add(f"{slug}.read")
|
||||
if slug not in module_access:
|
||||
module_access.append(slug)
|
||||
|
||||
return {
|
||||
"id": user.id,
|
||||
@@ -63,7 +69,8 @@ def _build_user_response(user: User, db: Session) -> dict:
|
||||
"is_superadmin": user.is_superadmin,
|
||||
"roles": global_roles,
|
||||
"module_roles": mod_roles,
|
||||
"permissions": list(permissions),
|
||||
"permissions": list(permissions), # Platform permissions only
|
||||
"module_access": module_access, # Which modules user can access
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
"""Authorization Boundary Tests — TT-007.1
|
||||
|
||||
Tests for Module-Owned Permission Boundary.
|
||||
Verifies that:
|
||||
- Module is authority for its own permissions
|
||||
- Platform does not compute module permissions
|
||||
- /auth/me returns identity + module_access, not module permissions
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def test_auth_me_returns_module_access(client, admin_token):
|
||||
"""Test that /auth/me returns module_access field."""
|
||||
response = client.get("/api/v1/auth/me", headers={
|
||||
"Authorization": f"Bearer {admin_token}"
|
||||
})
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert "module_access" in data
|
||||
assert isinstance(data["module_access"], list)
|
||||
|
||||
|
||||
def test_auth_me_no_module_permissions(client, admin_token):
|
||||
"""Test that /auth/me does NOT return module permissions (request.*, etc.)."""
|
||||
response = client.get("/api/v1/auth/me", headers={
|
||||
"Authorization": f"Bearer {admin_token}"
|
||||
})
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
permissions = data.get("permissions", [])
|
||||
# Module permissions should NOT be in /auth/me
|
||||
module_perms = [p for p in permissions if p.startswith("request.")]
|
||||
assert len(module_perms) == 0, f"Module permissions found in /auth/me: {module_perms}"
|
||||
|
||||
|
||||
def test_auth_me_has_platform_permissions(client, admin_token):
|
||||
"""Test that /auth/me still returns platform permissions."""
|
||||
response = client.get("/api/v1/auth/me", headers={
|
||||
"Authorization": f"Bearer {admin_token}"
|
||||
})
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
# Platform permissions should still be there
|
||||
assert "platform.dashboard.read" in data["permissions"]
|
||||
assert "platform.users.read" in data["permissions"]
|
||||
|
||||
|
||||
def test_auth_me_identity_fields(client, admin_token):
|
||||
"""Test that /auth/me returns identity fields."""
|
||||
response = client.get("/api/v1/auth/me", headers={
|
||||
"Authorization": f"Bearer {admin_token}"
|
||||
})
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
# Identity fields
|
||||
assert "id" in data
|
||||
assert "email" in data
|
||||
assert "first_name" in data
|
||||
assert "last_name" in data
|
||||
assert "is_active" in data
|
||||
assert "is_superadmin" in data
|
||||
assert "roles" in data
|
||||
|
||||
|
||||
def test_login_returns_user_with_module_access(client, admin_user):
|
||||
"""Test that login response includes module_access."""
|
||||
response = client.post("/api/v1/auth/login", json={
|
||||
"email": "admin@test.com",
|
||||
"password": "admin123",
|
||||
})
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert "user" in data
|
||||
assert "module_access" in data["user"]
|
||||
@@ -45,7 +45,8 @@ export default function Layout() {
|
||||
// Filter modules based on permissions
|
||||
const visibleModules = modules.filter(mod => {
|
||||
// Check if user has at least read permission for the module
|
||||
return hasPermission(`${mod.id}.read`) || user?.is_superadmin
|
||||
// Module permissions come from Module API, not from Platform superadmin status
|
||||
return hasPermission(`${mod.id}.read`)
|
||||
})
|
||||
|
||||
return (
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { createContext, useContext, useState, useEffect, useCallback } from 'react'
|
||||
import type { ReactNode } from 'react'
|
||||
import { authApi } from '../api/client'
|
||||
import api from '../api/client'
|
||||
|
||||
interface User {
|
||||
id: number
|
||||
@@ -11,7 +12,8 @@ interface User {
|
||||
is_superadmin: boolean
|
||||
roles: string[]
|
||||
module_roles: Record<string, string[]>
|
||||
permissions: string[]
|
||||
permissions: string[] // Platform permissions only (platform.*)
|
||||
module_access: string[] // Which modules user can access
|
||||
}
|
||||
|
||||
interface AuthContextType {
|
||||
@@ -21,6 +23,7 @@ interface AuthContextType {
|
||||
logout: () => void
|
||||
hasPermission: (permission: string) => boolean
|
||||
hasAnyPermission: (permissions: string[]) => boolean
|
||||
modulePermissions: Record<string, string[]> // moduleId -> permissions
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthContextType | undefined>(undefined)
|
||||
@@ -28,44 +31,89 @@ const AuthContext = createContext<AuthContextType | undefined>(undefined)
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [user, setUser] = useState<User | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [modulePermissions, setModulePermissions] = useState<Record<string, string[]>>({})
|
||||
|
||||
// Fetch module permissions from Module API
|
||||
const fetchModulePermissions = useCallback(async (moduleAccess: string[]) => {
|
||||
const perms: Record<string, string[]> = {}
|
||||
|
||||
for (const moduleId of moduleAccess) {
|
||||
try {
|
||||
// Module API is mounted on Platform at /api/v1/{moduleId}/permissions/me
|
||||
const res = await api.get(`/${moduleId}/permissions/me`)
|
||||
perms[moduleId] = res.data.permissions || []
|
||||
} catch {
|
||||
// Module might not have permissions endpoint yet
|
||||
perms[moduleId] = []
|
||||
}
|
||||
}
|
||||
|
||||
setModulePermissions(perms)
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
const token = localStorage.getItem('platform_token')
|
||||
if (token) {
|
||||
authApi.me()
|
||||
.then(res => setUser(res.data))
|
||||
.then(res => {
|
||||
const userData = res.data
|
||||
setUser(userData)
|
||||
// Fetch module permissions from Module API
|
||||
if (userData.module_access?.length > 0) {
|
||||
fetchModulePermissions(userData.module_access)
|
||||
}
|
||||
})
|
||||
.catch(() => localStorage.removeItem('platform_token'))
|
||||
.finally(() => setLoading(false))
|
||||
} else {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
}, [fetchModulePermissions])
|
||||
|
||||
const login = async (email: string, password: string) => {
|
||||
const res = await authApi.login({ email, password })
|
||||
localStorage.setItem('platform_token', res.data.access_token)
|
||||
setUser(res.data.user)
|
||||
const userData = res.data.user
|
||||
setUser(userData)
|
||||
// Fetch module permissions from Module API
|
||||
if (userData.module_access?.length > 0) {
|
||||
fetchModulePermissions(userData.module_access)
|
||||
}
|
||||
}
|
||||
|
||||
const logout = () => {
|
||||
localStorage.removeItem('platform_token')
|
||||
setUser(null)
|
||||
setModulePermissions({})
|
||||
}
|
||||
|
||||
const hasPermission = useCallback((permission: string): boolean => {
|
||||
if (!user) return false
|
||||
if (user.is_superadmin) return true
|
||||
return user.permissions?.includes(permission) ?? false
|
||||
}, [user])
|
||||
|
||||
// Platform permissions: superadmin bypass is allowed
|
||||
// Module permissions: superadmin does NOT get automatic access
|
||||
const isPlatformPermission = permission.startsWith('platform.')
|
||||
|
||||
if (isPlatformPermission && user.is_superadmin) return true
|
||||
|
||||
// Check platform permissions (from /auth/me)
|
||||
if (user.permissions?.includes(permission)) return true
|
||||
|
||||
// Check module permissions (from Module API — authoritative source)
|
||||
for (const moduleId of Object.keys(modulePermissions)) {
|
||||
if (modulePermissions[moduleId]?.includes(permission)) return true
|
||||
}
|
||||
|
||||
return false
|
||||
}, [user, modulePermissions])
|
||||
|
||||
const hasAnyPermission = useCallback((permissions: string[]): boolean => {
|
||||
if (!user) return false
|
||||
if (user.is_superadmin) return true
|
||||
return permissions.some(p => user.permissions?.includes(p) ?? false)
|
||||
}, [user])
|
||||
return permissions.some(p => hasPermission(p))
|
||||
}, [user, hasPermission])
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ user, loading, login, logout, hasPermission, hasAnyPermission }}>
|
||||
<AuthContext.Provider value={{ user, loading, login, logout, hasPermission, hasAnyPermission, modulePermissions }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user