mirror of https://github.com/grafana/grafana
Alerting: Add manage permissions UI logic for Contact Points (#92885)
* Add showPolicies prop * Add manage permissions component for easier reuse within alerting * Add method for checking whether to show access control within alerting * Remove accidental console.log from main * Tweak styling for contact point width and add manage permissions drawer * Improve typing for access control type response * Add basic test for manage permissions on contact points list * Only show manage permissions if grafana AM and alertingApiServer is enabled * Update i18n * Add test utils for turning features on and back off * Add access control handlers * Update tests with new util * Pass AM in and add tests * Receiver OSS resource permissions There is a complication that is not fully addressed: Viewer defaults to read:* and Editor defaults to read+write+delete:* This is different to other resource permissions where non-admin are not granted any global permissions and instead access is handled solely by resource-specific permissions that are populated on create and removed on delete. This allows them to easily remove permission to view or edit a single resource from basic roles. The reason this is tricky here is that we have multiple APIs that can create/delete receivers: config api, provisioning api, and k8s receivers api. Config api in particular is not well-equipped to determine when creates/deletes are happening and thus ensuring that the proper resource-specific permissions are created/deleted is finicky. We would also have to create a migration to populate resource-specific permissions for all current receivers. This migration would need to be reset so it can run again if the flag is disabled. * Add access control permissions * Pass in contact point ID to receivers form * Temporarily remove access control check for contact points * Include access control metadata in k8s receiver List & Get GET: Always included. LIST: Included by adding a label selector with value `grafana.com/accessControl` * Include new permissions for contact points navbar * Fix receiver creator fixed role to not give global read * Include in-use metadata in k8s receiver List & Get GET: Always included. LIST: Included by adding a label selector with value `grafana.com/inUse` * Add receiver creator permission to receiver writer * Add receiver creator permission to navbar * Always allow listing receivers, don't return 403 * Remove receiver read precondition from receiver create Otherwise, Creator role will not be able to create their first receiver * Update routes permissions * Add further support for RBAC in contact points * Update routes permissions * Update contact points header logic * Back out test feature toggle refactor Not working atm, not sure why * Tidy up imports * Update mock permissions * Revert more test changes * Update i18n * Sync inuse metadata pr * Add back canAdmin permissions after main merge * Split out check for policies navtree item * Tidy up utils and imports and fix rules in use * Fix contact point tests and act warnings * Add missing ReceiverPermissionAdmin after merge conflict * Move contact points permissions * Only show contact points filter when permissions are correct * Move to constants * Fallback to empty array and remove labelSelectors (not needed) * Allow `toAbility` to take multiple actions * Show builtin alertmanager if contact points permission * Add empty state and hide templates if missing permissions * Translations * Tidy up mock data * Fix tests and templates permission * Update message for unused contact points * Don't return 403 when user lists receivers and has access to none * Fix receiver create not adding empty uid permissions * Move SetDefaultPermissions to ReceiverPermissionService * Have SetDefaultPermissions use uid from string Fixes circular dependency * Add FakeReceiverPermissionsService and fix test wiring * Implement resource permission handling in provisioning API and renames Create: Sets to default permissions Delete: Removes permissions Update: If receiver name is modified and the new name doesn't exist, it copies the permissions from the old receiver to the newly created one. If old receiver is now empty, it removes the old permissions as well. * Split contact point permissions checks for read/modify * Generalise getting annotation values from k8s entities * Proxy RouteDeleteAlertingConfig through MultiOrgAlertmanager * Cleanup permissions on config api reset and restore * Cleanup permissions on config api POST note this is still not available with feature flag enabled * Gate the permission manager behind FF until initial migration is added * Sync changes from config api PR * Switch to named export * Revert unnecessary changes * Revert Filter auth change and implement in k8s api only * Don't allow new scoped permissions to give access without FF Prevents complications around mixed support for the scoped permissions causing oddities in the UI. * Fix integration tests to account for list permission change * Move to `permissions` file * Add additional tests for contact points * Fix redirect for viewer on edit page * Combine alerting test utils and move to new file location * Allow new permissions to access provisioning export paths with FF * Always allow exporting if its grafana flavoured * Fix logic for showing auto generated policies * Fix delete logic for contact point only referenced by a rule * Suppress warning message when renaming a contact point * Clear team and role perm cache on receiver rename Prevents temporarily broken UI permissions after rename when a user's source of elevated permissions comes from a cached team or basic role permission. * Debug log failed cache clear on CopyPermissions --------- Co-authored-by: Matt Jacobson <matthew.jacobson@grafana.com>field_config_one_click_datalinks^2
parent
86faeae6d2
commit
fc51ec70ba
@ -0,0 +1,25 @@ |
||||
import { AccessControlAction } from 'app/types'; |
||||
|
||||
/** |
||||
* List of granular permissions that allow viewing contact points |
||||
* |
||||
* Any permission in this list will be checked for client side access to view Contact Points functionality. |
||||
*/ |
||||
const PERMISSIONS_CONTACT_POINTS_READ = [AccessControlAction.AlertingReceiversRead]; |
||||
|
||||
/** |
||||
* List of granular permissions that allow modifying contact points |
||||
*/ |
||||
export const PERMISSIONS_CONTACT_POINTS_MODIFY = [ |
||||
AccessControlAction.AlertingReceiversCreate, |
||||
AccessControlAction.AlertingReceiversWrite, |
||||
]; |
||||
|
||||
/** |
||||
* List of all permissions that allow contact points read/write functionality |
||||
* |
||||
* Any permission in this list will also be checked for whether the built-in Grafana Alertmanager is shown |
||||
* (as the implication is that if they have one of these permissions, then they should be able to see Grafana AM in the AM selector) |
||||
*/ |
||||
|
||||
export const PERMISSIONS_CONTACT_POINTS = [...PERMISSIONS_CONTACT_POINTS_READ, ...PERMISSIONS_CONTACT_POINTS_MODIFY]; |
@ -0,0 +1,71 @@ |
||||
import { useState, ComponentProps } from 'react'; |
||||
|
||||
import { Button, Drawer } from '@grafana/ui'; |
||||
import { Permissions } from 'app/core/components/AccessControl'; |
||||
import { t, Trans } from 'app/core/internationalization'; |
||||
|
||||
type ButtonProps = { onClick: () => void }; |
||||
|
||||
type BaseProps = Pick<ComponentProps<typeof Permissions>, 'resource' | 'resourceId'> & { |
||||
resourceName?: string; |
||||
title?: string; |
||||
}; |
||||
|
||||
type Props = BaseProps & { |
||||
renderButton?: (props: ButtonProps) => JSX.Element; |
||||
}; |
||||
|
||||
/** |
||||
* Renders just the drawer containing permissions management for the resource. |
||||
* |
||||
* Useful for manually controlling the state/display of the drawer when you need to render the |
||||
* controlling button within a dropdown etc. |
||||
*/ |
||||
export const ManagePermissionsDrawer = ({ |
||||
resourceName, |
||||
title, |
||||
onClose, |
||||
...permissionsProps |
||||
}: BaseProps & Pick<ComponentProps<typeof Drawer>, 'onClose'>) => { |
||||
const defaultTitle = t('alerting.manage-permissions.title', 'Manage permissions'); |
||||
return ( |
||||
<Drawer onClose={onClose} title={title || defaultTitle} subtitle={resourceName}> |
||||
<Permissions {...permissionsProps} canSetPermissions></Permissions> |
||||
</Drawer> |
||||
); |
||||
}; |
||||
|
||||
/** Default way to render the button for "manage permissions" */ |
||||
const DefaultButton = ({ onClick }: ButtonProps) => { |
||||
return ( |
||||
<Button variant="secondary" onClick={onClick} icon="unlock"> |
||||
<Trans i18nKey="alerting.manage-permissions.button">Manage permissions</Trans> |
||||
</Button> |
||||
); |
||||
}; |
||||
|
||||
/** |
||||
* Renders a button that opens a drawer with the permissions editor. |
||||
* |
||||
* Provides capability to render button as custom component, and manages open/close state internally |
||||
*/ |
||||
export const ManagePermissions = ({ resource, resourceId, resourceName, title, renderButton }: Props) => { |
||||
const [showDrawer, setShowDrawer] = useState(false); |
||||
const closeDrawer = () => setShowDrawer(false); |
||||
const openDrawer = () => setShowDrawer(true); |
||||
|
||||
return ( |
||||
<> |
||||
{renderButton ? renderButton({ onClick: openDrawer }) : <DefaultButton onClick={openDrawer} />} |
||||
{showDrawer && ( |
||||
<ManagePermissionsDrawer |
||||
resource={resource} |
||||
resourceId={resourceId} |
||||
resourceName={resourceName} |
||||
title={title} |
||||
onClose={closeDrawer} |
||||
/> |
||||
)} |
||||
</> |
||||
); |
||||
}; |
@ -0,0 +1,67 @@ |
||||
import { HttpResponse, http } from 'msw'; |
||||
|
||||
import { Description, ResourcePermission } from 'app/core/components/AccessControl/types'; |
||||
import { AccessControlAction } from 'app/types'; |
||||
|
||||
// TODO: Expand this out to more realistic use cases as we work on RBAC for contact points
|
||||
const resourceDescriptionsMap: Record<string, Description> = { |
||||
receivers: { |
||||
assignments: { |
||||
users: true, |
||||
serviceAccounts: true, |
||||
teams: true, |
||||
builtInRoles: true, |
||||
}, |
||||
permissions: ['View', 'Edit', 'Admin'], |
||||
}, |
||||
}; |
||||
|
||||
/** |
||||
* Map of pre-determined resources and corresponding IDs for those resources, |
||||
* to permissions for those resources |
||||
* */ |
||||
const resourceDetailsMap: Record<string, Record<string, ResourcePermission[]>> = { |
||||
receivers: { |
||||
lotsaEmails: [ |
||||
{ |
||||
id: 123, |
||||
roleName: 'somerole:name', |
||||
isManaged: true, |
||||
isInherited: false, |
||||
isServiceAccount: false, |
||||
builtInRole: 'Viewer', |
||||
actions: [AccessControlAction.FoldersRead, AccessControlAction.AlertingRuleRead], |
||||
permission: 'View', |
||||
}, |
||||
], |
||||
}, |
||||
}; |
||||
|
||||
const getAccessControlResourceDescriptionHandler = () => |
||||
http.get<{ resourceType: string }>(`/api/access-control/:resourceType/description`, ({ params }) => { |
||||
const matchedResourceDescription = resourceDescriptionsMap[params.resourceType]; |
||||
return matchedResourceDescription |
||||
? HttpResponse.json(matchedResourceDescription) |
||||
: HttpResponse.json({ message: 'Not found' }, { status: 404 }); |
||||
}); |
||||
|
||||
const getAccessControlResourceDetailsHandler = () => |
||||
http.get<{ resourceType: string; resourceId: string }>( |
||||
`/api/access-control/:resourceType/:resourceId`, |
||||
({ params }) => { |
||||
const matchedResourceDetails = resourceDetailsMap[params.resourceType][params.resourceId]; |
||||
return matchedResourceDetails |
||||
? HttpResponse.json(matchedResourceDetails) |
||||
: HttpResponse.json( |
||||
{ |
||||
message: 'Failed to get permissions', |
||||
traceID: '', |
||||
}, |
||||
{ status: 404 } |
||||
); |
||||
} |
||||
); |
||||
|
||||
const handlers = [getAccessControlResourceDescriptionHandler(), getAccessControlResourceDetailsHandler()]; |
||||
|
||||
export default handlers; |
@ -0,0 +1,49 @@ |
||||
import { act } from '@testing-library/react'; |
||||
|
||||
import { FeatureToggles } from '@grafana/data'; |
||||
import { config } from '@grafana/runtime'; |
||||
|
||||
/** |
||||
* Flushes out microtasks so we don't get warnings from `@floating-ui/react` |
||||
* as per https://floating-ui.com/docs/react#testing
|
||||
*/ |
||||
export const flushMicrotasks = async () => { |
||||
await act(async () => { |
||||
await new Promise((resolve) => setTimeout(resolve, 0)); |
||||
}); |
||||
}; |
||||
|
||||
/** |
||||
* Enables feature toggles `beforeEach` test, and sets back to original settings `afterEach` test |
||||
*/ |
||||
export const testWithFeatureToggles = (featureToggles: Array<keyof FeatureToggles>) => { |
||||
const originalToggles = { ...config.featureToggles }; |
||||
|
||||
beforeEach(() => { |
||||
featureToggles.forEach((featureToggle) => { |
||||
config.featureToggles[featureToggle] = true; |
||||
}); |
||||
}); |
||||
|
||||
afterEach(() => { |
||||
config.featureToggles = originalToggles; |
||||
}); |
||||
}; |
||||
|
||||
/** |
||||
* Enables license features `beforeEach` test, and sets back to original settings `afterEach` test |
||||
*/ |
||||
export const testWithLicenseFeatures = (features: string[]) => { |
||||
const originalFeatures = { ...config.licenseInfo.enabledFeatures }; |
||||
beforeEach(() => { |
||||
config.licenseInfo.enabledFeatures = config.licenseInfo.enabledFeatures || {}; |
||||
|
||||
features.forEach((feature) => { |
||||
config.licenseInfo.enabledFeatures[feature] = true; |
||||
}); |
||||
}); |
||||
|
||||
afterEach(() => { |
||||
config.licenseInfo.enabledFeatures = originalFeatures; |
||||
}); |
||||
}; |
@ -1,5 +1,24 @@ |
||||
/** Name of the custom annotation label used in k8s APIs for us to discern if a given entity was provisioned */ |
||||
/** |
||||
* Name of the custom annotation label used in k8s APIs for us to discern if a given entity was provisioned |
||||
* @deprecated Use {@link K8sAnnotations.Provenance} instead |
||||
* */ |
||||
export const PROVENANCE_ANNOTATION = 'grafana.com/provenance'; |
||||
|
||||
/** Value of {@link PROVENANCE_ANNOTATION} given for entities that were not provisioned */ |
||||
export const PROVENANCE_NONE = 'none'; |
||||
|
||||
export enum K8sAnnotations { |
||||
Provenance = 'grafana.com/provenance', |
||||
|
||||
/** Annotation key that indicates how many notification policy routes are using this entity */ |
||||
InUseRoutes = 'grafana.com/inUse/routes', |
||||
/** Annotation key that indicates how many alert rules are using this entity */ |
||||
InUseRules = 'grafana.com/inUse/rules', |
||||
|
||||
/** Annotation key that indicates that the calling user is able to write (edit) this entity */ |
||||
AccessWrite = 'grafana.com/access/canWrite', |
||||
/** Annotation key that indicates that the calling user is able to admin the permissions of this entity */ |
||||
AccessAdmin = 'grafana.com/access/canAdmin', |
||||
/** Annotation key that indicates that the calling user is able to delete this entity */ |
||||
AccessDelete = 'grafana.com/access/canDelete', |
||||
} |
||||
|
Loading…
Reference in new issue