Compare commits

..

5 Commits

Author SHA1 Message Date
Gabriel Mabille 4919bce269 WIP 2026-01-14 22:14:21 +01:00
Gabriel Mabille c4c48da441 Merge remote-tracking branch 'origin/main' into gamab/authz/global-roles 2026-01-14 17:43:47 +01:00
Adela Almasan 99acd3766d Suggestions: Update empty state (#116172) 2026-01-14 10:37:42 -06:00
Gabriel Mabille 1cbeec336b Merge remote-tracking branch 'origin/main' into gamab/authz/global-roles 2026-01-14 16:05:53 +01:00
Gabriel Mabille 1b15ee6cab Add GlobalRole api 2026-01-13 10:43:49 +01:00
51 changed files with 251 additions and 62 deletions
+1
View File
@@ -25,6 +25,7 @@ coreroleKind: {
globalroleKind: {
kind: "GlobalRole"
pluralName: "GlobalRoles"
scope: "Cluster"
codegen: {
ts: { enabled: false }
go: { enabled: true }
+1 -1
View File
@@ -11,7 +11,7 @@ import (
// schema is unexported to prevent accidental overwrites
var (
schemaGlobalRole = resource.NewSimpleSchema("iam.grafana.app", "v0alpha1", NewGlobalRole(), &GlobalRoleList{}, resource.WithKind("GlobalRole"),
resource.WithPlural("globalroles"), resource.WithScope(resource.NamespacedScope))
resource.WithPlural("globalroles"), resource.WithScope(resource.ClusterScope))
kindGlobalRole = resource.Kind{
Schema: schemaGlobalRole,
Codecs: map[resource.KindEncoding]resource.Codec{
@@ -74,6 +74,33 @@ var RoleInfo = utils.NewResourceInfo(GROUP, VERSION,
},
)
var GlobalRoleInfo = globalRoleInfo.WithClusterScope()
var globalRoleInfo = utils.NewResourceInfo(GROUP, VERSION,
"globalroles", "globalrole", "GlobalRole",
func() runtime.Object { return &GlobalRole{} },
func() runtime.Object { return &GlobalRoleList{} },
utils.TableColumns{
Definition: []metav1.TableColumnDefinition{
{Name: "Name", Type: "string", Format: "name"},
{Name: "Group", Type: "string", Format: "group", Description: "Role group"},
{Name: "Title", Type: "string", Format: "string", Description: "Role name"},
{Name: "Created At", Type: "date"},
},
Reader: func(obj any) ([]interface{}, error) {
globalRole, ok := obj.(*GlobalRole)
if ok {
return []interface{}{
globalRole.Name,
globalRole.Spec.Group,
globalRole.Spec.Title,
globalRole.CreationTimestamp.UTC().Format(time.RFC3339),
}, nil
}
return nil, fmt.Errorf("expected global role")
},
},
)
var ResourcePermissionInfo = utils.NewResourceInfo(GROUP, VERSION,
"resourcepermissions", "resourcepermission", "ResourcePermission",
func() runtime.Object { return &ResourcePermission{} },
@@ -308,6 +335,14 @@ func AddResourcePermissionKnownTypes(scheme *runtime.Scheme, version schema.Grou
return nil
}
func AddGlobalRoleKnownTypes(scheme *runtime.Scheme) error {
scheme.AddKnownTypes(SchemeGroupVersion,
&GlobalRole{},
&GlobalRoleList{},
)
return nil
}
func AddAuthNKnownTypes(scheme *runtime.Scheme) error {
scheme.AddKnownTypes(SchemeGroupVersion,
// Identity
+3 -1
View File
@@ -18,6 +18,8 @@ import (
v0alpha1 "github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1"
)
var ()
var appManifestData = app.ManifestData{
AppName: "iam",
Group: "iam.grafana.app",
@@ -30,7 +32,7 @@ var appManifestData = app.ManifestData{
{
Kind: "GlobalRole",
Plural: "GlobalRoles",
Scope: "Namespaced",
Scope: "Cluster",
Conversion: false,
},
+4
View File
@@ -966,6 +966,10 @@ export interface FeatureToggles {
*/
kubernetesAuthzRolesApi?: boolean;
/**
* Registers AuthZ Global Roles /apis endpoint
*/
kubernetesAuthzGlobalRolesApi?: boolean;
/**
* Registers AuthZ Role Bindings /apis endpoint
*/
kubernetesAuthzRoleBindingsApi?: boolean;
@@ -22,7 +22,7 @@ import { getBarColorByDiff, getBarColorByPackage, getBarColorByValue } from './c
import { CollapseConfig, CollapsedMap, FlameGraphDataContainer, LevelItem } from './dataTransform';
type RenderOptions = {
canvasRef: RefObject<HTMLCanvasElement | null>;
canvasRef: RefObject<HTMLCanvasElement>;
data: FlameGraphDataContainer;
root: LevelItem;
direction: 'children' | 'parents';
@@ -373,7 +373,7 @@ function useColorFunction(
);
}
function useSetupCanvas(canvasRef: RefObject<HTMLCanvasElement | null>, wrapperWidth: number, numberOfLevels: number) {
function useSetupCanvas(canvasRef: RefObject<HTMLCanvasElement>, wrapperWidth: number, numberOfLevels: number) {
const [ctx, setCtx] = useState<CanvasRenderingContext2D>();
useEffect(() => {
@@ -7,7 +7,7 @@ const CAUGHT_KEYS = ['ArrowUp', 'ArrowDown', 'Home', 'End', 'Enter', 'Tab'];
/** @internal */
export interface UseListFocusProps {
localRef: RefObject<HTMLUListElement | null>;
localRef: RefObject<HTMLUListElement>;
options: TimeOption[];
}
@@ -1,7 +1,7 @@
import { RefObject, useRef } from 'react';
export function useFocus(): [RefObject<HTMLInputElement | null>, () => void] {
const ref = useRef<HTMLInputElement | null>(null);
export function useFocus(): [RefObject<HTMLInputElement>, () => void] {
const ref = useRef<HTMLInputElement>(null);
const setFocus = () => {
ref.current && ref.current.focus();
};
@@ -6,7 +6,7 @@ const UNFOCUSED = -1;
/** @internal */
export interface UseMenuFocusProps {
localRef: RefObject<HTMLDivElement | null>;
localRef: RefObject<HTMLDivElement>;
isMenuOpen?: boolean;
close?: () => void;
onOpen?: (focusOnItem: (itemId: number) => void) => void;
@@ -22,7 +22,7 @@ interface Props extends Omit<BoxProps, 'display' | 'direction' | 'element' | 'fl
*
* https://developers.grafana.com/ui/latest/index.html?path=/docs/layout-scrollcontainer--docs
*/
export const ScrollContainer = forwardRef<HTMLDivElement | null, PropsWithChildren<Props>>(
export const ScrollContainer = forwardRef<HTMLDivElement, PropsWithChildren<Props>>(
(
{
children,
@@ -20,7 +20,7 @@ export interface TableCellTooltipProps {
field: Field;
getActions: (field: Field, rowIdx: number) => ActionModel[];
getTextColorForBackground: (bgColor: string) => string;
gridRef: RefObject<DataGridHandle | null>;
gridRef: RefObject<DataGridHandle>;
height: number;
placement?: TableCellTooltipPlacement;
renderer: TableCellRenderer;
@@ -463,7 +463,7 @@ export function useColumnResize(
return dataGridResizeHandler;
}
export function useScrollbarWidth(ref: RefObject<DataGridHandle | null>, height: number) {
export function useScrollbarWidth(ref: RefObject<DataGridHandle>, height: number) {
const [scrollbarWidth, setScrollbarWidth] = useState(0);
useLayoutEffect(() => {
@@ -135,7 +135,7 @@ export const Table = memo((props: Props) => {
// `useTableStateReducer`, which is needed to construct options for `useTable` (the hook that returns
// `toggleAllRowsExpanded`), and if we used a variable, that variable would be undefined at the time
// we initialize `useTableStateReducer`.
const toggleAllRowsExpandedRef = useRef<((value?: boolean) => void) | null>(null);
const toggleAllRowsExpandedRef = useRef<(value?: boolean) => void>();
// Internal react table state reducer
const stateReducer = useTableStateReducer({
@@ -14,8 +14,8 @@ import { GrafanaTableState } from './types';
Select the scrollbar element from the VariableSizeList scope
*/
export function useFixScrollbarContainer(
variableSizeListScrollbarRef: React.RefObject<HTMLDivElement | null>,
tableDivRef: React.RefObject<HTMLDivElement | null>
variableSizeListScrollbarRef: React.RefObject<HTMLDivElement>,
tableDivRef: React.RefObject<HTMLDivElement>
) {
useEffect(() => {
if (variableSizeListScrollbarRef.current && tableDivRef.current) {
@@ -43,7 +43,7 @@ export function useFixScrollbarContainer(
*/
export function useResetVariableListSizeCache(
extendedState: GrafanaTableState,
listRef: React.RefObject<VariableSizeList | null>,
listRef: React.RefObject<VariableSizeList>,
data: DataFrame,
hasUniqueId: boolean
) {
@@ -19,7 +19,7 @@ interface EventsCanvasProps {
}
export function EventsCanvas({ id, events, renderEventMarker, mapEventToXYCoords, config }: EventsCanvasProps) {
const plotInstance = useRef<uPlot | null>(null);
const plotInstance = useRef<uPlot>();
// render token required to re-render annotation markers. Rendering lines happens in uPlot and the props do not change
// so we need to force the re-render when the draw hook was performed by uPlot
const [renderToken, setRenderToken] = useState(0);
@@ -140,7 +140,7 @@ export const TooltipPlugin2 = ({
const [{ plot, isHovering, isPinned, contents, style, dismiss }, setState] = useReducer(mergeState, null, initState);
const sizeRef = useRef<TooltipContainerSize | null>(null);
const sizeRef = useRef<TooltipContainerSize>();
const styles = useStyles2(getStyles, maxWidth);
const renderRef = useRef(render);
@@ -96,7 +96,7 @@ export interface GraphNGState {
export class GraphNG extends Component<GraphNGProps, GraphNGState> {
static contextType = PanelContextRoot;
panelContext: PanelContext = {} as PanelContext;
private plotInstance: React.RefObject<uPlot | null>;
private plotInstance: React.RefObject<uPlot>;
private subscription = new Subscription();
+10
View File
@@ -39,6 +39,9 @@ type ApiInstaller[T runtime.Object] interface {
// while keeping the core IAM registration logic in OSS.
type RoleApiInstaller ApiInstaller[*iamv0.Role]
// GlobalRoleApiInstaller provides GlobalRole-specific API registration and validation.
type GlobalRoleApiInstaller ApiInstaller[*iamv0.GlobalRole]
// NoopApiInstaller is a no-op implementation for when roles are not available (OSS).
type NoopApiInstaller[T runtime.Object] struct {
ResourceInfo utils.ResourceInfo
@@ -77,3 +80,10 @@ func ProvideNoopRoleApiInstaller() RoleApiInstaller {
ResourceInfo: iamv0.RoleInfo,
}
}
// ProvideNoopGlobalRoleApiInstaller provides a no-op global role installer specifically for GlobalRole types.
func ProvideNoopGlobalRoleApiInstaller() GlobalRoleApiInstaller {
return &NoopApiInstaller[*iamv0.GlobalRole]{
ResourceInfo: iamv0.GlobalRoleInfo,
}
}
+3
View File
@@ -23,6 +23,7 @@ func newIAMAuthorizer(
accessClient authlib.AccessClient,
legacyAccessClient authlib.AccessClient,
roleApiInstaller RoleApiInstaller,
globalRoleApiInstaller GlobalRoleApiInstaller,
) authorizer.Authorizer {
resourceAuthorizer := make(map[string]authorizer.Authorizer)
@@ -58,6 +59,8 @@ func newIAMAuthorizer(
resourceAuthorizer["searchUsers"] = serviceAuthorizer
resourceAuthorizer["searchTeams"] = serviceAuthorizer
resourceAuthorizer[iamv0.GlobalRoleInfo.GetName()] = globalRoleApiInstaller.GetAuthorizer()
return &iamAuthorizer{resourceAuthorizer: resourceAuthorizer}
}
+1
View File
@@ -57,6 +57,7 @@ type IdentityAccessManagementAPIBuilder struct {
ssoLegacyStore *sso.LegacyStore
coreRolesStorage CoreRoleStorageBackend
roleApiInstaller RoleApiInstaller
globalRoleApiInstaller GlobalRoleApiInstaller
resourcePermissionsStorage resource.StorageBackend
roleBindingsStorage RoleBindingStorageBackend
externalGroupMappingStorage ExternalGroupMappingStorageBackend
+31 -3
View File
@@ -75,6 +75,7 @@ func RegisterAPIService(
reg prometheus.Registerer,
coreRolesStorage CoreRoleStorageBackend,
roleApiInstaller RoleApiInstaller,
globalRoleApiInstaller GlobalRoleApiInstaller,
tracing *tracing.TracingService,
roleBindingsStorage RoleBindingStorageBackend,
externalGroupMappingStorageBackend ExternalGroupMappingStorageBackend,
@@ -89,7 +90,7 @@ func RegisterAPIService(
dbProvider := legacysql.NewDatabaseProvider(sql)
store := legacy.NewLegacySQLStores(dbProvider)
legacyAccessClient := newLegacyAccessClient(ac, store)
authorizer := newIAMAuthorizer(accessClient, legacyAccessClient, roleApiInstaller)
authorizer := newIAMAuthorizer(accessClient, legacyAccessClient, roleApiInstaller, globalRoleApiInstaller)
registerMetrics(reg)
//nolint:staticcheck // not yet migrated to OpenFeature
@@ -109,6 +110,7 @@ func RegisterAPIService(
ssoLegacyStore: sso.NewLegacyStore(ssoService, tracing),
coreRolesStorage: coreRolesStorage,
roleApiInstaller: roleApiInstaller,
globalRoleApiInstaller: globalRoleApiInstaller,
resourcePermissionsStorage: resourcepermission.ProvideStorageBackend(dbProvider),
roleBindingsStorage: roleBindingsStorage,
externalGroupMappingStorage: externalGroupMappingStorageBackend,
@@ -174,6 +176,7 @@ func NewAPIService(
zTickets: make(chan bool, MaxConcurrentZanzanaWrites),
reg: reg,
roleApiInstaller: roleApiInstaller,
globalRoleApiInstaller: ProvideNoopGlobalRoleApiInstaller(), // TODO: add a proper global role installer
authorizer: authorizer.AuthorizerFunc(
func(ctx context.Context, a authorizer.Attributes) (authorizer.Decision, string, error) {
user, ok := types.AuthInfoFrom(ctx)
@@ -219,12 +222,20 @@ func (b *IdentityAccessManagementAPIBuilder) InstallSchema(scheme *runtime.Schem
enableCoreRolesApi := client.Boolean(ctx, featuremgmt.FlagKubernetesAuthzCoreRolesApi, false, openfeature.TransactionContext(ctx))
enableRolesApi := client.Boolean(ctx, featuremgmt.FlagKubernetesAuthzRolesApi, false, openfeature.TransactionContext(ctx))
enableRoleBindingsApi := client.Boolean(ctx, featuremgmt.FlagKubernetesAuthzRoleBindingsApi, false, openfeature.TransactionContext(ctx))
enableGlobalRolesApi := client.Boolean(ctx, featuremgmt.FlagKubernetesAuthzGlobalRolesApi, false, openfeature.TransactionContext(ctx))
if enableCoreRolesApi || enableRolesApi || enableRoleBindingsApi {
if err := iamv0.AddAuthZKnownTypes(scheme); err != nil {
return err
}
}
if enableGlobalRolesApi {
if err := iamv0.AddGlobalRoleKnownTypes(scheme); err != nil {
return err
}
}
//nolint:staticcheck // not yet migrated to OpenFeature
if b.features.IsEnabledGlobally(featuremgmt.FlagKubernetesAuthzResourcePermissionApis) {
if err := iamv0.AddResourcePermissionKnownTypes(scheme, iamv0.SchemeGroupVersion); err != nil {
@@ -264,6 +275,7 @@ func (b *IdentityAccessManagementAPIBuilder) UpdateAPIGroupInfo(apiGroupInfo *ge
enableCoreRolesApi := client.Boolean(ctx, featuremgmt.FlagKubernetesAuthzCoreRolesApi, false, openfeature.TransactionContext(ctx))
enableRolesApi := client.Boolean(ctx, featuremgmt.FlagKubernetesAuthzRolesApi, false, openfeature.TransactionContext(ctx))
enableRoleBindingsApi := client.Boolean(ctx, featuremgmt.FlagKubernetesAuthzRoleBindingsApi, false, openfeature.TransactionContext(ctx))
enableGlobalRolesApi := client.Boolean(ctx, featuremgmt.FlagKubernetesAuthzGlobalRolesApi, false, openfeature.TransactionContext(ctx))
// teams + users must have shorter names because they are often used as part of another name
opts.StorageOptsRegister(iamv0.TeamResourceInfo.GroupResource(), apistore.StorageOptions{
@@ -313,6 +325,12 @@ func (b *IdentityAccessManagementAPIBuilder) UpdateAPIGroupInfo(apiGroupInfo *ge
}
}
if enableGlobalRolesApi {
if err := b.globalRoleApiInstaller.RegisterStorage(apiGroupInfo, &opts, storage); err != nil {
return err
}
}
if enableRoleBindingsApi {
if err := b.UpdateRoleBindingsAPIGroup(apiGroupInfo, opts, storage, enableZanzanaSync); err != nil {
return err
@@ -664,6 +682,8 @@ func (b *IdentityAccessManagementAPIBuilder) Validate(ctx context.Context, a adm
return externalgroupmapping.ValidateOnCreate(typedObj)
case *iamv0.Role:
return b.roleApiInstaller.ValidateOnCreate(ctx, typedObj)
case *iamv0.GlobalRole:
return b.globalRoleApiInstaller.ValidateOnCreate(ctx, typedObj)
}
return nil
case admission.Update:
@@ -694,12 +714,20 @@ func (b *IdentityAccessManagementAPIBuilder) Validate(ctx context.Context, a adm
return fmt.Errorf("expected old object to be a Role, got %T", oldRoleObj)
}
return b.roleApiInstaller.ValidateOnUpdate(ctx, oldRoleObj, typedObj)
case *iamv0.GlobalRole:
oldGlobalRoleObj, ok := a.GetOldObject().(*iamv0.GlobalRole)
if !ok {
return fmt.Errorf("expected old object to be a GlobalRole, got %T", oldGlobalRoleObj)
}
return b.globalRoleApiInstaller.ValidateOnUpdate(ctx, oldGlobalRoleObj, typedObj)
}
return nil
case admission.Delete:
switch oldRoleObj := a.GetOldObject().(type) {
switch oldObj := a.GetOldObject().(type) {
case *iamv0.Role:
return b.roleApiInstaller.ValidateOnDelete(ctx, oldRoleObj)
return b.roleApiInstaller.ValidateOnDelete(ctx, oldObj)
case *iamv0.GlobalRole:
return b.globalRoleApiInstaller.ValidateOnDelete(ctx, oldObj)
}
return nil
case admission.Connect:
+1
View File
@@ -29,6 +29,7 @@ var WireSetExts = wire.NewSet(
noopstorage.ProvideStorageBackend,
wire.Bind(new(iam.CoreRoleStorageBackend), new(*noopstorage.StorageBackendImpl)),
iam.ProvideNoopRoleApiInstaller,
iam.ProvideNoopGlobalRoleApiInstaller,
wire.Bind(new(iam.RoleBindingStorageBackend), new(*noopstorage.StorageBackendImpl)),
wire.Bind(new(iam.ExternalGroupMappingStorageBackend), new(*noopstorage.StorageBackendImpl)),
+4 -2
View File
@@ -882,8 +882,9 @@ func Initialize(ctx context.Context, cfg *setting.Cfg, opts Options, apiOpts api
folderAPIBuilder := folders.RegisterAPIService(cfg, featureToggles, apiserverService, folderimplService, folderPermissionsService, accessControl, acimplService, accessClient, registerer, resourceClient, zanzanaClient)
storageBackendImpl := noopstorage.ProvideStorageBackend()
roleApiInstaller := iam.ProvideNoopRoleApiInstaller()
globalRoleApiInstaller := iam.ProvideNoopGlobalRoleApiInstaller()
noopTeamGroupsREST := externalgroupmapping.ProvideNoopTeamGroupsREST()
identityAccessManagementAPIBuilder, err := iam.RegisterAPIService(cfg, featureToggles, apiserverService, ssosettingsimplService, sqlStore, accessControl, accessClient, zanzanaClient, registerer, storageBackendImpl, roleApiInstaller, tracingService, storageBackendImpl, storageBackendImpl, noopTeamGroupsREST, dualwriteService, resourceClient, orgService, userService, teamService, eventualRestConfigProvider)
identityAccessManagementAPIBuilder, err := iam.RegisterAPIService(cfg, featureToggles, apiserverService, ssosettingsimplService, sqlStore, accessControl, accessClient, zanzanaClient, registerer, storageBackendImpl, roleApiInstaller, globalRoleApiInstaller, tracingService, storageBackendImpl, storageBackendImpl, noopTeamGroupsREST, dualwriteService, resourceClient, orgService, userService, teamService, eventualRestConfigProvider)
if err != nil {
return nil, err
}
@@ -1550,8 +1551,9 @@ func InitializeForTest(ctx context.Context, t sqlutil.ITestDB, testingT interfac
folderAPIBuilder := folders.RegisterAPIService(cfg, featureToggles, apiserverService, folderimplService, folderPermissionsService, accessControl, acimplService, accessClient, registerer, resourceClient, zanzanaClient)
storageBackendImpl := noopstorage.ProvideStorageBackend()
roleApiInstaller := iam.ProvideNoopRoleApiInstaller()
globalRoleApiInstaller := iam.ProvideNoopGlobalRoleApiInstaller()
noopTeamGroupsREST := externalgroupmapping.ProvideNoopTeamGroupsREST()
identityAccessManagementAPIBuilder, err := iam.RegisterAPIService(cfg, featureToggles, apiserverService, ssosettingsimplService, sqlStore, accessControl, accessClient, zanzanaClient, registerer, storageBackendImpl, roleApiInstaller, tracingService, storageBackendImpl, storageBackendImpl, noopTeamGroupsREST, dualwriteService, resourceClient, orgService, userService, teamService, eventualRestConfigProvider)
identityAccessManagementAPIBuilder, err := iam.RegisterAPIService(cfg, featureToggles, apiserverService, ssosettingsimplService, sqlStore, accessControl, accessClient, zanzanaClient, registerer, storageBackendImpl, roleApiInstaller, globalRoleApiInstaller, tracingService, storageBackendImpl, storageBackendImpl, noopTeamGroupsREST, dualwriteService, resourceClient, orgService, userService, teamService, eventualRestConfigProvider)
if err != nil {
return nil, err
}
+7
View File
@@ -1597,6 +1597,13 @@ var (
Owner: identityAccessTeam,
HideFromDocs: true,
},
{
Name: "kubernetesAuthzGlobalRolesApi",
Description: "Registers AuthZ Global Roles /apis endpoint",
Stage: FeatureStageExperimental,
Owner: identityAccessTeam,
HideFromDocs: true,
},
{
Name: "kubernetesAuthzRoleBindingsApi",
Description: "Registers AuthZ Role Bindings /apis endpoint",
+1
View File
@@ -219,6 +219,7 @@ kubernetesAuthzResourcePermissionApis,experimental,@grafana/identity-access-team
kubernetesAuthzZanzanaSync,experimental,@grafana/identity-access-team,false,false,false
kubernetesAuthzCoreRolesApi,experimental,@grafana/identity-access-team,false,false,false
kubernetesAuthzRolesApi,experimental,@grafana/identity-access-team,false,false,false
kubernetesAuthzGlobalRolesApi,experimental,@grafana/identity-access-team,false,false,false
kubernetesAuthzRoleBindingsApi,experimental,@grafana/identity-access-team,false,false,false
kubernetesAuthnMutation,experimental,@grafana/identity-access-team,false,false,false
kubernetesExternalGroupMapping,experimental,@grafana/identity-access-team,false,false,false
1 Name Stage Owner requiresDevMode RequiresRestart FrontendOnly
219 kubernetesAuthzZanzanaSync experimental @grafana/identity-access-team false false false
220 kubernetesAuthzCoreRolesApi experimental @grafana/identity-access-team false false false
221 kubernetesAuthzRolesApi experimental @grafana/identity-access-team false false false
222 kubernetesAuthzGlobalRolesApi experimental @grafana/identity-access-team false false false
223 kubernetesAuthzRoleBindingsApi experimental @grafana/identity-access-team false false false
224 kubernetesAuthnMutation experimental @grafana/identity-access-team false false false
225 kubernetesExternalGroupMapping experimental @grafana/identity-access-team false false false
+4
View File
@@ -650,6 +650,10 @@ const (
// Registers AuthZ Roles /apis endpoint
FlagKubernetesAuthzRolesApi = "kubernetesAuthzRolesApi"
// FlagKubernetesAuthzGlobalRolesApi
// Registers AuthZ Global Roles /apis endpoint
FlagKubernetesAuthzGlobalRolesApi = "kubernetesAuthzGlobalRolesApi"
// FlagKubernetesAuthzRoleBindingsApi
// Registers AuthZ Role Bindings /apis endpoint
FlagKubernetesAuthzRoleBindingsApi = "kubernetesAuthzRoleBindingsApi"
+13
View File
@@ -2024,6 +2024,19 @@
"hideFromDocs": true
}
},
{
"metadata": {
"name": "kubernetesAuthzGlobalRolesApi",
"resourceVersion": "1768294340511",
"creationTimestamp": "2026-01-13T08:52:20Z"
},
"spec": {
"description": "Registers AuthZ Global Roles /apis endpoint",
"stage": "experimental",
"codeowner": "@grafana/identity-access-team",
"hideFromDocs": true
}
},
{
"metadata": {
"name": "kubernetesAuthzResourcePermissionApis",
@@ -109,7 +109,7 @@ const defaultMatchers = {
* "Time as X" core component, expects ascending x
*/
export class GraphNG extends Component<GraphNGProps, GraphNGState> {
private plotInstance: React.RefObject<uPlot | null>;
private plotInstance: React.RefObject<uPlot>;
constructor(props: GraphNGProps) {
super(props);
@@ -33,7 +33,7 @@ global.ResizeObserver = jest.fn().mockImplementation((callback) => {
});
// Helper function to assign a mock div to a ref
function assignMockDivToRef(ref: React.RefObject<HTMLDivElement | null>, mockDiv: HTMLDivElement) {
function assignMockDivToRef(ref: React.RefObject<HTMLDivElement>, mockDiv: HTMLDivElement) {
// Use type assertion to bypass readonly restriction in tests
(ref as { current: HTMLDivElement | null }).current = mockDiv;
}
@@ -8,7 +8,7 @@ import grafanaTextLogoDarkSvg from 'img/grafana_text_logo_dark.svg';
import grafanaTextLogoLightSvg from 'img/grafana_text_logo_light.svg';
interface SoloPanelPageLogoProps {
containerRef: React.RefObject<HTMLDivElement | null>;
containerRef: React.RefObject<HTMLDivElement>;
isHovered: boolean;
hideLogo?: UrlQueryValue;
}
@@ -61,7 +61,7 @@ interface State {
class UnThemedTransformationsEditor extends React.PureComponent<TransformationsEditorProps, State> {
subscription?: Unsubscribable;
ref: RefObject<HTMLDivElement | null>;
ref: RefObject<HTMLDivElement>;
constructor(props: TransformationsEditorProps) {
super(props);
@@ -43,7 +43,7 @@ export const LibraryPanelsView = ({
}
);
const asyncDispatch = useMemo(() => asyncDispatcher(dispatch), [dispatch]);
const abortControllerRef = useRef<AbortController | null>(null);
const abortControllerRef = useRef<AbortController>();
useDebounce(
() => {
@@ -12,7 +12,7 @@ export interface Props {}
export const LiveConnectionWarning = memo(function LiveConnectionWarning() {
const [show, setShow] = useState<boolean | undefined>(undefined);
const subscriptionRef = useRef<Unsubscribable | null>(null);
const subscriptionRef = useRef<Unsubscribable>();
const styles = useStyles2(getStyle);
useEffect(() => {
@@ -2,8 +2,9 @@ import { render, screen } from '@testing-library/react';
import { defaultsDeep } from 'lodash';
import { Provider } from 'react-redux';
import { FieldType, getDefaultTimeRange, LoadingState } from '@grafana/data';
import { PanelDataErrorViewProps } from '@grafana/runtime';
import { CoreApp, EventBusSrv, FieldType, getDefaultTimeRange, LoadingState } from '@grafana/data';
import { config, PanelDataErrorViewProps } from '@grafana/runtime';
import { usePanelContext } from '@grafana/ui';
import { configureStore } from 'app/store/configureStore';
import { PanelDataErrorView } from './PanelDataErrorView';
@@ -16,7 +17,24 @@ jest.mock('app/features/dashboard/services/DashboardSrv', () => ({
},
}));
jest.mock('@grafana/ui', () => ({
...jest.requireActual('@grafana/ui'),
usePanelContext: jest.fn(),
}));
const mockUsePanelContext = jest.mocked(usePanelContext);
const RUN_QUERY_MESSAGE = 'Run a query to visualize it here or go to all visualizations to add other panel types';
const panelContextRoot = {
app: CoreApp.Dashboard,
eventsScope: 'global',
eventBus: new EventBusSrv(),
};
describe('PanelDataErrorView', () => {
beforeEach(() => {
mockUsePanelContext.mockReturnValue(panelContextRoot);
});
it('show No data when there is no data', () => {
renderWithProps();
@@ -70,6 +88,45 @@ describe('PanelDataErrorView', () => {
expect(screen.getByText('Query returned nothing')).toBeInTheDocument();
});
it('should show "Run a query..." message when no query is configured and feature toggle is enabled', () => {
mockUsePanelContext.mockReturnValue(panelContextRoot);
const originalFeatureToggle = config.featureToggles.newVizSuggestions;
config.featureToggles.newVizSuggestions = true;
renderWithProps({
data: {
state: LoadingState.Done,
series: [],
timeRange: getDefaultTimeRange(),
},
});
expect(screen.getByText(RUN_QUERY_MESSAGE)).toBeInTheDocument();
config.featureToggles.newVizSuggestions = originalFeatureToggle;
});
it('should show "No data" message when feature toggle is disabled even without queries', () => {
mockUsePanelContext.mockReturnValue(panelContextRoot);
const originalFeatureToggle = config.featureToggles.newVizSuggestions;
config.featureToggles.newVizSuggestions = false;
renderWithProps({
data: {
state: LoadingState.Done,
series: [],
timeRange: getDefaultTimeRange(),
},
});
expect(screen.getByText('No data')).toBeInTheDocument();
expect(screen.queryByText(RUN_QUERY_MESSAGE)).not.toBeInTheDocument();
config.featureToggles.newVizSuggestions = originalFeatureToggle;
});
});
function renderWithProps(overrides?: Partial<PanelDataErrorViewProps>) {
@@ -5,14 +5,15 @@ import {
FieldType,
getPanelDataSummary,
GrafanaTheme2,
PanelData,
PanelDataSummary,
PanelPluginVisualizationSuggestion,
} from '@grafana/data';
import { selectors } from '@grafana/e2e-selectors';
import { t, Trans } from '@grafana/i18n';
import { PanelDataErrorViewProps, locationService } from '@grafana/runtime';
import { PanelDataErrorViewProps, locationService, config } from '@grafana/runtime';
import { VizPanel } from '@grafana/scenes';
import { usePanelContext, useStyles2 } from '@grafana/ui';
import { Icon, usePanelContext, useStyles2 } from '@grafana/ui';
import { CardButton } from 'app/core/components/CardButton';
import { LS_VISUALIZATION_SELECT_TAB_KEY } from 'app/core/constants';
import store from 'app/core/store';
@@ -24,6 +25,11 @@ import { findVizPanelByKey, getVizPanelKeyForPanelId } from 'app/features/dashbo
import { useDispatch } from 'app/types/store';
import { changePanelPlugin } from '../state/actions';
import { hasData } from '../suggestions/utils';
function hasNoQueryConfigured(data: PanelData): boolean {
return !data.request?.targets || data.request.targets.length === 0;
}
export function PanelDataErrorView(props: PanelDataErrorViewProps) {
const styles = useStyles2(getStyles);
@@ -93,8 +99,14 @@ export function PanelDataErrorView(props: PanelDataErrorViewProps) {
}
};
const noData = !hasData(props.data);
const noQueryConfigured = hasNoQueryConfigured(props.data);
const showEmptyState =
config.featureToggles.newVizSuggestions && context.app === CoreApp.PanelEditor && noQueryConfigured && noData;
return (
<div className={styles.wrapper}>
{showEmptyState && <Icon name="chart-line" size="xxxl" className={styles.emptyStateIcon} />}
<div className={styles.message} data-testid={selectors.components.Panels.Panel.PanelDataErrorMessage}>
{message}
</div>
@@ -131,7 +143,17 @@ function getMessageFor(
return message;
}
if (!data.series || data.series.length === 0 || data.series.every((frame) => frame.length === 0)) {
const noData = !hasData(data);
const noQueryConfigured = hasNoQueryConfigured(data);
if (config.featureToggles.newVizSuggestions && noQueryConfigured && noData) {
return t(
'dashboard.new-panel.empty-state-message',
'Run a query to visualize it here or go to all visualizations to add other panel types'
);
}
if (noData) {
return fieldConfig?.defaults.noValue ?? t('panel.panel-data-error-view.no-value.default', 'No data');
}
@@ -176,5 +198,9 @@ const getStyles = (theme: GrafanaTheme2) => {
width: '100%',
maxWidth: '600px',
}),
emptyStateIcon: css({
color: theme.colors.text.secondary,
marginBottom: theme.spacing(2),
}),
};
};
@@ -38,7 +38,7 @@ export function useSearchKeyboardNavigation(
): ItemSelection {
const highlightIndexRef = useRef<ItemSelection>({ x: 0, y: -1 });
const [highlightIndex, setHighlightIndex] = useState<ItemSelection>({ x: 0, y: -1 });
const urlsRef = useRef<Field | null>(null);
const urlsRef = useRef<Field>();
// Clear selection when the search results change
useEffect(() => {
@@ -77,7 +77,7 @@ export const SuggestionsInput = ({
const theme = useTheme2();
const styles = getStyles(theme, inputHeight);
const inputRef = useRef<HTMLInputElement | HTMLTextAreaElement | null>(null);
const inputRef = useRef<HTMLInputElement | HTMLTextAreaElement>();
useEffect(() => {
scrollRef.current?.scrollTo(0, scrollTop);
@@ -11,7 +11,7 @@ import checkboxWhitePng from 'img/checkbox_white.png';
import { ALL_VARIABLE_VALUE } from '../../constants';
export interface Props extends Omit<React.HTMLProps<HTMLUListElement>, 'onToggle'>, Themeable2 {
export interface Props extends React.HTMLProps<HTMLUListElement>, Themeable2 {
multi: boolean;
values: VariableOption[];
selectedValues: VariableOption[];
@@ -20,8 +20,8 @@ interface CodeEditorProps {
export const LogsQLCodeEditor = (props: CodeEditorProps) => {
const { query, datasource, onChange } = props;
const monacoRef = useRef<Monaco | null>(null);
const disposalRef = useRef<monacoType.IDisposable | undefined>(undefined);
const monacoRef = useRef<Monaco>();
const disposalRef = useRef<monacoType.IDisposable>();
const onFocus = useCallback(async () => {
disposalRef.current = await reRegisterCompletionProvider(
@@ -42,8 +42,8 @@ interface LogsCodeEditorProps {
export const PPLQueryEditor = (props: LogsCodeEditorProps) => {
const { query, datasource, onChange } = props;
const monacoRef = useRef<Monaco | null>(null);
const disposalRef = useRef<monacoType.IDisposable | undefined>(undefined);
const monacoRef = useRef<Monaco>();
const disposalRef = useRef<monacoType.IDisposable>();
const onFocus = useCallback(async () => {
disposalRef.current = await reRegisterCompletionProvider(
@@ -20,8 +20,8 @@ interface SQLCodeEditorProps {
export const SQLQueryEditor = (props: SQLCodeEditorProps) => {
const { query, datasource, onChange } = props;
const monacoRef = useRef<Monaco | null>(null);
const disposalRef = useRef<monacoType.IDisposable | undefined>(undefined);
const monacoRef = useRef<Monaco>();
const disposalRef = useRef<monacoType.IDisposable>();
const onFocus = useCallback(async () => {
disposalRef.current = await reRegisterCompletionProvider(
@@ -94,7 +94,7 @@ const EDITOR_HEIGHT_OFFSET = 2;
* Hook that returns function that will set up monaco autocomplete for the label selector
*/
function useAutocomplete(getLabelValues: (label: string) => Promise<string[]>, labels?: string[]) {
const providerRef = useRef<CompletionProvider | null>(null);
const providerRef = useRef<CompletionProvider>();
if (providerRef.current === undefined) {
providerRef.current = new CompletionProvider();
}
@@ -126,7 +126,7 @@ export function LokiContextUi(props: LokiContextUiProps) {
window.localStorage.getItem(SHOULD_INCLUDE_PIPELINE_OPERATIONS) === 'true'
);
const timerHandle = useRef<number | null>(null);
const timerHandle = useRef<number>();
const previousInitialized = useRef<boolean>(false);
const previousContextFilters = useRef<ContextFilter[]>([]);
@@ -191,18 +191,14 @@ export function LokiContextUi(props: LokiContextUiProps) {
}, 1500);
return () => {
if (timerHandle.current) {
clearTimeout(timerHandle.current);
}
clearTimeout(timerHandle.current);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [contextFilters, initialized]);
useEffect(() => {
return () => {
if (timerHandle.current) {
clearTimeout(timerHandle.current);
}
clearTimeout(timerHandle.current);
onClose();
};
}, [onClose]);
@@ -52,7 +52,7 @@ export function TraceQLEditor(props: Props) {
const onRunQueryRef = useRef(onRunQuery);
onRunQueryRef.current = onRunQuery;
const errorTimeoutId = useRef<number | null>(null);
const errorTimeoutId = useRef<number>();
return (
<>
@@ -103,9 +103,7 @@ export function TraceQLEditor(props: Props) {
}
// Remove previous callback if existing, to prevent squiggles from been shown while the user is still typing
if (errorTimeoutId.current) {
window.clearTimeout(errorTimeoutId.current);
}
window.clearTimeout(errorTimeoutId.current);
const errorNodes = getErrorNodes(model.getValue());
const cursorPosition = changeEvent.changes[0].rangeOffset;
@@ -1,5 +1,5 @@
export function renderHistogram(
can: React.RefObject<HTMLCanvasElement | null>,
can: React.RefObject<HTMLCanvasElement>,
histCanWidth: number,
histCanHeight: number,
xVals: number[],
+1 -1
View File
@@ -196,7 +196,7 @@ export const LogsPanel = ({
const dataSourcesMap = useDatasourcesFromTargets(panelData.request?.targets);
// Prevents the scroll position to change when new data from infinite scrolling is received
const keepScrollPositionRef = useRef<null | 'infinite-scroll' | 'user'>(null);
const closeCallback = useRef<(() => void) | null>(null);
let closeCallback = useRef<() => void>();
const { app, eventBus, onAddAdHocFilter } = usePanelContext();
useEffect(() => {
+1 -1
View File
@@ -70,7 +70,7 @@ export function useLayout(
const currentSignature = createDataSignature(rawNodes, rawEdges);
const isMounted = useMountedState();
const layoutWorkerCancelRef = useRef<(() => void) | null>(null);
const layoutWorkerCancelRef = useRef<(() => void) | undefined>();
useUnmount(() => {
if (layoutWorkerCancelRef.current) {
@@ -133,7 +133,7 @@ export const AnnotationsPlugin2 = ({
const newRangeRef = useRef(newRange);
newRangeRef.current = newRange;
const xAxisRef = useRef<HTMLDivElement | null>(null);
const xAxisRef = useRef<HTMLDivElement>();
useLayoutEffect(() => {
config.addHook('ready', (u) => {
@@ -23,7 +23,7 @@ export const ExemplarsPlugin = ({
maxHeight,
maxWidth,
}: ExemplarsPluginProps) => {
const plotInstance = useRef<uPlot | null>(null);
const plotInstance = useRef<uPlot>();
const [lockedExemplarRowIndex, setLockedExemplarRowIndex] = useState<number | undefined>();
@@ -11,7 +11,7 @@ interface ThresholdControlsPluginProps {
}
export const OutsideRangePlugin = ({ config, onChangeTimeRange }: ThresholdControlsPluginProps) => {
const plotInstance = useRef<uPlot | null>(null);
const plotInstance = useRef<uPlot>();
const [timevalues, setTimeValues] = useState<number[] | TypedArray>([]);
const [timeRange, setTimeRange] = useState<Scale | undefined>();
@@ -16,7 +16,7 @@ interface ThresholdControlsPluginProps {
}
export const ThresholdControlsPlugin = ({ config, fieldConfig, onThresholdsChange }: ThresholdControlsPluginProps) => {
const plotInstance = useRef<uPlot | null>(null);
const plotInstance = useRef<uPlot>();
const [renderToken, setRenderToken] = useState(0);
useLayoutEffect(() => {