Compare commits

...

4 Commits

Author SHA1 Message Date
Naman Verma
2a96645af6 fix(rules): keep rule labels from overriding engine labels (#13612)
Some checks are pending
build-staging / prepare (push) Waiting to run
build-staging / js-build (push) Blocked by required conditions
build-staging / go-build (push) Blocked by required conditions
build-staging / staging (push) Blocked by required conditions
cacheci / tests (push) Waiting to run
Release Drafter / update_release_draft (push) Waiting to run
<!--A few plain bullets saying what changed and why, for a reviewer
skimming it - not a wall of text, not a restatement of the diff, not
generated boilerplate.-->
#### Description

A rule label named threshold.name or severity replaced the value the
evaluator stamped. Rule Labels aren't supposed to be treated in a
special way like this.

<!--Reference issues using `Closes #issue-number` to enable automatic
closure on merge. -->
#### Issues closed by this PR

Part of https://github.com/SigNoz/pulse-pod/issues/653
2026-11-17 10:33:44 +00:00
hardik-signoz
900796a573 test(e2e): cover users FGA on the members page (#13615)
#### Description

- Adds `members.spec.ts` TC-04 to TC-07, each running as a member
holding only a custom role:
  - TC-04: `list:user` without `create:user`, invite button denied
- TC-05: no `list:user`, list shows "not authorized" and search is
denied
- TC-06: invited member without `factor-password:list`, "Invite Link
Unavailable"
- TC-07: self edit, adds then removes a role (needs `attach` and
`detach` on user and role)
- Drivers: `guestSettings` fixture (settings pages on the signed-in
guest page), `createGrantedUser` seed, members locators, `addRole` and
`removeRole`.
- Unit, story and integration tests already cover the rest of Users FGA,
see the plan on the issue.

#### Issues closed by this PR

Closes SigNoz/keystone-pod#212

#### Additional Information

- Each spec was checked by granting the missing permission and
confirming it fails.
- Run locally against hosted staging backend with the local frontend
(`--no-deps`). Not run on the pytest bootstrap stack.
2026-11-17 06:54:50 +00:00
Swapnil Nakade
2175611902 feat(authz): enable FGA for org preference routes (#13590)
<!--A few plain bullets saying what changed and why, for a reviewer
skimming it - not a wall of text, not a restatement of the diff, not
generated boilerplate.-->
#### Description
- Adds resource defs to the three `/api/v1/org/preferences` routes so
org preference updates emit audit events.
- Moves them from `AdminAccess` to `CheckResources`, scoped to
`org-preference:list`, `org-preference:read` and
`org-preference:update`. Admin keeps sole access.
- Migration 150 backfills the admin `org-preference` tuples for orgs
created before the grant existed. The registry and stored roles already
carry the grant, so it writes tuples only.
- The preference name is recorded as the resource ID with a wildcard
selector, since names are not UUIDs.

<!--Reference issues using `Closes #issue-number` to enable automatic
closure on merge. -->
#### Issues closed by this PR
contributes to https://github.com/SigNoz/keystone-pod/issues/10
contributes to https://github.com/SigNoz/keystone-pod/issues/43
2026-11-17 05:35:50 +00:00
hardik-signoz
29d4f7fb8d chore(sentry): exclude anonymous sentry errors (#13599)
#### Description

- Drop Sentry events whose throwing frame is `<anonymous>` (code loaded
without a script URL, such as extension or automation scripts).
- The existing `hasNoAppFrames` filter missed them: Sentry's bundled
`setTimeout` wrapper counts as an app frame.
- Matching the top frame instead of the error message keeps real bugs
reportable.

#### Issues closed by this PR

Closes SigNoz/keystone-pod#218
2026-11-17 05:34:07 +00:00
20 changed files with 609 additions and 66 deletions

View File

@@ -11992,8 +11992,9 @@ components:
additionalProperties:
type: string
description: Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*;
values may use Go templates such as {{$labels.service_name}}. severity
is the conventional routing label.
values may use Go templates such as {{$labels.service_name}}. A label
named after one the engine writes, such as severity or threshold.name,
is ignored.
type: object
notificationSettings:
allOf:
@@ -12110,8 +12111,9 @@ components:
additionalProperties:
type: string
description: Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*;
values may use Go templates such as {{$labels.service_name}}. severity
is the conventional routing label.
values may use Go templates such as {{$labels.service_name}}. A label
named after one the engine writes, such as severity or threshold.name,
is ignored.
type: object
notificationSettings:
allOf:
@@ -16567,9 +16569,9 @@ paths:
description: Internal Server Error
security:
- api_key:
- ADMIN
- org-preference:list
- tokenizer:
- ADMIN
- org-preference:list
summary: List org preferences
tags:
- preferences
@@ -16632,9 +16634,9 @@ paths:
description: Internal Server Error
security:
- api_key:
- ADMIN
- org-preference:read
- tokenizer:
- ADMIN
- org-preference:read
summary: Get org preference
tags:
- preferences
@@ -16689,9 +16691,9 @@ paths:
description: Internal Server Error
security:
- api_key:
- ADMIN
- org-preference:update
- tokenizer:
- ADMIN
- org-preference:update
summary: Update org preference
tags:
- preferences

View File

@@ -267,9 +267,7 @@ func (r *AnomalyRule) Eval(ctx context.Context, ts time.Time) (int, error) {
lb := ruletypes.NewBuilder(smpl.Metric...).Del(ruletypes.MetricNameLabel).Del(ruletypes.TemporalityLabel)
resultLabels := ruletypes.NewBuilder(smpl.Metric...).Del(ruletypes.MetricNameLabel).Del(ruletypes.TemporalityLabel).Labels()
for name, value := range r.Labels().Map() {
lb.Set(name, expand(value))
}
lb.SetRuleLabels(r.Labels().Map(), expand)
lb.Set(ruletypes.AlertNameLabel, r.Name())
lb.Set(ruletypes.AlertRuleIDLabel, r.ID())

View File

@@ -2,9 +2,9 @@ import type { ErrorEvent, StackFrame } from '@sentry/react';
import { AxiosError, AxiosHeaders } from 'axios';
import {
hasNoAppFrames,
isInjectedScriptError,
isExpectedRequestFailure,
isExternalIntegrationError,
isThirdPartyScriptError,
SENTRY_IGNORE_ERRORS,
} from '../sentryFilters';
@@ -27,7 +27,7 @@ function eventWithFrames(...filenames: string[]): ErrorEvent {
};
}
describe('isExternalIntegrationError', () => {
describe('isThirdPartyScriptError', () => {
it.each([
[
'PostHog recorder',
@@ -39,14 +39,12 @@ describe('isExternalIntegrationError', () => {
],
['Appcues', 'https://fast.appcues.com/123456.js'],
])('drops an error with a %s frame', (_, url) => {
expect(isExternalIntegrationError(eventWithFrames(APP_BUNDLE, url))).toBe(
true,
);
expect(isThirdPartyScriptError(eventWithFrames(APP_BUNDLE, url))).toBe(true);
});
it('drops it when the top frame is our bundle', () => {
expect(
isExternalIntegrationError(
isThirdPartyScriptError(
eventWithFrames(
'https://us-assets.i.posthog.com/static/posthog-recorder.js?v=1.298.0',
'<anonymous>',
@@ -58,13 +56,13 @@ describe('isExternalIntegrationError', () => {
it('keeps an error from our bundle only', () => {
expect(
isExternalIntegrationError(eventWithFrames(APP_BUNDLE, '<anonymous>')),
isThirdPartyScriptError(eventWithFrames(APP_BUNDLE, '<anonymous>')),
).toBe(false);
});
it('keeps an error from a host that only contains an integration name', () => {
expect(
isExternalIntegrationError(
isThirdPartyScriptError(
eventWithFrames(
'https://posthog.example.com/app.js',
'https://notusepylon.com/widget.js',
@@ -74,11 +72,11 @@ describe('isExternalIntegrationError', () => {
});
it('keeps an error without a stack trace', () => {
expect(isExternalIntegrationError({ type: undefined })).toBe(false);
expect(isThirdPartyScriptError({ type: undefined })).toBe(false);
});
});
describe('hasNoAppFrames', () => {
describe('isInjectedScriptError', () => {
const PAGE_URL = 'https://example.us.signoz.cloud/dashboard/01a081e1';
function eventWithStackFrames(frames: StackFrame[]): ErrorEvent {
@@ -92,7 +90,7 @@ describe('hasNoAppFrames', () => {
it('drops a script appended to the page', () => {
expect(
hasNoAppFrames(
isInjectedScriptError(
eventWithStackFrames([
{ filename: PAGE_URL, lineno: 1, colno: 30, function: 'global code' },
{ filename: '[native code]', function: 'eval' },
@@ -104,7 +102,7 @@ describe('hasNoAppFrames', () => {
it('drops a browser extension error', () => {
expect(
hasNoAppFrames(
isInjectedScriptError(
eventWithStackFrames([
{ filename: 'chrome-extension://abc/content.js', lineno: 4, colno: 12 },
]),
@@ -112,21 +110,46 @@ describe('hasNoAppFrames', () => {
).toBe(true);
});
it('drops an error thrown from injected code behind the Sentry wrapper', () => {
expect(
isInjectedScriptError(eventWithFrames(APP_BUNDLE, '<anonymous>')),
).toBe(true);
});
it('keeps an error thrown from our bundle after an anonymous frame', () => {
expect(
isInjectedScriptError(eventWithFrames('<anonymous>', APP_BUNDLE)),
).toBe(false);
});
it('keeps an error with a frame from our bundle', () => {
expect(hasNoAppFrames(eventWithFrames(PAGE_URL, APP_BUNDLE))).toBe(false);
expect(isInjectedScriptError(eventWithFrames(PAGE_URL, APP_BUNDLE))).toBe(
false,
);
});
it('keeps an error without a stack trace', () => {
expect(hasNoAppFrames({ type: undefined })).toBe(false);
expect(isInjectedScriptError({ type: undefined })).toBe(false);
});
it('keeps an error whose frames have no position', () => {
expect(
hasNoAppFrames(
isInjectedScriptError(
eventWithStackFrames([{ filename: '[native code]', function: 'eval' }]),
),
).toBe(false);
});
it('keeps an error a builtin threw for our bundle', () => {
expect(
isInjectedScriptError(
eventWithStackFrames([
{ filename: APP_BUNDLE, lineno: 1, colno: 1 },
{ filename: '<anonymous>', function: 'JSON.parse' },
]),
),
).toBe(false);
});
});
describe('SENTRY_IGNORE_ERRORS', () => {

View File

@@ -44,9 +44,9 @@ import defaultRoutes, {
} from './routes';
import type { EnabledRouteKeys } from './RouteGate';
import {
hasNoAppFrames,
isInjectedScriptError,
isExpectedRequestFailure,
isExternalIntegrationError,
isThirdPartyScriptError,
SENTRY_IGNORE_ERRORS,
} from './sentryFilters';
@@ -360,12 +360,12 @@ function App(): JSX.Element {
return null;
}
if (isExternalIntegrationError(event)) {
if (isThirdPartyScriptError(event)) {
return null;
}
// Dev serves source from /src/, so every frame would look foreign there.
if (IS_PROD && hasNoAppFrames(event)) {
if (IS_PROD && isInjectedScriptError(event)) {
return null;
}

View File

@@ -28,10 +28,15 @@ export function isExpectedRequestFailure(error: unknown): boolean {
}
const APP_ASSETS_PATH = '/assets/';
const ANONYMOUS_FILENAME = '<anonymous>';
// Frames without a position are `[native code]`, which says nothing about the
// script that threw.
export function hasNoAppFrames(event: ErrorEvent): boolean {
// Frames without a position are `[native code]` or a browser builtin such as
// `JSON.parse (<anonymous>)`, which say nothing about the script that threw.
// A positioned `<anonymous>` throwing (last) frame is code loaded without a
// URL: the DevTools console, CDP, or an extension's `executeScript`. Sentry's
// own timer wrapper is bundled with the app, so checking for any app frame
// alone misses it.
export function isInjectedScriptError(event: ErrorEvent): boolean {
const frames = (event.exception?.values ?? [])
.flatMap((exception) => exception.stacktrace?.frames ?? [])
.filter(
@@ -40,12 +45,13 @@ export function hasNoAppFrames(event: ErrorEvent): boolean {
return (
frames.length > 0 &&
!frames.some((frame) => frame.filename?.includes(APP_ASSETS_PATH))
(frames[frames.length - 1].filename === ANONYMOUS_FILENAME ||
!frames.some((frame) => frame.filename?.includes(APP_ASSETS_PATH)))
);
}
// PostHog's lazy recorder, the Pylon widget and Appcues.
const EXTERNAL_SCRIPT_URLS = [
const THIRD_PARTY_SCRIPT_URLS = [
/^https?:\/\/[^/]+\.posthog\.com\//,
/^https?:\/\/(?:[^/]+\.)?usepylon\.com\//,
/^https?:\/\/(?:[^/]+\.)?appcues\.(?:com|net)\//,
@@ -53,10 +59,10 @@ const EXTERNAL_SCRIPT_URLS = [
// Checks every frame, not only the top one: a failed fetch from the recorder
// tops out in Sentry's own fetch wrapper, which is bundled with the app.
export function isExternalIntegrationError(event: ErrorEvent): boolean {
export function isThirdPartyScriptError(event: ErrorEvent): boolean {
return (event.exception?.values ?? []).some((exception) =>
(exception.stacktrace?.frames ?? []).some((frame) =>
EXTERNAL_SCRIPT_URLS.some((url) => url.test(frame.filename ?? '')),
THIRD_PARTY_SCRIPT_URLS.some((url) => url.test(frame.filename ?? '')),
),
);
}

View File

@@ -13156,7 +13156,7 @@ export interface RuletypesNotificationSettingsDTO {
export type RuletypesPostableRuleDTOAnnotations = { [key: string]: string };
/**
* Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. severity is the conventional routing label.
* Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. A label named after one the engine writes, such as severity or threshold.name, is ignored.
*/
export type RuletypesPostableRuleDTOLabels = { [key: string]: string };
@@ -13273,7 +13273,7 @@ export interface RuletypesPostableRuleDTO {
evaluation: RuletypesEvaluationEnvelopeDTO;
/**
* @type object
* @description Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. severity is the conventional routing label.
* @description Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. A label named after one the engine writes, such as severity or threshold.name, is ignored.
*/
labels?: RuletypesPostableRuleDTOLabels;
/**
@@ -13306,7 +13306,7 @@ export interface RuletypesPostableRuleViewDTO {
export type RuletypesRuleDTOAnnotations = { [key: string]: string };
/**
* Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. severity is the conventional routing label.
* Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. A label named after one the engine writes, such as severity or threshold.name, is ignored.
*/
export type RuletypesRuleDTOLabels = { [key: string]: string };
@@ -13365,7 +13365,7 @@ export interface RuletypesRuleDTO {
id: string;
/**
* @type object
* @description Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. severity is the conventional routing label.
* @description Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. A label named after one the engine writes, such as severity or threshold.name, is ignored.
*/
labels?: RuletypesRuleDTOLabels;
/**

View File

@@ -5,6 +5,8 @@ import (
"github.com/SigNoz/signoz/pkg/http/handler"
"github.com/SigNoz/signoz/pkg/types"
"github.com/SigNoz/signoz/pkg/types/authtypes"
"github.com/SigNoz/signoz/pkg/types/coretypes"
"github.com/SigNoz/signoz/pkg/types/preferencetypes"
"github.com/gorilla/mux"
)
@@ -61,7 +63,7 @@ func (provider *provider) addPreferenceRoutes(router *mux.Router) error {
return err
}
if err := router.Handle("/api/v1/org/preferences", handler.New(provider.authzMiddleware.AdminAccess(provider.preferenceHandler.ListByOrg), handler.OpenAPIDef{
if err := router.Handle("/api/v1/org/preferences", handler.New(provider.authzMiddleware.CheckResources(provider.preferenceHandler.ListByOrg, authtypes.SigNozAdminRoleName), handler.OpenAPIDef{
ID: "ListOrgPreferences",
Tags: []string{"preferences"},
Summary: "List org preferences",
@@ -73,12 +75,17 @@ func (provider *provider) addPreferenceRoutes(router *mux.Router) error {
SuccessStatusCode: http.StatusOK,
ErrorStatusCodes: []int{},
Deprecated: false,
SecuritySchemes: newSecuritySchemes(types.RoleAdmin),
})).Methods(http.MethodGet).GetError(); err != nil {
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceOrgPreference.Scope(coretypes.VerbList)}),
}, handler.WithResourceDefs(handler.BasicResourceDef{
Resource: coretypes.ResourceMetaResourceOrgPreference,
Verb: coretypes.VerbList,
Category: coretypes.ActionCategoryDataAccess,
Selector: coretypes.WildcardSelector,
}))).Methods(http.MethodGet).GetError(); err != nil {
return err
}
if err := router.Handle("/api/v1/org/preferences/{name}", handler.New(provider.authzMiddleware.AdminAccess(provider.preferenceHandler.GetByOrg), handler.OpenAPIDef{
if err := router.Handle("/api/v1/org/preferences/{name}", handler.New(provider.authzMiddleware.CheckResources(provider.preferenceHandler.GetByOrg, authtypes.SigNozAdminRoleName), handler.OpenAPIDef{
ID: "GetOrgPreference",
Tags: []string{"preferences"},
Summary: "Get org preference",
@@ -90,12 +97,18 @@ func (provider *provider) addPreferenceRoutes(router *mux.Router) error {
SuccessStatusCode: http.StatusOK,
ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},
Deprecated: false,
SecuritySchemes: newSecuritySchemes(types.RoleAdmin),
})).Methods(http.MethodGet).GetError(); err != nil {
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceOrgPreference.Scope(coretypes.VerbRead)}),
}, handler.WithResourceDefs(handler.BasicResourceDef{
Resource: coretypes.ResourceMetaResourceOrgPreference,
Verb: coretypes.VerbRead,
Category: coretypes.ActionCategoryDataAccess,
ID: coretypes.PathParam("name"),
Selector: coretypes.WildcardSelector,
}))).Methods(http.MethodGet).GetError(); err != nil {
return err
}
if err := router.Handle("/api/v1/org/preferences/{name}", handler.New(provider.authzMiddleware.AdminAccess(provider.preferenceHandler.UpdateByOrg), handler.OpenAPIDef{
if err := router.Handle("/api/v1/org/preferences/{name}", handler.New(provider.authzMiddleware.CheckResources(provider.preferenceHandler.UpdateByOrg, authtypes.SigNozAdminRoleName), handler.OpenAPIDef{
ID: "UpdateOrgPreference",
Tags: []string{"preferences"},
Summary: "Update org preference",
@@ -107,8 +120,14 @@ func (provider *provider) addPreferenceRoutes(router *mux.Router) error {
SuccessStatusCode: http.StatusNoContent,
ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},
Deprecated: false,
SecuritySchemes: newSecuritySchemes(types.RoleAdmin),
})).Methods(http.MethodPut).GetError(); err != nil {
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceOrgPreference.Scope(coretypes.VerbUpdate)}),
}, handler.WithResourceDefs(handler.BasicResourceDef{
Resource: coretypes.ResourceMetaResourceOrgPreference,
Verb: coretypes.VerbUpdate,
Category: coretypes.ActionCategoryConfigurationChange,
ID: coretypes.PathParam("name"),
Selector: coretypes.WildcardSelector,
}))).Methods(http.MethodPut).GetError(); err != nil {
return err
}

View File

@@ -201,9 +201,7 @@ func (r *PromRule) Eval(ctx context.Context, ts time.Time) (int, error) {
lb := ruletypes.NewBuilder(result.Metric...).Del(ruletypes.MetricNameLabel)
resultLabels := ruletypes.NewBuilder(result.Metric...).Del(ruletypes.MetricNameLabel).Labels()
for name, value := range r.labels.Map() {
lb.Set(name, expand(value))
}
lb.SetRuleLabels(r.labels.Map(), expand)
lb.Set(ruletypes.AlertNameLabel, r.Name())
lb.Set(ruletypes.AlertRuleIDLabel, r.ID())

View File

@@ -278,9 +278,7 @@ func (r *ThresholdRule) Eval(ctx context.Context, ts time.Time) (int, error) {
lb := ruletypes.NewBuilder(smpl.Metric...).Del(ruletypes.MetricNameLabel).Del(ruletypes.TemporalityLabel)
resultLabels := ruletypes.NewBuilder(smpl.Metric...).Del(ruletypes.MetricNameLabel).Del(ruletypes.TemporalityLabel).Labels()
for name, value := range r.labels.Map() {
lb.Set(name, expand(value))
}
lb.SetRuleLabels(r.labels.Map(), expand)
lb.Set(ruletypes.AlertNameLabel, r.Name())
lb.Set(ruletypes.AlertRuleIDLabel, r.ID())

View File

@@ -277,6 +277,7 @@ func NewSQLMigrationProviderFactories(
sqlmigration.NewRemoveUnsupportedQuickFiltersFactory(),
sqlmigration.NewMigrateRelatedLinksTemplateFactory(),
sqlmigration.NewAddOrganizationTuplesFactory(sqlstore),
sqlmigration.NewAddOrgPreferenceTuplesFactory(sqlstore),
)
}

View File

@@ -0,0 +1,133 @@
package sqlmigration
import (
"context"
"database/sql"
"time"
"github.com/oklog/ulid/v2"
"github.com/uptrace/bun"
"github.com/uptrace/bun/dialect"
"github.com/uptrace/bun/migrate"
"github.com/SigNoz/signoz/pkg/factory"
"github.com/SigNoz/signoz/pkg/sqlstore"
)
type addOrgPreferenceTuples struct {
sqlstore sqlstore.SQLStore
}
func NewAddOrgPreferenceTuplesFactory(sqlstore sqlstore.SQLStore) factory.ProviderFactory[SQLMigration, Config] {
return factory.NewProviderFactory(factory.MustNewName("add_org_preference_tuples"), func(ctx context.Context, ps factory.ProviderSettings, c Config) (SQLMigration, error) {
return &addOrgPreferenceTuples{sqlstore: sqlstore}, nil
})
}
func (migration *addOrgPreferenceTuples) Register(migrations *migrate.Migrations) error {
return migrations.Register(migration.Up, migration.Down)
}
func (migration *addOrgPreferenceTuples) Up(ctx context.Context, db *bun.DB) error {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer func() { _ = tx.Rollback() }()
var storeID string
err = tx.QueryRowContext(ctx, `SELECT id FROM store WHERE name = ? LIMIT 1`, "signoz").Scan(&storeID)
if err != nil {
return err
}
var orgIDs []string
err = tx.NewSelect().
Table("organizations").
Column("id").
Scan(ctx, &orgIDs)
if err != nil && err != sql.ErrNoRows {
return err
}
isPG := migration.sqlstore.BunDB().Dialect().Name() == dialect.PG
tuples := []migrationTuple{
{"signoz-admin", "metaresource", "org-preference", "read"},
{"signoz-admin", "metaresource", "org-preference", "update"},
{"signoz-admin", "metaresource", "org-preference", "delete"},
{"signoz-admin", "metaresource", "org-preference", "create"},
{"signoz-admin", "metaresource", "org-preference", "list"},
}
for _, orgID := range orgIDs {
for _, tuple := range tuples {
entropy := ulid.DefaultEntropy()
now := time.Now().UTC()
tupleID := ulid.MustNew(ulid.Timestamp(now), entropy).String()
objectID := "organization/" + orgID + "/" + tuple.objectName + "/*"
roleSubject := "organization/" + orgID + "/role/" + tuple.roleName
if isPG {
user := "role:" + roleSubject + "#assignee"
result, err := tx.ExecContext(ctx, `
INSERT INTO tuple (store, object_type, object_id, relation, _user, user_type, ulid, inserted_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (store, object_type, object_id, relation, _user) DO NOTHING`,
storeID, tuple.objectType, objectID, tuple.relation, user, "userset", tupleID, now,
)
if err != nil {
return err
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return err
}
if rowsAffected == 0 {
continue
}
_, err = tx.ExecContext(ctx, `
INSERT INTO changelog (store, object_type, object_id, relation, _user, operation, ulid, inserted_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (store, ulid, object_type) DO NOTHING`,
storeID, tuple.objectType, objectID, tuple.relation, user, 0, tupleID, now,
)
if err != nil {
return err
}
} else {
result, err := tx.ExecContext(ctx, `
INSERT INTO tuple (store, object_type, object_id, relation, user_object_type, user_object_id, user_relation, user_type, ulid, inserted_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (store, object_type, object_id, relation, user_object_type, user_object_id, user_relation) DO NOTHING`,
storeID, tuple.objectType, objectID, tuple.relation, "role", roleSubject, "assignee", "userset", tupleID, now,
)
if err != nil {
return err
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return err
}
if rowsAffected == 0 {
continue
}
_, err = tx.ExecContext(ctx, `
INSERT INTO changelog (store, object_type, object_id, relation, user_object_type, user_object_id, user_relation, operation, ulid, inserted_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (store, ulid, object_type) DO NOTHING`,
storeID, tuple.objectType, objectID, tuple.relation, "role", roleSubject, "assignee", 0, tupleID, now,
)
if err != nil {
return err
}
}
}
}
return tx.Commit()
}
func (migration *addOrgPreferenceTuples) Down(context.Context, *bun.DB) error {
return nil
}

View File

@@ -71,7 +71,7 @@ type PostableRule struct {
RuleType RuleType `json:"ruleType" required:"true" description:"The evaluation strategy: threshold_rule compares against thresholds, promql_rule evaluates a PromQL expression, anomaly_rule scores deviation from seasonal history. Defaults to threshold_rule for builder and clickhouse_sql queries and is forced to promql_rule for promql queries."`
RuleCondition *RuleCondition `json:"condition" required:"true" description:"The query to evaluate and the thresholds applied to its result."`
Labels map[string]string `json:"labels,omitempty" description:"Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. severity is the conventional routing label."`
Labels map[string]string `json:"labels,omitempty" description:"Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. A label named after one the engine writes, such as severity or threshold.name, is ignored."`
Annotations map[string]string `json:"annotations,omitempty" description:"Free text attached to every alert, conventionally summary and description. Values may use Go templates with $value, $threshold and $labels."`
Disabled bool `json:"disabled" description:"Whether the rule is paused. A disabled rule is neither evaluated nor notifies. Defaults to false."`

View File

@@ -31,6 +31,23 @@ const (
AlertDescriptionLabel = "description"
)
// reservedLabelNames are written by the rule engine; a rule label with one of
// these names never reaches the alert.
var reservedLabelNames = map[string]struct{}{
MetricNameLabel: {},
TemporalityLabel: {},
AlertNameLabel: {},
AlertRuleIDLabel: {},
RuleSourceLabel: {},
NoDataLabel: {},
LabelThresholdName: {},
LabelSeverityName: {},
LabelLastSeen: {},
// TODO: the template layer reads is_recovering but nothing writes it;
// set it from Alert.IsRecovering.
LabelIsRecovering: {},
}
// Label is a key/value pair of strings.
// TODO(srikanthccv): https://github.com/SigNoz/signoz/issues/9232?
type Label struct {
@@ -285,6 +302,20 @@ func (b *Builder) Set(n, v string) *Builder {
return b
}
// SetRuleLabels adds the rule's labels, each expanded, skipping the names the
// engine writes.
// TODO: a rule label still overwrites a query result label of the same name;
// decide whether those are locked too.
func (b *Builder) SetRuleLabels(ruleLabels map[string]string, expand func(string) string) *Builder {
for name, value := range ruleLabels {
if _, reserved := reservedLabelNames[name]; reserved {
continue
}
b.Set(name, expand(value))
}
return b
}
// Labels returns the labels from the builder. If no modifications
// were made, the original labels are returned.
func (b *Builder) Labels() Labels {

View File

@@ -131,14 +131,23 @@ export interface Settings {
/** The member's table row. Search for the email first: the list pages at 20. */
row(email: string): Locator;
inviteButton(): Locator;
searchInput(): Locator;
resetLinkButton(): Locator;
/** The "is not authorized" message a denied list or drawer renders. */
deniedMessage(): Locator;
openInvite(): Promise<void>;
inviteDialog(): Locator;
invite(rows: { email: string; role: string }[]): Promise<void>;
openMember(email: string): Promise<void>;
drawer(): Locator;
nameInput(): Locator;
roleSelect(): Locator;
deleteButton(): Locator;
setRoles(roles: string[]): Promise<void>;
/** Add a role to the open member without clearing the others. */
addRole(role: string): Promise<void>;
/** Remove one role from the open member, leaving the others. */
removeRole(role: string): Promise<void>;
saveMember(): Promise<void>;
/** Mint a reset or invite link from the drawer and return it. */
generateLink(): Promise<string>;
@@ -414,6 +423,9 @@ export function settingsDriver(page: Page): Settings {
// antd keys each row by the member id; the email is what callers hold.
row: (email) => page.locator('tr[data-row-key]').filter({ hasText: email }),
inviteButton: () => page.getByTestId('invite-member-btn'),
searchInput: () => page.getByTestId('members-search-input'),
resetLinkButton: () => page.getByTestId('member-reset-link-btn'),
deniedMessage: () => page.getByText(/is not authorized/).first(),
openInvite: async () => {
await settings.members.inviteButton().click();
await expect(settings.members.inviteDialog()).toBeVisible();
@@ -449,6 +461,7 @@ export function settingsDriver(page: Page): Settings {
await expect(settings.members.drawer().getByText(email)).toBeVisible();
},
drawer: () => page.getByRole('dialog', { name: 'Member Details' }),
nameInput: () => page.getByPlaceholder('Enter name'),
roleSelect: () => selectById('member-role'),
deleteButton: () => page.getByTestId('member-delete-btn'),
setRoles: async (roles) => {
@@ -458,6 +471,21 @@ export function settingsDriver(page: Page): Settings {
await pickInDialog(settings.members.drawer(), select, role);
}
},
addRole: async (role) => {
await pickInDialog(
settings.members.drawer(),
settings.members.roleSelect(),
role,
);
},
removeRole: async (role) => {
await settings.members
.roleSelect()
.locator('.ant-select-selection-item')
.filter({ hasText: role })
.locator('.ant-select-selection-item-remove')
.click();
},
saveMember: async () => {
await page.getByTestId('member-save-btn').click();
await expect(

View File

@@ -1,7 +1,7 @@
import { withAuthFlows } from '../auth-flows';
import { kit } from '../kit';
import { guestDriver, kit, type Layer } from '../kit';
import { withSettings } from './driver';
import { settingsDriver, withSettings, type Settings } from './driver';
import {
withActiveEditor,
withCustomRoleSeed,
@@ -9,6 +9,12 @@ import {
withServiceAccountSeed,
} from './seeds';
/** The settings pages bound to the logged-out `guestPage`, for a signed-in member. */
const withGuestSettings: Layer<{ guestSettings: Settings }> = guestDriver(
'guestSettings',
({ page }) => settingsDriver(page),
);
/**
* The settings `test`. Seeds are test-scoped and lazy: a spec pays only for the
* ones it destructures. `authFlows` drives a guest context, for the flows that
@@ -16,8 +22,10 @@ import {
*/
export const test = withAuthFlows(
withSettings(
withActiveEditor(
withPendingMember(withServiceAccountSeed(withCustomRoleSeed(kit))),
withGuestSettings(
withActiveEditor(
withPendingMember(withServiceAccountSeed(withCustomRoleSeed(kit))),
),
),
),
);

View File

@@ -1,9 +1,11 @@
import type { Browser, TestType } from '@playwright/test';
import type { User } from '../auth';
import type { AuthtypesTransactionGroupDTO } from '../schemas';
import { onAdminPage, type Layer } from '../kit';
import { usersApi, type CreatedUser } from '../users';
import { grantAll, roleName, settingsDriver } from './driver';
import { grantAll, roleName, settingsDriver, type Settings } from './driver';
/**
* Test-scoped seeds. Each test that asks for one gets its own copy, created on
@@ -123,3 +125,40 @@ export const withActiveEditor = perTest(
({ browser, value }) =>
onAdminPage(browser, (page) => usersApi(page).remove(value.id)),
);
export interface GrantedUser {
user: User;
role: string;
remove(): Promise<void>;
}
/**
* An active member whose only role is a fresh custom role holding
* `transactionGroups`. Call `remove` in a `finally`.
*/
export async function createGrantedUser(
settings: Settings,
workerIndex: number,
kind: string,
transactionGroups: AuthtypesTransactionGroupDTO[],
): Promise<GrantedUser> {
const name = roleName(kind, workerIndex);
const roleId = await settings.roles.createApi({ name, transactionGroups });
const label = `${kind}-w${workerIndex}-${Date.now()}`;
let member: CreatedUser;
try {
member = await settings.users.createActive(name, label);
} catch (error) {
await settings.users.removeByEmail(`e2e-${label}@signoz.test`);
await settings.roles.removeApi(roleId);
throw error;
}
return {
user: member.user,
role: name,
remove: async () => {
await settings.users.remove(member.id);
await settings.roles.removeApi(roleId);
},
};
}

View File

@@ -1,4 +1,9 @@
import { expect, test } from '../../drivers/settings';
import {
createGrantedUser,
expect,
grantAll,
test,
} from '../../drivers/settings';
test.describe('settings — members', () => {
test('TC-01 an invite of two rows creates two pending members', async ({
@@ -62,4 +67,163 @@ test.describe('settings — members', () => {
await settings.members.search(email);
await expect(settings.members.row(email)).toContainText('DELETED');
});
test('TC-04 a user without create:user cannot invite members', async ({
settings,
authFlows,
guestSettings,
}, testInfo) => {
const member = await createGrantedUser(
settings,
testInfo.workerIndex,
'list-users',
[grantAll('list', 'user', 'user')],
);
try {
await authFlows.login(member.user);
await guestSettings.members.goto();
await expect(guestSettings.members.inviteButton()).toHaveAttribute(
'data-denied-permissions',
/create/,
);
} finally {
await member.remove();
}
});
test('TC-05 a user without list:user cannot list members', async ({
settings,
authFlows,
guestSettings,
}, testInfo) => {
const member = await createGrantedUser(
settings,
testInfo.workerIndex,
'no-list',
[grantAll('read', 'dashboard')],
);
try {
await authFlows.login(member.user);
await guestSettings.members.goto();
await expect(guestSettings.members.deniedMessage()).toBeVisible();
await expect(guestSettings.members.searchInput()).toHaveAttribute(
'data-denied-permissions',
/list/,
);
} finally {
await member.remove();
}
});
test('TC-06 an invite link is unavailable without factor-password:list', async ({
settings,
authFlows,
guestSettings,
pendingMember,
}, testInfo) => {
const member = await createGrantedUser(
settings,
testInfo.workerIndex,
'no-pwd',
[grantAll('list', 'user', 'user'), grantAll('read', 'user', 'user')],
);
try {
await authFlows.login(member.user);
await guestSettings.members.goto();
await guestSettings.members.openMember(pendingMember.email);
await expect(guestSettings.members.resetLinkButton()).toHaveAttribute(
'data-denied-permissions',
/factor-password/,
);
await expect(guestSettings.members.resetLinkButton()).toContainText(
'Invite Link Unavailable',
);
} finally {
await member.remove();
}
});
test('TC-07 a member can add and remove a role on themselves', async ({
settings,
authFlows,
guestSettings,
}, testInfo) => {
const member = await createGrantedUser(
settings,
testInfo.workerIndex,
'self-edit',
[
grantAll('list', 'user', 'user'),
grantAll('read', 'user', 'user'),
grantAll('attach', 'user', 'user'),
grantAll('detach', 'user', 'user'),
grantAll('list', 'role', 'role'),
grantAll('read', 'role', 'role'),
grantAll('attach', 'role', 'role'),
grantAll('detach', 'role', 'role'),
],
);
try {
await authFlows.login(member.user);
await guestSettings.members.goto();
await guestSettings.members.openMember(member.user.email);
await guestSettings.members.addRole('signoz-viewer');
await guestSettings.members.saveMember();
await guestSettings.reload();
await guestSettings.members.openMember(member.user.email);
await expect(guestSettings.members.roleSelect()).toContainText(
'signoz-viewer',
);
const added = await settings.users.byEmail(member.user.email);
expect(
(added?.userRoles ?? []).map((entry) => entry.role.name).sort(),
).toEqual([member.role, 'signoz-viewer'].sort());
await guestSettings.members.removeRole('signoz-viewer');
await guestSettings.members.saveMember();
await guestSettings.reload();
await guestSettings.members.openMember(member.user.email);
await expect(guestSettings.members.roleSelect()).not.toContainText(
'signoz-viewer',
);
const removed = await settings.users.byEmail(member.user.email);
expect((removed?.userRoles ?? []).map((entry) => entry.role.name)).toEqual([
member.role,
]);
} finally {
await member.remove();
}
});
test('TC-08 a user without update:user cannot rename another member', async ({
settings,
authFlows,
guestSettings,
activeEditor,
}, testInfo) => {
const member = await createGrantedUser(
settings,
testInfo.workerIndex,
'no-update',
[grantAll('list', 'user', 'user'), grantAll('read', 'user', 'user')],
);
try {
await authFlows.login(member.user);
await guestSettings.members.goto();
await guestSettings.members.openMember(activeEditor.user.email);
await expect(guestSettings.members.nameInput()).toHaveAttribute(
'data-denied-permissions',
/update/,
);
} finally {
await member.remove();
}
});
});

View File

@@ -0,0 +1,12 @@
{"metric_name":"request_total_reserved_labels_from_engine","labels":{"service":"api","endpoint":"/health","status_code":"200"},"timestamp":"2026-01-29T10:01:00+00:00","value":1,"temporality":"Cumulative","type_":"Sum","is_monotonic":false,"flags":0,"description":"","unit":"","env":"default","resource_attrs":{},"scope_attrs":{}}
{"metric_name":"request_total_reserved_labels_from_engine","labels":{"service":"api","endpoint":"/health","status_code":"200"},"timestamp":"2026-01-29T10:02:00+00:00","value":2,"temporality":"Cumulative","type_":"Sum","is_monotonic":false,"flags":0,"description":"","unit":"","env":"default","resource_attrs":{},"scope_attrs":{}}
{"metric_name":"request_total_reserved_labels_from_engine","labels":{"service":"api","endpoint":"/health","status_code":"200"},"timestamp":"2026-01-29T10:03:00+00:00","value":4,"temporality":"Cumulative","type_":"Sum","is_monotonic":false,"flags":0,"description":"","unit":"","env":"default","resource_attrs":{},"scope_attrs":{}}
{"metric_name":"request_total_reserved_labels_from_engine","labels":{"service":"api","endpoint":"/health","status_code":"200"},"timestamp":"2026-01-29T10:04:00+00:00","value":4,"temporality":"Cumulative","type_":"Sum","is_monotonic":false,"flags":0,"description":"","unit":"","env":"default","resource_attrs":{},"scope_attrs":{}}
{"metric_name":"request_total_reserved_labels_from_engine","labels":{"service":"api","endpoint":"/health","status_code":"200"},"timestamp":"2026-01-29T10:05:00+00:00","value":15,"temporality":"Cumulative","type_":"Sum","is_monotonic":false,"flags":0,"description":"","unit":"","env":"default","resource_attrs":{},"scope_attrs":{}}
{"metric_name":"request_total_reserved_labels_from_engine","labels":{"service":"api","endpoint":"/health","status_code":"200"},"timestamp":"2026-01-29T10:06:00+00:00","value":10,"temporality":"Cumulative","type_":"Sum","is_monotonic":false,"flags":0,"description":"","unit":"","env":"default","resource_attrs":{},"scope_attrs":{}}
{"metric_name":"request_total_reserved_labels_from_engine","labels":{"service":"api","endpoint":"/health","status_code":"200"},"timestamp":"2026-01-29T10:07:00+00:00","value":36,"temporality":"Cumulative","type_":"Sum","is_monotonic":false,"flags":0,"description":"","unit":"","env":"default","resource_attrs":{},"scope_attrs":{}}
{"metric_name":"request_total_reserved_labels_from_engine","labels":{"service":"api","endpoint":"/health","status_code":"200"},"timestamp":"2026-01-29T10:08:00+00:00","value":25,"temporality":"Cumulative","type_":"Sum","is_monotonic":false,"flags":0,"description":"","unit":"","env":"default","resource_attrs":{},"scope_attrs":{}}
{"metric_name":"request_total_reserved_labels_from_engine","labels":{"service":"api","endpoint":"/health","status_code":"200"},"timestamp":"2026-01-29T10:09:00+00:00","value":37,"temporality":"Cumulative","type_":"Sum","is_monotonic":false,"flags":0,"description":"","unit":"","env":"default","resource_attrs":{},"scope_attrs":{}}
{"metric_name":"request_total_reserved_labels_from_engine","labels":{"service":"api","endpoint":"/health","status_code":"200"},"timestamp":"2026-01-29T10:10:00+00:00","value":35,"temporality":"Cumulative","type_":"Sum","is_monotonic":false,"flags":0,"description":"","unit":"","env":"default","resource_attrs":{},"scope_attrs":{}}
{"metric_name":"request_total_reserved_labels_from_engine","labels":{"service":"api","endpoint":"/health","status_code":"200"},"timestamp":"2026-01-29T10:11:00+00:00","value":39,"temporality":"Cumulative","type_":"Sum","is_monotonic":false,"flags":0,"description":"","unit":"","env":"default","resource_attrs":{},"scope_attrs":{}}
{"metric_name":"request_total_reserved_labels_from_engine","labels":{"service":"api","endpoint":"/health","status_code":"200"},"timestamp":"2026-01-29T10:12:00+00:00","value":25,"temporality":"Cumulative","type_":"Sum","is_monotonic":false,"flags":0,"description":"","unit":"","env":"default","resource_attrs":{},"scope_attrs":{}}

View File

@@ -0,0 +1,57 @@
{
"alert": "reserved_labels_from_engine",
"ruleType": "threshold_rule",
"alertType": "METRIC_BASED_ALERT",
"condition": {
"thresholds": {
"kind": "basic",
"spec": [
{
"name": "critical",
"target": 10,
"matchType": "at_least_once",
"op": "above",
"channels": [
"test channel"
]
}
]
},
"compositeQuery": {
"queryType": "clickhouse_sql",
"panelType": "graph",
"queries": [
{
"type": "clickhouse_sql",
"spec": {
"name": "A",
"query": "WITH __temporal_aggregation_cte AS (\n SELECT \n fingerprint, \n toStartOfInterval(toDateTime(intDiv(unix_milli, 1000)), toIntervalSecond(60)) AS ts, \n avg(value) AS per_series_value \n FROM signoz_metrics.distributed_samples_v4 AS points \n INNER JOIN (\n SELECT fingerprint \n FROM signoz_metrics.time_series_v4 \n WHERE metric_name IN ('request_total_reserved_labels_from_engine') \n AND LOWER(temporality) LIKE LOWER('cumulative') \n GROUP BY fingerprint\n ) AS filtered_time_series ON points.fingerprint = filtered_time_series.fingerprint \n WHERE metric_name IN ('request_total_reserved_labels_from_engine') \n AND unix_milli >= $start_timestamp_ms \n AND unix_milli < $end_timestamp_ms \n GROUP BY fingerprint, ts \n ORDER BY fingerprint, ts\n), \n__spatial_aggregation_cte AS (\n SELECT \n ts, \n sum(per_series_value) AS value \n FROM __temporal_aggregation_cte \n WHERE isNaN(per_series_value) = 0 \n GROUP BY ts\n) \nSELECT * FROM __spatial_aggregation_cte \nORDER BY ts"
}
}
]
},
"selectedQueryName": "A"
},
"evaluation": {
"kind": "rolling",
"spec": {
"evalWindow": "5m0s",
"frequency": "15s"
}
},
"labels": {"threshold.name": "spoofed", "severity": "spoofed", "team": "payments"},
"annotations": {
"description": "This alert is fired when the defined metric (current value: {{$value}}) crosses the threshold ({{$threshold}})",
"summary": "This alert is fired when the defined metric (current value: {{$value}}) crosses the threshold ({{$threshold}})"
},
"notificationSettings": {
"groupBy": [],
"usePolicy": false,
"renotify": {
"enabled": false,
"interval": "30m",
"alertStates": []
}
},
"schemaVersion": "v2alpha1"
}

View File

@@ -543,6 +543,32 @@ TEST_RULES_MISCELLANEOUS = [
],
),
),
# the rule carries threshold.name and severity labels of its own; the alert
# keeps the values the engine wrote and only the plain label comes through
types.AlertTestCase(
name="test_rule_labels_do_not_override_engine_labels",
rule_path="ruler/test_scenarios/reserved_labels_from_engine/rule.json",
alert_data=[
types.AlertData(
type="metrics",
data_path="ruler/test_scenarios/reserved_labels_from_engine/alert_data.jsonl",
),
],
alert_expectation=types.AlertExpectation(
should_alert=True,
wait_time_seconds=30,
expected_alerts=[
types.FiringAlert(
labels={
"alertname": "reserved_labels_from_engine",
"threshold.name": "critical",
"severity": "critical",
"team": "payments",
}
),
],
),
),
# TODO: @abhishekhugetech enable the test for multi threshold rule, pylint: disable=W0511
# after the [issue](https://github.com/SigNoz/engineering-pod/issues/3934) with alertManager is resolved
# types.AlertTestCase(