Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: client side access control (WIP) #27174

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Open
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
7 changes: 7 additions & 0 deletions frontend/src/exporter/__mocks__/Exporter.mocks.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,7 @@ export const dashboard: DashboardType = {
effective_privilege_level: 37,
timezone: null,
tags: [],
user_access_level: 'editor',
},
} as DashboardTile,
{
Expand Down Expand Up @@ -369,6 +370,7 @@ export const dashboard: DashboardType = {
effective_privilege_level: 37,
timezone: null,
tags: [],
user_access_level: 'editor',
},
} as DashboardTile,
{
Expand Down Expand Up @@ -547,6 +549,7 @@ export const dashboard: DashboardType = {
effective_privilege_level: 37,
timezone: null,
tags: [],
user_access_level: 'editor',
},
} as DashboardTile,
{
Expand Down Expand Up @@ -688,6 +691,7 @@ export const dashboard: DashboardType = {
effective_privilege_level: 37,
timezone: null,
tags: [],
user_access_level: 'editor',
},
} as DashboardTile,
{
Expand Down Expand Up @@ -1107,6 +1111,7 @@ export const dashboard: DashboardType = {
effective_privilege_level: 37,
timezone: null,
tags: [],
user_access_level: 'editor',
},
} as DashboardTile,
{
Expand Down Expand Up @@ -1245,6 +1250,7 @@ export const dashboard: DashboardType = {
effective_privilege_level: 37,
timezone: null,
tags: [],
user_access_level: 'editor',
},
} as DashboardTile,
],
Expand All @@ -1258,4 +1264,5 @@ export const dashboard: DashboardType = {
effective_restriction_level: 37,
effective_privilege_level: 37,
tags: [],
user_access_level: 'editor',
}
6 changes: 5 additions & 1 deletion frontend/src/layout/navigation-3000/Navigation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@ import './Navigation.scss'

import clsx from 'clsx'
import { useValues } from 'kea'
import { AccessDenied } from 'lib/components/AccessDenied'
import { BillingAlertsV2 } from 'lib/components/BillingAlertsV2'
import { CommandBar } from 'lib/components/CommandBar/CommandBar'
import { FlaggedFeature } from 'lib/components/FlaggedFeature'
import { FEATURE_FLAGS } from 'lib/constants'
import { apiStatusLogic } from 'lib/logic/apiStatusLogic'
import { ReactNode } from 'react'
import { SceneConfig } from 'scenes/sceneTypes'

Expand All @@ -30,6 +32,8 @@ export function Navigation({
const { mobileLayout } = useValues(navigationLogic)
const { activeNavbarItem, mode } = useValues(navigation3000Logic)

const { resourceAccessDenied } = useValues(apiStatusLogic)

if (mode !== 'full') {
return (
// eslint-disable-next-line react/forbid-dom-props
Expand Down Expand Up @@ -60,7 +64,7 @@ export function Navigation({
>
{!sceneConfig?.hideBillingNotice && <BillingAlertsV2 />}
{!sceneConfig?.hideProjectNotice && <ProjectNotice />}
{children}
{resourceAccessDenied ? <AccessDenied /> : children}
</div>
</main>
<SidePanel />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
APIScopeObject,
OrganizationMemberType,
RoleType,
WithAccessControl,
} from '~/types'

import type { accessControlLogicType } from './accessControlLogicType'
Expand Down Expand Up @@ -242,6 +243,21 @@ export const accessControlLogic = kea<accessControlLogicType>([
: []
},
],

hasResourceAccess: [
() => [],
() =>
({
userAccessLevel,
requiredLevels,
}: {
userAccessLevel?: WithAccessControl['user_access_level']
requiredLevels: WithAccessControl['user_access_level'][]
}) => {
// Fallback to true if userAccessLevel is not set
return userAccessLevel ? requiredLevels.includes(userAccessLevel) : true
},
],
}),
afterMount(({ actions }) => {
actions.loadAccessControls()
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2677,7 +2677,7 @@ async function handleFetch(url: string, method: string, fetcher: () => Promise<R
error = e
}

apiStatusLogic.findMounted()?.actions.onApiResponse(response, error)
apiStatusLogic.findMounted()?.actions.onApiResponse(response, error, { method })

if (error || !response) {
if (error && (error as any).name === 'AbortError') {
Expand Down
33 changes: 33 additions & 0 deletions frontend/src/lib/components/AccessControlAction.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { useValues } from 'kea'

import { accessControlLogic } from '~/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic'

import { WithAccessControl } from '../../types'

interface AccessControlActionProps {
children: (props: { disabled: boolean; disabledReason: string | null }) => React.ReactElement
userAccessLevel?: WithAccessControl['user_access_level']
requiredLevels: WithAccessControl['user_access_level'][]
resourceType?: string
}

export const AccessControlAction = ({
children,
userAccessLevel,
requiredLevels,
resourceType = 'resource',
}: AccessControlActionProps): JSX.Element => {
const { hasResourceAccess } = useValues(accessControlLogic)

const hasAccess = hasResourceAccess({ userAccessLevel, requiredLevels })
const disabledReason = !hasAccess
? `You don't have sufficient permissions for this ${resourceType}. Your access level (${userAccessLevel}) doesn't meet the required level (${requiredLevels.join(
' or '
)}).`
: null

return children({
disabled: !hasAccess,
disabledReason,
})
}
10 changes: 10 additions & 0 deletions frontend/src/lib/components/AccessDenied/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
export function AccessDenied(): JSX.Element {
return (
<div className="flex flex-col items-center max-w-2xl p-4 my-24 mx-auto text-center">
<h1 className="text-3xl font-bold mt-4 mb-0">Access denied</h1>
<p className="text-sm mt-3 mb-0">
You don't have access to this resource. Please contact support if you think this is a mistake.
</p>
</div>
)
}
33 changes: 30 additions & 3 deletions frontend/src/lib/logic/apiStatusLogic.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,22 @@
import { actions, kea, listeners, path, reducers } from 'kea'
import { actions, connect, kea, listeners, path, reducers } from 'kea'
import { router } from 'kea-router'
import api from 'lib/api'
import { toast } from 'react-toastify'
import { userLogic } from 'scenes/userLogic'

import type { apiStatusLogicType } from './apiStatusLogicType'

export const apiStatusLogic = kea<apiStatusLogicType>([
path(['lib', 'apiStatusLogic']),
connect({
actions: [router, ['locationChanged']],
}),
actions({
onApiResponse: (response?: Response, error?: any) => ({ response, error }),
onApiResponse: (response?: Response, error?: any, extra?: { method: string }) => ({ response, error, extra }),
setInternetConnectionIssue: (issue: boolean) => ({ issue }),
setTimeSensitiveAuthenticationRequired: (required: boolean) => ({ required }),
setResourceAccessDenied: (resource: string) => ({ resource }),
clearResourceAccessDenied: true,
}),

reducers({
Expand All @@ -26,9 +33,17 @@ export const apiStatusLogic = kea<apiStatusLogicType>([
setTimeSensitiveAuthenticationRequired: (_, { required }) => required,
},
],
resourceAccessDenied: [
null as string | null,
{
setResourceAccessDenied: (_, { resource }) => resource,
clearResourceAccessDenied: () => null,
},
],
}),
listeners(({ cache, actions, values }) => ({
onApiResponse: async ({ response, error }, breakpoint) => {
onApiResponse: async ({ response, error, extra }, breakpoint) => {
const { method } = extra || {}
if (error || !response?.status) {
await breakpoint(50)
// Likely CORS headers errors (i.e. request failing without reaching Django))
Expand All @@ -46,6 +61,13 @@ export const apiStatusLogic = kea<apiStatusLogicType>([
const data = await response?.json()
if (data.detail === 'This action requires you to be recently authenticated.') {
actions.setTimeSensitiveAuthenticationRequired(true)
} else if (data.code === 'permission_denied') {
// TODO - only do if the RBAC feature flag is enabled
if (method === 'GET') {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

importing feature flag logic here is breaking this logic so haven't figured out this check yet

actions.setResourceAccessDenied(data.resource || 'resource')
} else {
toast.error('You are not authorized to perform this action')
}
}
}
} catch (e) {
Expand Down Expand Up @@ -73,4 +95,9 @@ export const apiStatusLogic = kea<apiStatusLogicType>([
}
},
})),
listeners(({ actions }) => ({
locationChanged: () => {
actions.clearResourceAccessDenied()
},
})),
])
1 change: 1 addition & 0 deletions frontend/src/models/dashboardsModel.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ const basicDashboard: DashboardBasicType = {
restriction_level: DashboardRestrictionLevel.EveryoneInProjectCanEdit,
effective_restriction_level: DashboardRestrictionLevel.EveryoneInProjectCanEdit,
effective_privilege_level: DashboardPrivilegeLevel.CanEdit,
user_access_level: 'editor',
}

describe('the dashboards model', () => {
Expand Down
Loading
Loading