Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

feat(authz): accept singular roles for user and service accounts (#10827)

Vikrant Gupta55cce3c708e1
diff --git a/frontend/src/components/EditMemberDrawer/EditMemberDrawer.styles.scss b/frontend/src/components/EditMemberDrawer/EditMemberDrawer.styles.scss
index 9f1d6b7d6c..0666fddf80 100644
--- a/frontend/src/components/EditMemberDrawer/EditMemberDrawer.styles.scss
+++ b/frontend/src/components/EditMemberDrawer/EditMemberDrawer.styles.scss
@@ -83,37 +83,6 @@
opacity: 0.6;
}
- &__role-select {
- width: 100%;
-
- .ant-select-selector {
- background-color: var(--l2-background) !important;
- border-color: var(--border) !important;
- border-radius: 2px;
- padding: var(--padding-1) var(--padding-2) !important;
- display: flex;
- align-items: center;
- flex-wrap: wrap;
- min-height: 32px;
- height: auto !important;
- }
-
- .ant-select-selection-item {
- font-size: var(--font-size-sm);
- color: var(--l1-foreground);
- line-height: 22px;
- letter-spacing: -0.07px;
- }
-
- .ant-select-arrow {
- color: var(--foreground);
- }
-
- &:not(.ant-select-disabled):hover .ant-select-selector {
- border-color: var(--foreground);
- }
- }
-
&__meta {
display: flex;
flex-direction: column;
diff --git a/frontend/src/components/EditMemberDrawer/EditMemberDrawer.tsx b/frontend/src/components/EditMemberDrawer/EditMemberDrawer.tsx
index 192007b0d8..591c3c55ee 100644
--- a/frontend/src/components/EditMemberDrawer/EditMemberDrawer.tsx
+++ b/frontend/src/components/EditMemberDrawer/EditMemberDrawer.tsx
@@ -61,10 +61,6 @@ function toSaveApiError(err: unknown): APIError {
);
}
-function areSortedArraysEqual(a: string[], b: string[]): boolean {
- return JSON.stringify([...a].sort()) === JSON.stringify([...b].sort());
-}
-
export interface EditMemberDrawerProps {
member: MemberRow | null;
open: boolean;
@@ -83,7 +79,7 @@ function EditMemberDrawer({
const { user: currentUser } = useAppContext();
const [localDisplayName, setLocalDisplayName] = useState('');
- const [localRoles, setLocalRoles] = useState<string[]>([]);
+ const [localRole, setLocalRole] = useState('');
const [isSaving, setIsSaving] = useState(false);
const [saveErrors, setSaveErrors] = useState<SaveError[]>([]);
const [isGeneratingLink, setIsGeneratingLink] = useState(false);
@@ -133,14 +129,14 @@ function EditMemberDrawer({
}, [fetchedUserId, fetchedUserDisplayName, member?.name]);
useEffect(() => {
- setLocalRoles(fetchedRoleIds);
+ setLocalRole(fetchedRoleIds[0] ?? '');
}, [fetchedRoleIds]);
const isDirty =
member !== null &&
fetchedUser != null &&
(localDisplayName !== fetchedDisplayName ||
- !areSortedArraysEqual(localRoles, fetchedRoleIds));
+ localRole !== (fetchedRoleIds[0] ?? ''));
const { mutateAsync: updateMyUser } = useUpdateMyUserV2();
const { mutateAsync: updateUser } = useUpdateUser();
@@ -224,7 +220,7 @@ function EditMemberDrawer({
setIsSaving(true);
try {
const nameChanged = localDisplayName !== fetchedDisplayName;
- const rolesChanged = !areSortedArraysEqual(localRoles, fetchedRoleIds);
+ const rolesChanged = localRole !== (fetchedRoleIds[0] ?? '');
const namePromise = nameChanged
? isSelf
@@ -237,7 +233,9 @@ function EditMemberDrawer({
const [nameResult, rolesResult] = await Promise.allSettled([
namePromise,
- rolesChanged ? applyDiff(localRoles, availableRoles) : Promise.resolve([]),
+ rolesChanged
+ ? applyDiff([localRole].filter(Boolean), availableRoles)
+ : Promise.resolve([]),
]);
const errors: SaveError[] = [];
@@ -255,7 +253,10 @@ function EditMemberDrawer({
context: 'Roles update',
apiError: toSaveApiError(rolesResult.reason),
onRetry: async (): Promise<void> => {
- const failures = await applyDiff(localRoles, availableRoles);
+ const failures = await applyDiff(
+ [localRole].filter(Boolean),
+ availableRoles,
+ );
setSaveErrors((prev) => {
const rest = prev.filter((e) => e.context !== 'Roles update');
return [
@@ -303,7 +304,7 @@ function EditMemberDrawer({
isDirty,
isSelf,
localDisplayName,
- localRoles,
+ localRole,
fetchedDisplayName,
fetchedRoleIds,
updateMyUser,
@@ -445,15 +446,10 @@ function EditMemberDrawer({
>
<div className="edit-member-drawer__input-wrapper edit-member-drawer__input-wrapper--disabled">
<div className="edit-member-drawer__disabled-roles">
- {localRoles.length > 0 ? (
- localRoles.map((roleId) => {
- const role = availableRoles.find((r) => r.id === roleId);
- return (
- <Badge key={roleId} color="vanilla">
- {role?.name ?? roleId}
- </Badge>
- );
- })
+ {localRole ? (
+ <Badge color="vanilla">
+ {availableRoles.find((r) => r.id === localRole)?.name ?? localRole}
+ </Badge>
) : (
<span className="edit-member-drawer__email-text">—</span>
)}
@@ -464,15 +460,14 @@ function EditMemberDrawer({
) : (
<RolesSelect
id="member-role"
- mode="multiple"
roles={availableRoles}
loading={rolesLoading}
isError={rolesError}
error={rolesErrorObj}
onRefetch={refetchRoles}
- value={localRoles}
- onChange={(roles): void => {
- setLocalRoles(roles);
+ value={localRole}
+ onChange={(role): void => {
+ setLocalRole(role);
setSaveErrors((prev) =>
prev.filter(
(err) =>
@@ -480,8 +475,7 @@ function EditMemberDrawer({
),
);
}}
- className="edit-member-drawer__role-select"
- placeholder="Select roles"
+ placeholder="Select role"
/>
)}
</div>
diff --git a/frontend/src/components/EditMemberDrawer/__tests__/EditMemberDrawer.test.tsx b/frontend/src/components/EditMemberDrawer/__tests__/EditMemberDrawer.test.tsx
index 3aba875788..1c51495aaf 100644
--- a/frontend/src/components/EditMemberDrawer/__tests__/EditMemberDrawer.test.tsx
+++ b/frontend/src/components/EditMemberDrawer/__tests__/EditMemberDrawer.test.tsx
@@ -5,7 +5,6 @@ import {
getResetPasswordToken,
useDeleteUser,
useGetUser,
- useRemoveUserRoleByUserIDAndRoleID,
useSetRoleByUserID,
useUpdateMyUserV2,
useUpdateUser,
@@ -56,7 +55,6 @@ jest.mock('api/generated/services/users', () => ({
useUpdateUser: jest.fn(),
useUpdateMyUserV2: jest.fn(),
useSetRoleByUserID: jest.fn(),
- useRemoveUserRoleByUserIDAndRoleID: jest.fn(),
getResetPasswordToken: jest.fn(),
}));
@@ -171,10 +169,6 @@ describe('EditMemberDrawer', () => {
mutateAsync: jest.fn().mockResolvedValue({}),
isLoading: false,
});
- (useRemoveUserRoleByUserIDAndRoleID as jest.Mock).mockReturnValue({
- mutateAsync: jest.fn().mockResolvedValue({}),
- isLoading: false,
- });
(useDeleteUser as jest.Mock).mockReturnValue({
mutate: mockDeleteMutate,
isLoading: false,
@@ -248,7 +242,7 @@ describe('EditMemberDrawer', () => {
expect(onClose).not.toHaveBeenCalled();
});
- it('calls setRole when a new role is added', async () => {
+ it('selecting a different role calls setRole with the new role name', async () => {
const onComplete = jest.fn();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const mockSet = jest.fn().mockResolvedValue({});
@@ -277,32 +271,30 @@ describe('EditMemberDrawer', () => {
});
});
- it('calls removeRole when an existing role is removed', async () => {
+ it('does not call removeRole when the role is changed', async () => {
const onComplete = jest.fn();
const user = userEvent.setup({ pointerEventsCheck: 0 });
- const mockRemove = jest.fn().mockResolvedValue({});
+ const mockSet = jest.fn().mockResolvedValue({});
- (useRemoveUserRoleByUserIDAndRoleID as jest.Mock).mockReturnValue({
- mutateAsync: mockRemove,
+ (useSetRoleByUserID as jest.Mock).mockReturnValue({
+ mutateAsync: mockSet,
isLoading: false,
});
renderDrawer({ onComplete });
- // Wait for the signoz-admin tag to appear, then click its remove button
- const adminTag = await screen.findByTitle('signoz-admin');
- const removeBtn = adminTag.querySelector(
- '.ant-select-selection-item-remove',
- ) as Element;
- await user.click(removeBtn);
+ // Switch from signoz-admin to signoz-viewer using single-select
+ await user.click(screen.getByLabelText('Roles'));
+ await user.click(await screen.findByTitle('signoz-viewer'));
const saveBtn = screen.getByRole('button', { name: /save member details/i });
await waitFor(() => expect(saveBtn).not.toBeDisabled());
await user.click(saveBtn);
await waitFor(() => {
- expect(mockRemove).toHaveBeenCalledWith({
- pathParams: { id: 'user-1', roleId: managedRoles[0].id },
+ expect(mockSet).toHaveBeenCalledWith({
+ pathParams: { id: 'user-1' },
+ data: { name: 'signoz-viewer' },
});
expect(onComplete).toHaveBeenCalled();
});
diff --git a/frontend/src/components/RolesSelect/RolesSelect.styles.scss b/frontend/src/components/RolesSelect/RolesSelect.styles.scss
index df4e61ed27..7f3987c636 100644
--- a/frontend/src/components/RolesSelect/RolesSelect.styles.scss
+++ b/frontend/src/components/RolesSelect/RolesSelect.styles.scss
@@ -88,3 +88,13 @@
color: var(--destructive);
}
}
+
+.roles-single-select {
+ .ant-select-selector {
+ min-height: 32px;
+ background-color: var(--l2-background) !important;
+ border: 1px solid var(--border) !important;
+ border-radius: 2px;
+ padding: 2px var(--padding-2) !important;
+ }
+}
diff --git a/frontend/src/components/RolesSelect/RolesSelect.tsx b/frontend/src/components/RolesSelect/RolesSelect.tsx
index 12d2ea3bc3..f217aa9bba 100644
--- a/frontend/src/components/RolesSelect/RolesSelect.tsx
+++ b/frontend/src/components/RolesSelect/RolesSelect.tsx
@@ -158,10 +158,10 @@ function RolesSelect(props: RolesSelectProps): JSX.Element {
return (
<Select
id={id}
- value={value}
+ value={value || undefined}
onChange={onChange}
placeholder={placeholder}
- className={cx('roles-select', className)}
+ className={cx('roles-single-select', className)}
loading={loading}
notFoundContent={notFoundContent}
options={options}
diff --git a/frontend/src/components/ServiceAccountDrawer/OverviewTab.tsx b/frontend/src/components/ServiceAccountDrawer/OverviewTab.tsx
index 1fc7df75c0..9a37e5a531 100644
--- a/frontend/src/components/ServiceAccountDrawer/OverviewTab.tsx
+++ b/frontend/src/components/ServiceAccountDrawer/OverviewTab.tsx
@@ -16,8 +16,8 @@ interface OverviewTabProps {
account: ServiceAccountRow;
localName: string;
onNameChange: (v: string) => void;
- localRoles: string[];
- onRolesChange: (v: string[]) => void;
+ localRole: string;
+ onRoleChange: (v: string) => void;
isDisabled: boolean;
availableRoles: AuthtypesRoleDTO[];
rolesLoading?: boolean;
@@ -31,8 +31,8 @@ function OverviewTab({
account,
localName,
onNameChange,
- localRoles,
- onRolesChange,
+ localRole,
+ onRoleChange,
isDisabled,
availableRoles,
rolesLoading,
@@ -96,15 +96,10 @@ function OverviewTab({
{isDisabled ? (
<div className="sa-drawer__input-wrapper sa-drawer__input-wrapper--disabled">
<div className="sa-drawer__disabled-roles">
- {localRoles.length > 0 ? (
- localRoles.map((roleId) => {
- const role = availableRoles.find((r) => r.id === roleId);
- return (
- <Badge key={roleId} color="vanilla">
- {role?.name ?? roleId}
- </Badge>
- );
- })
+ {localRole ? (
+ <Badge color="vanilla">
+ {availableRoles.find((r) => r.id === localRole)?.name ?? localRole}
+ </Badge>
) : (
<span className="sa-drawer__input-text">—</span>
)}
@@ -114,15 +109,14 @@ function OverviewTab({
) : (
<RolesSelect
id="sa-roles"
- mode="multiple"
roles={availableRoles}
loading={rolesLoading}
isError={rolesError}
error={rolesErrorObj}
onRefetch={onRefetchRoles}
- value={localRoles}
- onChange={onRolesChange}
- placeholder="Select roles"
+ value={localRole}
+ onChange={onRoleChange}
+ placeholder="Select role"
/>
)}
</div>
diff --git a/frontend/src/components/ServiceAccountDrawer/ServiceAccountDrawer.tsx b/frontend/src/components/ServiceAccountDrawer/ServiceAccountDrawer.tsx
index 66287970a7..b6f00abff5 100644
--- a/frontend/src/components/ServiceAccountDrawer/ServiceAccountDrawer.tsx
+++ b/frontend/src/components/ServiceAccountDrawer/ServiceAccountDrawer.tsx
@@ -80,7 +80,7 @@ function ServiceAccountDrawer({
parseAsBoolean.withDefault(false),
);
const [localName, setLocalName] = useState('');
- const [localRoles, setLocalRoles] = useState<string[]>([]);
+ const [localRole, setLocalRole] = useState('');
const [isSaving, setIsSaving] = useState(false);
const [saveErrors, setSaveErrors] = useState<SaveError[]>([]);
@@ -116,7 +116,7 @@ function ServiceAccountDrawer({
}, [account?.id, account?.name, setKeysPage]);
useEffect(() => {
- setLocalRoles(currentRoles.map((r) => r.id).filter(Boolean) as string[]);
+ setLocalRole(currentRoles[0]?.id ?? '');
}, [currentRoles]);
const isDeleted =
@@ -125,8 +125,7 @@ function ServiceAccountDrawer({
const isDirty =
account !== null &&
(localName !== (account.name ?? '') ||
- JSON.stringify([...localRoles].sort()) !==
- JSON.stringify([...currentRoles.map((r) => r.id).filter(Boolean)].sort()));
+ localRole !== (currentRoles[0]?.id ?? ''));
const {
roles: availableRoles,
@@ -216,7 +215,10 @@ function ServiceAccountDrawer({
const retryRolesUpdate = useCallback(async (): Promise<void> => {
try {
- const failures = await applyDiff(localRoles, availableRoles);
+ const failures = await applyDiff(
+ [localRole].filter(Boolean),
+ availableRoles,
+ );
if (failures.length === 0) {
setSaveErrors((prev) => prev.filter((e) => e.context !== 'Roles update'));
} else {
@@ -240,7 +242,7 @@ function ServiceAccountDrawer({
),
);
}
- }, [localRoles, availableRoles, applyDiff, toSaveApiError, makeRoleRetry]);
+ }, [localRole, availableRoles, applyDiff, toSaveApiError, makeRoleRetry]);
const handleSave = useCallback(async (): Promise<void> => {
if (!account || !isDirty) {
@@ -259,7 +261,7 @@ function ServiceAccountDrawer({
const [nameResult, rolesResult] = await Promise.allSettled([
namePromise,
- applyDiff(localRoles, availableRoles),
+ applyDiff([localRole].filter(Boolean), availableRoles),
]);
const errors: SaveError[] = [];
@@ -308,7 +310,7 @@ function ServiceAccountDrawer({
account,
isDirty,
localName,
- localRoles,
+ localRole,
availableRoles,
updateMutateAsync,
applyDiff,
@@ -410,8 +412,8 @@ function ServiceAccountDrawer({
account={account}
localName={localName}
onNameChange={handleNameChange}
- localRoles={localRoles}
- onRolesChange={setLocalRoles}
+ localRole={localRole}
+ onRoleChange={setLocalRole}
isDisabled={isDeleted}
availableRoles={availableRoles}
rolesLoading={rolesLoading}
diff --git a/frontend/src/components/ServiceAccountDrawer/__tests__/ServiceAccountDrawer.test.tsx b/frontend/src/components/ServiceAccountDrawer/__tests__/ServiceAccountDrawer.test.tsx
index eef57ef2cd..0099226544 100644
--- a/frontend/src/components/ServiceAccountDrawer/__tests__/ServiceAccountDrawer.test.tsx
+++ b/frontend/src/components/ServiceAccountDrawer/__tests__/ServiceAccountDrawer.test.tsx
@@ -139,20 +139,20 @@ describe('ServiceAccountDrawer', () => {
});
});
- it('changing roles enables Save; clicking Save sends updated roles in payload', async () => {
- const updateSpy = jest.fn();
+ it('changing roles enables Save; clicking Save sends role add request without delete', async () => {
const roleSpy = jest.fn();
+ const deleteSpy = jest.fn();
const user = userEvent.setup({ pointerEventsCheck: 0 });
server.use(
- rest.put(SA_ENDPOINT, async (req, res, ctx) => {
- updateSpy(await req.json());
- return res(ctx.status(200), ctx.json({ status: 'success', data: {} }));
- }),
rest.post(SA_ROLES_ENDPOINT, async (req, res, ctx) => {
roleSpy(await req.json());
return res(ctx.status(200), ctx.json({ status: 'success', data: {} }));
}),
+ rest.delete(SA_ROLE_DELETE_ENDPOINT, (_, res, ctx) => {
+ deleteSpy();
+ return res(ctx.status(200), ctx.json({ status: 'success', data: {} }));
+ }),
);
renderDrawer();
@@ -167,12 +167,12 @@ describe('ServiceAccountDrawer', () => {
await user.click(saveBtn);
await waitFor(() => {
- expect(updateSpy).not.toHaveBeenCalled();
expect(roleSpy).toHaveBeenCalledWith(
expect.objectContaining({
id: '019c24aa-2248-7585-a129-4188b3473c27',
}),
);
+ expect(deleteSpy).not.toHaveBeenCalled();
});
});
@@ -350,7 +350,7 @@ describe('ServiceAccountDrawer – save-error UX', () => {
).toBeInTheDocument();
});
- it('role update failure shows SaveErrorItem with the role name context', async () => {
+ it('role add failure shows SaveErrorItem with the role name context', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
server.use(
diff --git a/frontend/src/hooks/member/useMemberRoleManager.ts b/frontend/src/hooks/member/useMemberRoleManager.ts
index 0ca06263fe..ea82772213 100644
--- a/frontend/src/hooks/member/useMemberRoleManager.ts
+++ b/frontend/src/hooks/member/useMemberRoleManager.ts
@@ -1,10 +1,6 @@
import { useCallback, useMemo } from 'react';
import type { AuthtypesRoleDTO } from 'api/generated/services/sigNoz.schemas';
-import {
- useGetUser,
- useRemoveUserRoleByUserIDAndRoleID,
- useSetRoleByUserID,
-} from 'api/generated/services/users';
+import { useGetUser, useSetRoleByUserID } from 'api/generated/services/users';
export interface MemberRoleUpdateFailure {
roleName: string;
@@ -43,7 +39,6 @@ export function useMemberRoleManager(
);
const { mutateAsync: setRole } = useSetRoleByUserID();
- const { mutateAsync: removeRole } = useRemoveUserRoleByUserIDAndRoleID();
const applyDiff = useCallback(
async (
@@ -53,25 +48,12 @@ export function useMemberRoleManager(
const currentRoleIdSet = new Set(fetchedRoleIds);
const desiredRoleIdSet = new Set(localRoleIds.filter(Boolean));
- const toRemove = currentUserRoles.filter((ur) => {
- const id = ur.role?.id ?? ur.roleId;
- return id && !desiredRoleIdSet.has(id);
- });
const toAdd = availableRoles.filter(
(r) => r.id && desiredRoleIdSet.has(r.id) && !currentRoleIdSet.has(r.id),
);
+ /// TODO: re-enable deletes once BE for this is streamlined
const allOps = [
- ...toRemove.map((ur) => ({
- roleName: ur.role?.name ?? 'unknown',
- run: (): ReturnType<typeof removeRole> =>
- removeRole({
- pathParams: {
- id: userId,
- roleId: ur.role?.id ?? ur.roleId ?? '',
- },
- }),
- })),
...toAdd.map((role) => ({
roleName: role.name ?? 'unknown',
run: (): ReturnType<typeof setRole> =>
@@ -94,7 +76,7 @@ export function useMemberRoleManager(
return failures;
},
- [userId, fetchedRoleIds, currentUserRoles, setRole, removeRole],
+ [userId, fetchedRoleIds, setRole],
);
return { fetchedRoleIds, isLoading, applyDiff };
diff --git a/frontend/src/hooks/serviceAccount/useServiceAccountRoleManager.ts b/frontend/src/hooks/serviceAccount/useServiceAccountRoleManager.ts
index 73f8e9462c..2e5ba0e946 100644
--- a/frontend/src/hooks/serviceAccount/useServiceAccountRoleManager.ts
+++ b/frontend/src/hooks/serviceAccount/useServiceAccountRoleManager.ts
@@ -3,7 +3,6 @@ import { useQueryClient } from 'react-query';
import {
getGetServiceAccountRolesQueryKey,
useCreateServiceAccountRole,
- useDeleteServiceAccountRole,
useGetServiceAccountRoles,
} from 'api/generated/services/serviceaccount';
import type { AuthtypesRoleDTO } from 'api/generated/services/sigNoz.schemas';
@@ -36,7 +35,6 @@ export function useServiceAccountRoleManager(
// the retry for these mutations is safe due to being idempotent on backend
const { mutateAsync: createRole } = useCreateServiceAccountRole();
- const { mutateAsync: deleteRole } = useDeleteServiceAccountRole();
const invalidateRoles = useCallback(
() =>
@@ -62,21 +60,13 @@ export function useServiceAccountRoleManager(
(r) => r.id && desiredRoleIds.has(r.id) && !currentRoleIds.has(r.id),
);
- const removedRoles = currentRoles.filter(
- (r) => r.id && !desiredRoleIds.has(r.id),
- );
-
+ // TODO: re-enable deletes once BE for this is streamlined
const allOperations = [
...addedRoles.map((role) => ({
role,
run: (): ReturnType<typeof createRole> =>
createRole({ pathParams: { id: accountId }, data: { id: role.id } }),
})),
- ...removedRoles.map((role) => ({
- role,
- run: (): ReturnType<typeof deleteRole> =>
- deleteRole({ pathParams: { id: accountId, rid: role.id } }),
- })),
];
const results = await Promise.allSettled(
@@ -102,7 +92,7 @@ export function useServiceAccountRoleManager(
return failures;
},
- [accountId, currentRoles, createRole, deleteRole, invalidateRoles],
+ [accountId, currentRoles, createRole, invalidateRoles],
);
return {
diff --git a/pkg/modules/serviceaccount/implserviceaccount/module.go b/pkg/modules/serviceaccount/implserviceaccount/module.go
index 8f1d1c2978..f36897f347 100644
--- a/pkg/modules/serviceaccount/implserviceaccount/module.go
+++ b/pkg/modules/serviceaccount/implserviceaccount/module.go
@@ -376,7 +376,7 @@ func (module *module) getOrGetSetIdentity(ctx context.Context, serviceAccountID
}
func (module *module) setRole(ctx context.Context, orgID valuer.UUID, id valuer.UUID, role *authtypes.Role) error {
- serviceAccount, err := module.Get(ctx, orgID, id)
+ serviceAccount, err := module.GetWithRoles(ctx, orgID, id)
if err != nil {
return err
}
@@ -386,12 +386,24 @@ func (module *module) setRole(ctx context.Context, orgID valuer.UUID, id valuer.
return err
}
- err = module.authz.Grant(ctx, orgID, []string{role.Name}, authtypes.MustNewSubject(authtypes.TypeableServiceAccount, id.String(), orgID, nil))
+ err = module.authz.ModifyGrant(ctx, orgID, serviceAccount.RoleNames(), []string{role.Name}, authtypes.MustNewSubject(authtypes.TypeableServiceAccount, id.String(), orgID, nil))
if err != nil {
return err
}
- err = module.store.CreateServiceAccountRole(ctx, serviceAccountRole)
+ err = module.store.RunInTx(ctx, func(ctx context.Context) error {
+ err = module.store.DeleteServiceAccountRoles(ctx, serviceAccount.ID)
+ if err != nil {
+ return err
+ }
+
+ err = module.store.CreateServiceAccountRole(ctx, serviceAccountRole)
+ if err != nil {
+ return err
+ }
+
+ return nil
+ })
if err != nil {
return err
}
diff --git a/pkg/modules/serviceaccount/implserviceaccount/store.go b/pkg/modules/serviceaccount/implserviceaccount/store.go
index 36106d4736..8c718614be 100644
--- a/pkg/modules/serviceaccount/implserviceaccount/store.go
+++ b/pkg/modules/serviceaccount/implserviceaccount/store.go
@@ -170,6 +170,21 @@ func (store *store) CreateServiceAccountRole(ctx context.Context, serviceAccount
return nil
}
+func (store *store) DeleteServiceAccountRoles(ctx context.Context, serviceAccountID valuer.UUID) error {
+ _, err := store.
+ sqlstore.
+ BunDBCtx(ctx).
+ NewDelete().
+ Model(new(serviceaccounttypes.ServiceAccountRole)).
+ Where("service_account_id = ?", serviceAccountID).
+ Exec(ctx)
+ if err != nil {
+ return err
+ }
+
+ return nil
+}
+
func (store *store) DeleteServiceAccountRole(ctx context.Context, serviceAccountID valuer.UUID, roleID valuer.UUID) error {
_, err := store.
sqlstore.
diff --git a/pkg/modules/serviceaccount/serviceaccount.go b/pkg/modules/serviceaccount/serviceaccount.go
index a8d3214b41..9bcef5b37f 100644
--- a/pkg/modules/serviceaccount/serviceaccount.go
+++ b/pkg/modules/serviceaccount/serviceaccount.go
@@ -5,6 +5,7 @@ import (
"net/http"
"time"
+ "github.com/SigNoz/signoz/pkg/statsreporter"
"github.com/SigNoz/signoz/pkg/types/authtypes"
"github.com/SigNoz/signoz/pkg/types/serviceaccounttypes"
"github.com/SigNoz/signoz/pkg/valuer"
@@ -66,6 +67,8 @@ type Module interface {
GetIdentity(context.Context, string) (*authtypes.Identity, error)
Config() Config
+
+ statsreporter.StatsCollector
}
type Handler interface {
diff --git a/pkg/modules/user/impluser/setter.go b/pkg/modules/user/impluser/setter.go
index 648533962f..cc7b5c0bbe 100644
--- a/pkg/modules/user/impluser/setter.go
+++ b/pkg/modules/user/impluser/setter.go
@@ -383,6 +383,11 @@ func (module *setter) DeleteUser(ctx context.Context, orgID valuer.UUID, id stri
return errors.New(errors.TypeForbidden, errors.CodeForbidden, "cannot self delete")
}
+ err = user.UpdateStatus(types.UserStatusDeleted)
+ if err != nil {
+ return err
+ }
+
userRoles, err := module.getter.GetRolesByUserID(ctx, user.ID)
if err != nil {
return err
@@ -406,6 +411,8 @@ func (module *setter) DeleteUser(ctx context.Context, orgID valuer.UUID, id stri
return err
}
+ traitsOrProperties := types.NewTraitsFromUser(user)
+ module.analytics.IdentifyUser(ctx, user.OrgID.String(), user.ID.String(), traitsOrProperties)
module.analytics.TrackUser(ctx, user.OrgID.String(), user.ID.String(), "User Deleted", map[string]any{
"deleted_by": deletedBy,
})
@@ -568,8 +575,13 @@ func (module *setter) UpdatePasswordByResetPasswordToken(ctx context.Context, to
roleNames := roleNamesFromUserRoles(userRoles)
+ isPendingInviteUser := user.Status == types.UserStatusPendingInvite
// since grant is idempotent, multiple calls won't cause issues in case of retries
- if user.Status == types.UserStatusPendingInvite {
+ if isPendingInviteUser {
+ if err := user.UpdateStatus(types.UserStatusActive); err != nil {
+ return err
+ }
+
if err = module.authz.Grant(
ctx,
user.OrgID,
@@ -580,15 +592,14 @@ func (module *setter) UpdatePasswordByResetPasswordToken(ctx context.Context, to
}
traitsOrProperties := types.NewTraitsFromUser(user)
+ module.analytics.IdentifyUser(ctx, user.OrgID.String(), user.ID.String(), traitsOrProperties)
module.analytics.TrackUser(ctx, user.OrgID.String(), user.ID.String(), "User Activated", traitsOrProperties)
}
return module.store.RunInTx(ctx, func(ctx context.Context) error {
- if user.Status == types.UserStatusPendingInvite {
- if err := user.UpdateStatus(types.UserStatusActive); err != nil {
- return err
- }
- if err := module.store.UpdateUser(ctx, user.OrgID, user); err != nil {
+ if isPendingInviteUser {
+ err := module.store.UpdateUser(ctx, user.OrgID, user)
+ if err != nil {
return err
}
}
@@ -817,6 +828,7 @@ func (module *setter) activatePendingUser(ctx context.Context, user *types.User,
}
traitsOrProperties := types.NewTraitsFromUser(user)
+ module.analytics.IdentifyUser(ctx, user.OrgID.String(), user.ID.String(), traitsOrProperties)
module.analytics.TrackUser(ctx, user.OrgID.String(), user.ID.String(), "User Activated", traitsOrProperties)
return nil
@@ -866,16 +878,17 @@ func (module *setter) AddUserRole(ctx context.Context, orgID, userID valuer.UUID
if err != nil {
return err
}
- for _, userRole := range existingUserRoles {
- if userRole.Role != nil && userRole.Role.Name == roleName {
- return nil // role already assigned no-op
- }
+
+ existingRoles := make([]string, len(existingUserRoles))
+ for idx, role := range existingUserRoles {
+ existingRoles[idx] = role.Role.Name
}
// grant via authz (idempotent)
- if err := module.authz.Grant(
+ if err := module.authz.ModifyGrant(
ctx,
orgID,
+ existingRoles,
[]string{roleName},
authtypes.MustNewSubject(authtypes.TypeableUser, existingUser.ID.StringValue(), existingUser.OrgID, nil),
); err != nil {
@@ -884,7 +897,20 @@ func (module *setter) AddUserRole(ctx context.Context, orgID, userID valuer.UUID
// create user_role entry
userRoles := authtypes.NewUserRoles(userID, foundRoles)
- if err := module.userRoleStore.CreateUserRoles(ctx, userRoles); err != nil {
+ err = module.store.RunInTx(ctx, func(ctx context.Context) error {
+ err = module.userRoleStore.DeleteUserRoles(ctx, existingUser.ID)
+ if err != nil {
+ return err
+ }
+
+ err := module.userRoleStore.CreateUserRoles(ctx, userRoles)
+ if err != nil {
+ return err
+ }
+
+ return nil
+ })
+ if err != nil {
return err
}
diff --git a/pkg/signoz/signoz.go b/pkg/signoz/signoz.go
index ec61920c39..0b0e33ddb5 100644
--- a/pkg/signoz/signoz.go
+++ b/pkg/signoz/signoz.go
@@ -437,6 +437,7 @@ func New(
tokenizer,
config,
modules.AuthDomain,
+ modules.ServiceAccount,
}
// Initialize stats reporter from the available stats reporter provider factories
diff --git a/pkg/types/serviceaccounttypes/service_acccount.go b/pkg/types/serviceaccounttypes/service_acccount.go
index 84e98aa85b..7111a5f43c 100644
--- a/pkg/types/serviceaccounttypes/service_acccount.go
+++ b/pkg/types/serviceaccounttypes/service_acccount.go
@@ -243,6 +243,7 @@ type Store interface {
// Service Account Role
CreateServiceAccountRole(context.Context, *ServiceAccountRole) error
+ DeleteServiceAccountRoles(context.Context, valuer.UUID) error
DeleteServiceAccountRole(context.Context, valuer.UUID, valuer.UUID) error
// Service Account Factor API Key
diff --git a/tests/integration/src/passwordauthn/04_role.py b/tests/integration/src/passwordauthn/04_role.py
index 28e18f0609..2bf2a9623c 100644
--- a/tests/integration/src/passwordauthn/04_role.py
+++ b/tests/integration/src/passwordauthn/04_role.py
@@ -133,11 +133,11 @@ def test_get_user_roles(
assert "type" in role
-def test_assign_additional_role(
+def test_assign_role_replaces_previous(
signoz: types.SigNoz,
get_token: Callable[[str, str], str],
):
- """Verify POST /api/v2/users/{id}/roles assigns an additional role."""
+ """Verify POST /api/v2/users/{id}/roles replaces existing role."""
admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
response = requests.get(
signoz.self.host_configs["8080"].get("/api/v2/users/me"),
@@ -166,8 +166,8 @@ def test_assign_additional_role(
assert response.status_code == HTTPStatus.OK
roles = response.json()["data"]
names = {r["name"] for r in roles}
- assert "signoz-admin" in names
assert "signoz-editor" in names
+ assert "signoz-admin" not in names
def test_get_users_by_role(
@@ -253,9 +253,7 @@ def test_remove_role(
)
assert response.status_code == HTTPStatus.OK
roles_after = response.json()["data"]
- names = {r["name"] for r in roles_after}
- assert "signoz-editor" not in names
- assert "signoz-admin" in names
+ assert len(roles_after) == 0
def test_user_with_roles_reflects_change(
@@ -282,8 +280,7 @@ def test_user_with_roles_reflects_change(
assert response.status_code == HTTPStatus.OK
data = response.json()["data"]
role_names = {ur["role"]["name"] for ur in data["userRoles"]}
- assert "signoz-admin" in role_names
- assert "signoz-editor" not in role_names
+ assert len(role_names) == 0
def test_admin_cannot_assign_role_to_self(
diff --git a/tests/integration/src/serviceaccount/04_roles.py b/tests/integration/src/serviceaccount/04_roles.py
index 4e53f5da18..223e07564d 100644
--- a/tests/integration/src/serviceaccount/04_roles.py
+++ b/tests/integration/src/serviceaccount/04_roles.py
@@ -48,7 +48,7 @@ def test_assign_role_to_service_account(
create_user_admin: types.Operation, # pylint: disable=unused-argument
get_token: Callable[[str, str], str],
):
- """POST /{id}/roles assigns a new role, verify via GET."""
+ """POST /{id}/roles replaces existing role, verify via GET."""
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
# create service account with viewer role
@@ -56,7 +56,7 @@ def test_assign_role_to_service_account(
signoz, token, "sa-assign-role", role="signoz-viewer"
)
- # assign editor role additionally
+ # assign editor role (replaces viewer)
editor_role_id = find_role_by_name(signoz, token, "signoz-editor")
assign_resp = requests.post(
signoz.self.host_configs["8080"].get(
@@ -68,7 +68,7 @@ def test_assign_role_to_service_account(
)
assert assign_resp.status_code == HTTPStatus.NO_CONTENT, assign_resp.text
- # verify both roles are present
+ # verify only editor role is present (viewer was replaced)
roles_resp = requests.get(
signoz.self.host_configs["8080"].get(
f"{SERVICE_ACCOUNT_BASE}/{service_account_id}/roles"
@@ -78,8 +78,9 @@ def test_assign_role_to_service_account(
)
assert roles_resp.status_code == HTTPStatus.OK, roles_resp.text
role_names = [r["name"] for r in roles_resp.json()["data"]]
- assert "signoz-viewer" in role_names
+ assert len(role_names) == 1
assert "signoz-editor" in role_names
+ assert "signoz-viewer" not in role_names
def test_assign_role_idempotent(
@@ -87,7 +88,7 @@ def test_assign_role_idempotent(
create_user_admin: types.Operation, # pylint: disable=unused-argument
get_token: Callable[[str, str], str],
):
- """POST same role twice succeeds (store uses ON CONFLICT DO NOTHING)."""
+ """POST same role twice succeeds (replace with same role is idempotent)."""
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
service_account_id = create_service_account(
signoz, token, "sa-role-idempotent", role="signoz-viewer"
@@ -118,6 +119,66 @@ def test_assign_role_idempotent(
assert role_names.count("signoz-viewer") == 1
+def test_assign_role_replaces_access(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ """After role replacement, SA loses old permissions and gains new ones."""
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+
+ # create SA with viewer role and an API key
+ service_account_id, api_key = create_service_account_with_key(
+ signoz, token, "sa-role-replace-access", role="signoz-viewer"
+ )
+
+ # viewer should get 403 on admin-only endpoint
+ resp = requests.get(
+ signoz.self.host_configs["8080"].get(SERVICE_ACCOUNT_BASE),
+ headers={"SIGNOZ-API-KEY": api_key},
+ timeout=5,
+ )
+ assert (
+ resp.status_code == HTTPStatus.FORBIDDEN
+ ), f"Expected 403 for viewer on admin endpoint, got {resp.status_code}: {resp.text}"
+
+ # assign admin role (replaces viewer)
+ admin_role_id = find_role_by_name(signoz, token, "signoz-admin")
+ assign_resp = requests.post(
+ signoz.self.host_configs["8080"].get(
+ f"{SERVICE_ACCOUNT_BASE}/{service_account_id}/roles"
+ ),
+ json={"id": admin_role_id},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert assign_resp.status_code == HTTPStatus.NO_CONTENT, assign_resp.text
+
+ # SA should now have admin access
+ resp = requests.get(
+ signoz.self.host_configs["8080"].get(SERVICE_ACCOUNT_BASE),
+ headers={"SIGNOZ-API-KEY": api_key},
+ timeout=5,
+ )
+ assert (
+ resp.status_code == HTTPStatus.OK
+ ), f"Expected 200 for admin on admin endpoint, got {resp.status_code}: {resp.text}"
+
+ # verify only admin role is present
+ roles_resp = requests.get(
+ signoz.self.host_configs["8080"].get(
+ f"{SERVICE_ACCOUNT_BASE}/{service_account_id}/roles"
+ ),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert roles_resp.status_code == HTTPStatus.OK, roles_resp.text
+ role_names = [r["name"] for r in roles_resp.json()["data"]]
+ assert len(role_names) == 1
+ assert "signoz-admin" in role_names
+ assert "signoz-viewer" not in role_names
+
+
def test_remove_role_from_service_account(
signoz: types.SigNoz,
create_user_admin: types.Operation, # pylint: disable=unused-argument