Compare commits

...

4 Commits

Author SHA1 Message Date
nityanandagohain
20080ec988 Merge remote-tracking branch 'origin/main' into issue_nerve_462 2026-10-29 16:17:03 +05:30
Naman Verma
5097d1578f chore: preemptively update rules v2 schema's api spec properties (#13306)
Some checks are pending
build-staging / js-build (push) Blocked by required conditions
build-staging / prepare (push) Waiting to run
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

Rules v1 to v2 migration is gonna happen soon, so its better to have at
least our api spec updated so that agents stop creating v1 rules
2026-10-29 09:29:02 +00:00
nityanandagohain
fb33e31c4c Merge remote-tracking branch 'origin/main' into issue_nerve_462 2026-10-26 17:54:41 +05:30
nityanandagohain
0a0cd96e93 feat(spanmapper): add fga to span mapper group and mapper routes 2026-10-26 17:51:42 +05:30
18 changed files with 964 additions and 173 deletions

View File

@@ -3932,6 +3932,8 @@ components:
- logs-field
- traces-field
- metrics-field
- span-mapper-group
- span-mapper
type: string
CoretypesObject:
properties:
@@ -11389,8 +11391,7 @@ components:
evaluation:
allOf:
- $ref: '#/components/schemas/RuletypesEvaluationEnvelope'
description: The evaluation window, as a kind and spec. Required when schemaVersion
is v2alpha1; derived from evalWindow and frequency for v1.
description: The evaluation window, as a kind and spec.
frequency:
description: How often the rule is evaluated, as a Go duration such as 1m.
Only read when schemaVersion is v1, defaulting to 1m; v2alpha1 rules set
@@ -11406,8 +11407,7 @@ components:
notificationSettings:
allOf:
- $ref: '#/components/schemas/RuletypesNotificationSettings'
description: Grouping, re-notification and routing behaviour. Required when
schemaVersion is v2alpha1; derived from the v1 fields otherwise.
description: Grouping, re-notification and routing behaviour.
preferredChannels:
description: The displayName of each notification channel to notify, for
schemaVersion v1 rules. Ignored for v2alpha1, where each threshold carries
@@ -11420,26 +11420,30 @@ components:
- $ref: '#/components/schemas/RuletypesRuleType'
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 queries
and is forced to promql_rule for promql queries.'
from seasonal history. Defaults to threshold_rule for builder and clickhouse_sql
queries and is forced to promql_rule for promql queries.'
schemaVersion:
description: 'The rule payload schema: v1 (the default when omitted) uses
the flat condition fields, v2alpha1 uses condition.thresholds, evaluation
and notificationSettings.'
description: The rule payload schema.
enum:
- v2alpha1
type: string
source:
deprecated: true
description: The URL of the page the rule was created from. Informational;
it is not used for evaluation.
type: string
version:
description: The query payload version. Only v5 is accepted and it is filled
in when omitted.
deprecated: true
description: The query payload version. Nothing reads it.
type: string
required:
- alert
- alertType
- ruleType
- condition
- evaluation
- schemaVersion
- notificationSettings
type: object
RuletypesPostableRuleView:
properties:
@@ -11528,8 +11532,7 @@ components:
evaluation:
allOf:
- $ref: '#/components/schemas/RuletypesEvaluationEnvelope'
description: The evaluation window, as a kind and spec. Required when schemaVersion
is v2alpha1; derived from evalWindow and frequency for v1.
description: The evaluation window, as a kind and spec.
frequency:
description: How often the rule is evaluated, as a Go duration such as 1m.
Only read when schemaVersion is v1, defaulting to 1m; v2alpha1 rules set
@@ -11548,8 +11551,7 @@ components:
notificationSettings:
allOf:
- $ref: '#/components/schemas/RuletypesNotificationSettings'
description: Grouping, re-notification and routing behaviour. Required when
schemaVersion is v2alpha1; derived from the v1 fields otherwise.
description: Grouping, re-notification and routing behaviour.
preferredChannels:
description: The displayName of each notification channel to notify, for
schemaVersion v1 rules. Ignored for v2alpha1, where each threshold carries
@@ -11562,14 +11564,15 @@ components:
- $ref: '#/components/schemas/RuletypesRuleType'
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 queries
and is forced to promql_rule for promql queries.'
from seasonal history. Defaults to threshold_rule for builder and clickhouse_sql
queries and is forced to promql_rule for promql queries.'
schemaVersion:
description: 'The rule payload schema: v1 (the default when omitted) uses
the flat condition fields, v2alpha1 uses condition.thresholds, evaluation
and notificationSettings.'
description: The rule payload schema.
enum:
- v2alpha1
type: string
source:
deprecated: true
description: The URL of the page the rule was created from. Informational;
it is not used for evaluation.
type: string
@@ -11584,8 +11587,8 @@ components:
updatedBy:
type: string
version:
description: The query payload version. Only v5 is accepted and it is filled
in when omitted.
deprecated: true
description: The query payload version. Nothing reads it.
type: string
required:
- id
@@ -11594,6 +11597,9 @@ components:
- alertType
- ruleType
- condition
- evaluation
- schemaVersion
- notificationSettings
type: object
RuletypesRuleCondition:
properties:
@@ -11643,8 +11649,7 @@ components:
against, hourly, daily or weekly.'
selectedQueryName:
description: The name of the query whose result is evaluated, such as A
or F1. Must match a query in compositeQuery. When omitted, F1 is used
if present, otherwise the enabled query with the highest name.
or F1. Must match a query in compositeQuery.
type: string
target:
description: 'schemaVersion v1 only: the value compared against, in targetUnit.
@@ -11660,10 +11665,11 @@ components:
thresholds:
allOf:
- $ref: '#/components/schemas/RuletypesRuleThresholdData'
description: The thresholds to evaluate, as a kind and spec. Required when
schemaVersion is v2alpha1; derived from op, target and matchType for v1.
description: The thresholds to evaluate, as a kind and spec.
required:
- compositeQuery
- selectedQueryName
- thresholds
type: object
RuletypesRuleThresholdData:
discriminator:
@@ -17810,9 +17816,9 @@ paths:
description: Internal Server Error
security:
- api_key:
- VIEWER
- span-mapper-group:list
- tokenizer:
- VIEWER
- span-mapper-group:list
summary: List span attribute mapping groups
tags:
- spanmapper
@@ -17873,9 +17879,9 @@ paths:
description: Internal Server Error
security:
- api_key:
- ADMIN
- span-mapper-group:create
- tokenizer:
- ADMIN
- span-mapper-group:create
summary: Create a span attribute mapping group
tags:
- spanmapper
@@ -17920,9 +17926,9 @@ paths:
description: Internal Server Error
security:
- api_key:
- ADMIN
- span-mapper-group:delete
- tokenizer:
- ADMIN
- span-mapper-group:delete
summary: Delete a span attribute mapping group
tags:
- spanmapper
@@ -17978,9 +17984,9 @@ paths:
description: Internal Server Error
security:
- api_key:
- ADMIN
- span-mapper-group:update
- tokenizer:
- ADMIN
- span-mapper-group:update
summary: Update a span attribute mapping group
tags:
- spanmapper
@@ -18043,9 +18049,9 @@ paths:
description: Internal Server Error
security:
- api_key:
- VIEWER
- span-mapper-group:read
- tokenizer:
- VIEWER
- span-mapper-group:read
summary: List span mappers for a group
tags:
- spanmapper
@@ -18118,9 +18124,11 @@ paths:
description: Internal Server Error
security:
- api_key:
- ADMIN
- span-mapper:create
- span-mapper-group:attach
- tokenizer:
- ADMIN
- span-mapper:create
- span-mapper-group:attach
summary: Create a span mapper
tags:
- spanmapper
@@ -18170,9 +18178,11 @@ paths:
description: Internal Server Error
security:
- api_key:
- ADMIN
- span-mapper:delete
- span-mapper-group:detach
- tokenizer:
- ADMIN
- span-mapper:delete
- span-mapper-group:detach
summary: Delete a span mapper
tags:
- spanmapper
@@ -18233,9 +18243,9 @@ paths:
description: Internal Server Error
security:
- api_key:
- ADMIN
- span-mapper:update
- tokenizer:
- ADMIN
- span-mapper:update
summary: Update a span mapper
tags:
- spanmapper
@@ -18243,7 +18253,8 @@ paths:
/api/v1/span_mapper_groups/test:
post:
deprecated: false
description: Tests how span mappers would transform sample spans
description: Tests how span mappers would transform sample spans. Groups sent
without mappers are read from the store by name.
operationId: TestSpanMappers
requestBody:
content:
@@ -18297,9 +18308,9 @@ paths:
description: Internal Server Error
security:
- api_key:
- VIEWER
- span-mapper-group:read
- tokenizer:
- VIEWER
- span-mapper-group:read
summary: Test span mappers against sample spans
tags:
- spanmapper
@@ -25312,13 +25323,13 @@ paths:
schemaVersion: v2alpha1
version: v5
metric_anomaly:
description: Anomaly rules are not yet supported under schemaVersion
v2alpha1, so this example uses the v1 shape. Wraps a builder query
in the `anomaly` function with daily seasonality SigNoz compares
each point against the forecast for that time of day. Fires when
the anomaly score stays below the threshold for the entire window;
`requireMinPoints` guards against noisy intervals.
summary: Metric anomaly rule (v1 only)
description: Wraps a builder query in the `anomaly` function with
daily seasonality, so SigNoz compares each point against the forecast
for that time of day. The threshold is compared against the signed
anomaly score, so `below` with a target of -2 fires when an abrupt
drop holds for the entire window; `requireMinPoints` guards against
noisy intervals.
summary: Metric anomaly rule
value:
alert: Anomalous drop in ingested spans
alertType: METRIC_BASED_ALERT
@@ -25353,22 +25364,36 @@ paths:
stepInterval: 21600
type: builder_query
queryType: builder
matchType: all_the_times
op: below
requireMinPoints: true
requiredNumPoints: 3
seasonality: daily
selectedQueryName: A
target: 2
thresholds:
kind: basic
spec:
- channels:
- slack-ingestion
matchType: all_the_times
name: warning
op: below
target: -2
description: Detect an abrupt drop in span ingestion using a z-score
anomaly function
evalWindow: 24h
frequency: 3h
evaluation:
kind: rolling
spec:
evalWindow: 24h
frequency: 3h
labels:
severity: warning
preferredChannels:
- slack-ingestion
notificationSettings:
renotify:
alertStates:
- firing
enabled: true
interval: 4h
ruleType: anomaly_rule
schemaVersion: v2alpha1
version: v5
metric_promql:
description: PromQL expression instead of the builder. Dotted OTEL
@@ -26264,13 +26289,13 @@ paths:
schemaVersion: v2alpha1
version: v5
metric_anomaly:
description: Anomaly rules are not yet supported under schemaVersion
v2alpha1, so this example uses the v1 shape. Wraps a builder query
in the `anomaly` function with daily seasonality SigNoz compares
each point against the forecast for that time of day. Fires when
the anomaly score stays below the threshold for the entire window;
`requireMinPoints` guards against noisy intervals.
summary: Metric anomaly rule (v1 only)
description: Wraps a builder query in the `anomaly` function with
daily seasonality, so SigNoz compares each point against the forecast
for that time of day. The threshold is compared against the signed
anomaly score, so `below` with a target of -2 fires when an abrupt
drop holds for the entire window; `requireMinPoints` guards against
noisy intervals.
summary: Metric anomaly rule
value:
alert: Anomalous drop in ingested spans
alertType: METRIC_BASED_ALERT
@@ -26305,22 +26330,36 @@ paths:
stepInterval: 21600
type: builder_query
queryType: builder
matchType: all_the_times
op: below
requireMinPoints: true
requiredNumPoints: 3
seasonality: daily
selectedQueryName: A
target: 2
thresholds:
kind: basic
spec:
- channels:
- slack-ingestion
matchType: all_the_times
name: warning
op: below
target: -2
description: Detect an abrupt drop in span ingestion using a z-score
anomaly function
evalWindow: 24h
frequency: 3h
evaluation:
kind: rolling
spec:
evalWindow: 24h
frequency: 3h
labels:
severity: warning
preferredChannels:
- slack-ingestion
notificationSettings:
renotify:
alertStates:
- firing
enabled: true
interval: 4h
ruleType: anomaly_rule
schemaVersion: v2alpha1
version: v5
metric_promql:
description: PromQL expression instead of the builder. Dotted OTEL
@@ -27117,13 +27156,13 @@ paths:
schemaVersion: v2alpha1
version: v5
metric_anomaly:
description: Anomaly rules are not yet supported under schemaVersion
v2alpha1, so this example uses the v1 shape. Wraps a builder query
in the `anomaly` function with daily seasonality SigNoz compares
each point against the forecast for that time of day. Fires when
the anomaly score stays below the threshold for the entire window;
`requireMinPoints` guards against noisy intervals.
summary: Metric anomaly rule (v1 only)
description: Wraps a builder query in the `anomaly` function with
daily seasonality, so SigNoz compares each point against the forecast
for that time of day. The threshold is compared against the signed
anomaly score, so `below` with a target of -2 fires when an abrupt
drop holds for the entire window; `requireMinPoints` guards against
noisy intervals.
summary: Metric anomaly rule
value:
alert: Anomalous drop in ingested spans
alertType: METRIC_BASED_ALERT
@@ -27158,22 +27197,36 @@ paths:
stepInterval: 21600
type: builder_query
queryType: builder
matchType: all_the_times
op: below
requireMinPoints: true
requiredNumPoints: 3
seasonality: daily
selectedQueryName: A
target: 2
thresholds:
kind: basic
spec:
- channels:
- slack-ingestion
matchType: all_the_times
name: warning
op: below
target: -2
description: Detect an abrupt drop in span ingestion using a z-score
anomaly function
evalWindow: 24h
frequency: 3h
evaluation:
kind: rolling
spec:
evalWindow: 24h
frequency: 3h
labels:
severity: warning
preferredChannels:
- slack-ingestion
notificationSettings:
renotify:
alertStates:
- firing
enabled: true
interval: 4h
ruleType: anomaly_rule
schemaVersion: v2alpha1
version: v5
metric_promql:
description: PromQL expression instead of the builder. Dotted OTEL
@@ -28676,13 +28729,13 @@ paths:
schemaVersion: v2alpha1
version: v5
metric_anomaly:
description: Anomaly rules are not yet supported under schemaVersion
v2alpha1, so this example uses the v1 shape. Wraps a builder query
in the `anomaly` function with daily seasonality SigNoz compares
each point against the forecast for that time of day. Fires when
the anomaly score stays below the threshold for the entire window;
`requireMinPoints` guards against noisy intervals.
summary: Metric anomaly rule (v1 only)
description: Wraps a builder query in the `anomaly` function with
daily seasonality, so SigNoz compares each point against the forecast
for that time of day. The threshold is compared against the signed
anomaly score, so `below` with a target of -2 fires when an abrupt
drop holds for the entire window; `requireMinPoints` guards against
noisy intervals.
summary: Metric anomaly rule
value:
alert: Anomalous drop in ingested spans
alertType: METRIC_BASED_ALERT
@@ -28717,22 +28770,36 @@ paths:
stepInterval: 21600
type: builder_query
queryType: builder
matchType: all_the_times
op: below
requireMinPoints: true
requiredNumPoints: 3
seasonality: daily
selectedQueryName: A
target: 2
thresholds:
kind: basic
spec:
- channels:
- slack-ingestion
matchType: all_the_times
name: warning
op: below
target: -2
description: Detect an abrupt drop in span ingestion using a z-score
anomaly function
evalWindow: 24h
frequency: 3h
evaluation:
kind: rolling
spec:
evalWindow: 24h
frequency: 3h
labels:
severity: warning
preferredChannels:
- slack-ingestion
notificationSettings:
renotify:
alertStates:
- firing
enabled: true
interval: 4h
ruleType: anomaly_rule
schemaVersion: v2alpha1
version: v5
metric_promql:
description: PromQL expression instead of the builder. Dotted OTEL

View File

@@ -3579,6 +3579,8 @@ export enum CoretypesKindDTO {
'logs-field' = 'logs-field',
'traces-field' = 'traces-field',
'metrics-field' = 'metrics-field',
'span-mapper-group' = 'span-mapper-group',
'span-mapper' = 'span-mapper',
}
export enum CoretypesTypeDTO {
user = 'user',
@@ -12584,6 +12586,12 @@ export type RuletypesPostableRuleDTOAnnotations = { [key: string]: string };
*/
export type RuletypesPostableRuleDTOLabels = { [key: string]: string };
/**
* The rule payload schema.
*/
export enum RuletypesPostableRuleDTOSchemaVersion {
v2alpha1 = 'v2alpha1',
}
export enum RuletypesSeasonalityDTO {
hourly = 'hourly',
daily = 'daily',
@@ -12660,9 +12668,9 @@ export interface RuletypesRuleConditionDTO {
seasonality?: RuletypesSeasonalityDTO;
/**
* @type string
* @description The name of the query whose result is evaluated, such as A or F1. Must match a query in compositeQuery. When omitted, F1 is used if present, otherwise the enabled query with the highest name.
* @description The name of the query whose result is evaluated, such as A or F1. Must match a query in compositeQuery.
*/
selectedQueryName?: string;
selectedQueryName: string;
/**
* @type number,null
* @format double
@@ -12675,9 +12683,9 @@ export interface RuletypesRuleConditionDTO {
*/
targetUnit?: string;
/**
* @description The thresholds to evaluate, as a kind and spec. Required when schemaVersion is v2alpha1; derived from op, target and matchType for v1.
* @description The thresholds to evaluate, as a kind and spec.
*/
thresholds?: RuletypesRuleThresholdDataDTO;
thresholds: RuletypesRuleThresholdDataDTO;
}
export interface RuletypesPostableRuleDTO {
@@ -12715,9 +12723,9 @@ export interface RuletypesPostableRuleDTO {
*/
evalWindow?: string;
/**
* @description The evaluation window, as a kind and spec. Required when schemaVersion is v2alpha1; derived from evalWindow and frequency for v1.
* @description The evaluation window, as a kind and spec.
*/
evaluation?: RuletypesEvaluationEnvelopeDTO;
evaluation: RuletypesEvaluationEnvelopeDTO;
/**
* @type string
* @description How often the rule is evaluated, as a Go duration such as 1m. Only read when schemaVersion is v1, defaulting to 1m; v2alpha1 rules set it in evaluation.spec instead.
@@ -12729,23 +12737,24 @@ export interface RuletypesPostableRuleDTO {
*/
labels?: RuletypesPostableRuleDTOLabels;
/**
* @description Grouping, re-notification and routing behaviour. Required when schemaVersion is v2alpha1; derived from the v1 fields otherwise.
* @description Grouping, re-notification and routing behaviour.
*/
notificationSettings?: RuletypesNotificationSettingsDTO;
notificationSettings: RuletypesNotificationSettingsDTO;
/**
* @type array
* @description The displayName of each notification channel to notify, for schemaVersion v1 rules. Ignored for v2alpha1, where each threshold carries its own channels.
*/
preferredChannels?: string[];
/**
* @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 queries and is forced to promql_rule for promql queries.
* @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.
*/
ruleType: RuletypesRuleTypeDTO;
/**
* @enum v2alpha1
* @type string
* @description The rule payload schema: v1 (the default when omitted) uses the flat condition fields, v2alpha1 uses condition.thresholds, evaluation and notificationSettings.
* @description The rule payload schema.
*/
schemaVersion?: string;
schemaVersion: RuletypesPostableRuleDTOSchemaVersion;
/**
* @type string
* @description The URL of the page the rule was created from. Informational; it is not used for evaluation.
@@ -12753,7 +12762,7 @@ export interface RuletypesPostableRuleDTO {
source?: string;
/**
* @type string
* @description The query payload version. Only v5 is accepted and it is filled in when omitted.
* @description The query payload version. Nothing reads it.
*/
version?: string;
}
@@ -12776,6 +12785,12 @@ export type RuletypesRuleDTOAnnotations = { [key: string]: string };
*/
export type RuletypesRuleDTOLabels = { [key: string]: string };
/**
* The rule payload schema.
*/
export enum RuletypesRuleDTOSchemaVersion {
v2alpha1 = 'v2alpha1',
}
export interface RuletypesRuleDTO {
/**
* @type string
@@ -12820,9 +12835,9 @@ export interface RuletypesRuleDTO {
*/
evalWindow?: string;
/**
* @description The evaluation window, as a kind and spec. Required when schemaVersion is v2alpha1; derived from evalWindow and frequency for v1.
* @description The evaluation window, as a kind and spec.
*/
evaluation?: RuletypesEvaluationEnvelopeDTO;
evaluation: RuletypesEvaluationEnvelopeDTO;
/**
* @type string
* @description How often the rule is evaluated, as a Go duration such as 1m. Only read when schemaVersion is v1, defaulting to 1m; v2alpha1 rules set it in evaluation.spec instead.
@@ -12839,23 +12854,24 @@ export interface RuletypesRuleDTO {
*/
labels?: RuletypesRuleDTOLabels;
/**
* @description Grouping, re-notification and routing behaviour. Required when schemaVersion is v2alpha1; derived from the v1 fields otherwise.
* @description Grouping, re-notification and routing behaviour.
*/
notificationSettings?: RuletypesNotificationSettingsDTO;
notificationSettings: RuletypesNotificationSettingsDTO;
/**
* @type array
* @description The displayName of each notification channel to notify, for schemaVersion v1 rules. Ignored for v2alpha1, where each threshold carries its own channels.
*/
preferredChannels?: string[];
/**
* @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 queries and is forced to promql_rule for promql queries.
* @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.
*/
ruleType: RuletypesRuleTypeDTO;
/**
* @enum v2alpha1
* @type string
* @description The rule payload schema: v1 (the default when omitted) uses the flat condition fields, v2alpha1 uses condition.thresholds, evaluation and notificationSettings.
* @description The rule payload schema.
*/
schemaVersion?: string;
schemaVersion: RuletypesRuleDTOSchemaVersion;
/**
* @type string
* @description The URL of the page the rule was created from. Informational; it is not used for evaluation.
@@ -12876,7 +12892,7 @@ export interface RuletypesRuleDTO {
updatedBy?: string;
/**
* @type string
* @description The query payload version. Only v5 is accepted and it is filled in when omitted.
* @description The query payload version. Nothing reads it.
*/
version?: string;
}

View File

@@ -803,7 +803,7 @@ export const useUpdateSpanMapper = <
return useMutation(getUpdateSpanMapperMutationOptions(options));
};
/**
* Tests how span mappers would transform sample spans
* Tests how span mappers would transform sample spans. Groups sent without mappers are read from the store by name.
* @summary Test span mappers against sample spans
*/
export const testSpanMappers = (

View File

@@ -1,8 +1,10 @@
import {
RuletypesAlertStateDTO,
RuletypesAlertTypeDTO,
RuletypesEvaluationRollingDTOKind,
RuletypesPanelTypeDTO,
RuletypesQueryTypeDTO,
RuletypesRuleDTOSchemaVersion,
RuletypesRuleTypeDTO,
} from 'api/generated/services/sigNoz.schemas';
import type {
@@ -38,6 +40,12 @@ const make = (
evalWindow: '5m0s',
frequency: '1m0s',
ruleType: RuletypesRuleTypeDTO.threshold_rule,
schemaVersion: RuletypesRuleDTOSchemaVersion.v2alpha1,
evaluation: {
kind: RuletypesEvaluationRollingDTOKind.rolling,
spec: { evalWindow: '5m0s', frequency: '1m0s' },
},
notificationSettings: { usePolicy: false, renotify: { enabled: false } },
...overrides,
});

View File

@@ -18,6 +18,7 @@ import {
RuletypesMatchTypeDTO,
RuletypesPanelTypeDTO,
RuletypesQueryTypeDTO,
RuletypesRuleDTOSchemaVersion,
RuletypesRuleTypeDTO,
RuletypesSeasonalityDTO,
RuletypesThresholdBasicDTOKind,
@@ -34,7 +35,6 @@ import {
type AlertmanagertypesGettableNotificationChannelDTO,
type AlertmanagertypesListedNotificationChannelDTO,
} from 'api/generated/services/sigNoz.schemas';
import { NEW_ALERT_SCHEMA_VERSION } from 'types/api/alerts/alertTypesV2';
const MINUTE = 60 * 1000;
const HOUR = 60 * MINUTE;
@@ -388,18 +388,18 @@ const buildRule = (index: number, shape: RuleShape): RuletypesRuleDTO => {
},
evalWindow: isAnomaly ? '1h0m0s' : '5m0s',
frequency: '1m0s',
...(isAnomaly && {
evaluation: {
kind: RuletypesEvaluationRollingDTOKind.rolling,
spec: { evalWindow: '1h0m0s', frequency: '1m0s' },
},
}),
evaluation: {
kind: RuletypesEvaluationRollingDTOKind.rolling,
spec: { evalWindow: isAnomaly ? '1h0m0s' : '5m0s', frequency: '1m0s' },
},
createdAt: ago((index + 3) * DAY),
updatedAt: ago((index + 1) * HOUR),
createdBy: 'ada@signoz.io',
updatedBy: 'grace@signoz.io',
schemaVersion:
shape.schema === 'classic' ? undefined : NEW_ALERT_SCHEMA_VERSION,
// classic rows predate schemaVersion, which the spec now requires
schemaVersion: (shape.schema === 'classic'
? undefined
: RuletypesRuleDTOSchemaVersion.v2alpha1) as RuletypesRuleDTOSchemaVersion,
version: 'v5',
source: 'http://localhost/alerts',
preferredChannels: ['ops-slack'],

View File

@@ -74,7 +74,9 @@
"meter-metrics",
"logs-field",
"traces-field",
"metrics-field"
"metrics-field",
"span-mapper-group",
"span-mapper"
],
"type": "string"
},

View File

@@ -221,16 +221,15 @@ func postableRuleExamples() []handler.OpenAPIExample {
},
{
Name: "metric_anomaly",
Summary: "Metric anomaly rule (v1 only)",
Description: "Anomaly rules are not yet supported under schemaVersion v2alpha1, so this example uses the v1 shape. Wraps a builder query in the `anomaly` function with daily seasonality SigNoz compares each point against the forecast for that time of day. Fires when the anomaly score stays below the threshold for the entire window; `requireMinPoints` guards against noisy intervals.",
Summary: "Metric anomaly rule",
Description: "Wraps a builder query in the `anomaly` function with daily seasonality, so SigNoz compares each point against the forecast for that time of day. The threshold is compared against the signed anomaly score, so `below` with a target of -2 fires when an abrupt drop holds for the entire window; `requireMinPoints` guards against noisy intervals.",
Value: map[string]any{
"alert": "Anomalous drop in ingested spans",
"alertType": "METRIC_BASED_ALERT",
"description": "Detect an abrupt drop in span ingestion using a z-score anomaly function",
"ruleType": "anomaly_rule",
"version": "v5",
"evalWindow": "24h",
"frequency": "3h",
"alert": "Anomalous drop in ingested spans",
"alertType": "METRIC_BASED_ALERT",
"description": "Detect an abrupt drop in span ingestion using a z-score anomaly function",
"ruleType": "anomaly_rule",
"version": "v5",
"schemaVersion": "v2alpha1",
"condition": map[string]any{
"compositeQuery": map[string]any{
"queryType": "builder",
@@ -256,17 +255,29 @@ func postableRuleExamples() []handler.OpenAPIExample {
},
},
},
"op": "below",
"matchType": "all_the_times",
"target": 2,
"algorithm": "standard",
"seasonality": "daily",
"selectedQueryName": "A",
"requireMinPoints": true,
"requiredNumPoints": 3,
"thresholds": map[string]any{
"kind": "basic",
"spec": []any{
map[string]any{
"name": "warning",
"op": "below",
"matchType": "all_the_times",
"target": -2,
"channels": []any{"slack-ingestion"},
},
},
},
},
"labels": map[string]any{"severity": "warning"},
"preferredChannels": []any{"slack-ingestion"},
"evaluation": rolling("24h", "3h"),
"notificationSettings": map[string]any{
"renotify": renotify("4h", "firing"),
},
"labels": map[string]any{"severity": "warning"},
"annotations": map[string]any{
"description": "Ingestion rate for tenant {{$tenant_id}} is anomalously low (z-score {{$value}}).",
"summary": "Span ingestion anomaly",

View File

@@ -4,14 +4,15 @@ import (
"net/http"
"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/spantypes"
"github.com/gorilla/mux"
)
func (provider *provider) addSpanMapperRoutes(router *mux.Router) error {
if err := router.Handle("/api/v1/span_mapper_groups", handler.New(
provider.authzMiddleware.ViewAccess(provider.spanMapperHandler.ListGroups),
provider.authzMiddleware.CheckResources(provider.spanMapperHandler.ListGroups, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName, authtypes.SigNozViewerRoleName),
handler.OpenAPIDef{
ID: "ListSpanMapperGroups",
Tags: []string{"spanmapper"},
@@ -25,14 +26,20 @@ func (provider *provider) addSpanMapperRoutes(router *mux.Router) error {
SuccessStatusCode: http.StatusOK,
ErrorStatusCodes: []int{http.StatusBadRequest},
Deprecated: false,
SecuritySchemes: newSecuritySchemes(types.RoleViewer),
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceSpanMapperGroup.Scope(coretypes.VerbList)}),
},
handler.WithResourceDefs(handler.BasicResourceDef{
Resource: coretypes.ResourceMetaResourceSpanMapperGroup,
Verb: coretypes.VerbList,
Category: coretypes.ActionCategoryDataAccess,
Selector: coretypes.WildcardSelector,
}),
)).Methods(http.MethodGet).GetError(); err != nil {
return err
}
if err := router.Handle("/api/v1/span_mapper_groups", handler.New(
provider.authzMiddleware.AdminAccess(provider.spanMapperHandler.CreateGroup),
provider.authzMiddleware.CheckResources(provider.spanMapperHandler.CreateGroup, authtypes.SigNozAdminRoleName),
handler.OpenAPIDef{
ID: "CreateSpanMapperGroup",
Tags: []string{"spanmapper"},
@@ -45,19 +52,26 @@ func (provider *provider) addSpanMapperRoutes(router *mux.Router) error {
SuccessStatusCode: http.StatusCreated,
ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusConflict},
Deprecated: false,
SecuritySchemes: newSecuritySchemes(types.RoleAdmin),
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceSpanMapperGroup.Scope(coretypes.VerbCreate)}),
},
handler.WithResourceDefs(handler.BasicResourceDef{
Resource: coretypes.ResourceMetaResourceSpanMapperGroup,
Verb: coretypes.VerbCreate,
Category: coretypes.ActionCategoryConfigurationChange,
ID: coretypes.ResponseJSONPath("data.id"),
Selector: coretypes.WildcardSelector,
}),
)).Methods(http.MethodPost).GetError(); err != nil {
return err
}
if err := router.Handle("/api/v1/span_mapper_groups/test", handler.New(
provider.authzMiddleware.ViewAccess(provider.spanMapperHandler.TestMappers),
provider.authzMiddleware.CheckResources(provider.spanMapperHandler.TestMappers, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName, authtypes.SigNozViewerRoleName),
handler.OpenAPIDef{
ID: "TestSpanMappers",
Tags: []string{"spanmapper"},
Summary: "Test span mappers against sample spans",
Description: "Tests how span mappers would transform sample spans",
Description: "Tests how span mappers would transform sample spans. Groups sent without mappers are read from the store by name.",
Request: new(spantypes.PostableSpanMapperTest),
RequestContentType: "application/json",
Response: new(spantypes.GettableSpanMapperTest),
@@ -65,14 +79,20 @@ func (provider *provider) addSpanMapperRoutes(router *mux.Router) error {
SuccessStatusCode: http.StatusOK,
ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},
Deprecated: false,
SecuritySchemes: newSecuritySchemes(types.RoleViewer),
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceSpanMapperGroup.Scope(coretypes.VerbRead)}),
},
handler.WithResourceDefs(handler.BasicResourceDef{
Resource: coretypes.ResourceMetaResourceSpanMapperGroup,
Verb: coretypes.VerbRead,
Category: coretypes.ActionCategoryDataAccess,
Selector: coretypes.WildcardSelector,
}),
)).Methods(http.MethodPost).GetError(); err != nil {
return err
}
if err := router.Handle("/api/v1/span_mapper_groups/{groupId}", handler.New(
provider.authzMiddleware.AdminAccess(provider.spanMapperHandler.UpdateGroup),
provider.authzMiddleware.CheckResources(provider.spanMapperHandler.UpdateGroup, authtypes.SigNozAdminRoleName),
handler.OpenAPIDef{
ID: "UpdateSpanMapperGroup",
Tags: []string{"spanmapper"},
@@ -83,14 +103,21 @@ func (provider *provider) addSpanMapperRoutes(router *mux.Router) error {
SuccessStatusCode: http.StatusNoContent,
ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},
Deprecated: false,
SecuritySchemes: newSecuritySchemes(types.RoleAdmin),
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceSpanMapperGroup.Scope(coretypes.VerbUpdate)}),
},
handler.WithResourceDefs(handler.BasicResourceDef{
Resource: coretypes.ResourceMetaResourceSpanMapperGroup,
Verb: coretypes.VerbUpdate,
Category: coretypes.ActionCategoryConfigurationChange,
ID: coretypes.PathParam("groupId"),
Selector: coretypes.IDSelector,
}),
)).Methods(http.MethodPatch).GetError(); err != nil {
return err
}
if err := router.Handle("/api/v1/span_mapper_groups/{groupId}", handler.New(
provider.authzMiddleware.AdminAccess(provider.spanMapperHandler.DeleteGroup),
provider.authzMiddleware.CheckResources(provider.spanMapperHandler.DeleteGroup, authtypes.SigNozAdminRoleName),
handler.OpenAPIDef{
ID: "DeleteSpanMapperGroup",
Tags: []string{"spanmapper"},
@@ -103,14 +130,21 @@ func (provider *provider) addSpanMapperRoutes(router *mux.Router) error {
SuccessStatusCode: http.StatusNoContent,
ErrorStatusCodes: []int{http.StatusNotFound},
Deprecated: false,
SecuritySchemes: newSecuritySchemes(types.RoleAdmin),
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceSpanMapperGroup.Scope(coretypes.VerbDelete)}),
},
handler.WithResourceDefs(handler.BasicResourceDef{
Resource: coretypes.ResourceMetaResourceSpanMapperGroup,
Verb: coretypes.VerbDelete,
Category: coretypes.ActionCategoryConfigurationChange,
ID: coretypes.PathParam("groupId"),
Selector: coretypes.IDSelector,
}),
)).Methods(http.MethodDelete).GetError(); err != nil {
return err
}
if err := router.Handle("/api/v1/span_mapper_groups/{groupId}/span_mappers", handler.New(
provider.authzMiddleware.ViewAccess(provider.spanMapperHandler.ListMappers),
provider.authzMiddleware.CheckResources(provider.spanMapperHandler.ListMappers, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName, authtypes.SigNozViewerRoleName),
handler.OpenAPIDef{
ID: "ListSpanMappers",
Tags: []string{"spanmapper"},
@@ -123,14 +157,21 @@ func (provider *provider) addSpanMapperRoutes(router *mux.Router) error {
SuccessStatusCode: http.StatusOK,
ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},
Deprecated: false,
SecuritySchemes: newSecuritySchemes(types.RoleViewer),
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceSpanMapperGroup.Scope(coretypes.VerbRead)}),
},
handler.WithResourceDefs(handler.BasicResourceDef{
Resource: coretypes.ResourceMetaResourceSpanMapperGroup,
Verb: coretypes.VerbRead,
Category: coretypes.ActionCategoryDataAccess,
ID: coretypes.PathParam("groupId"),
Selector: coretypes.IDSelector,
}),
)).Methods(http.MethodGet).GetError(); err != nil {
return err
}
if err := router.Handle("/api/v1/span_mapper_groups/{groupId}/span_mappers", handler.New(
provider.authzMiddleware.AdminAccess(provider.spanMapperHandler.CreateMapper),
provider.authzMiddleware.CheckResources(provider.spanMapperHandler.CreateMapper, authtypes.SigNozAdminRoleName),
handler.OpenAPIDef{
ID: "CreateSpanMapper",
Tags: []string{"spanmapper"},
@@ -143,14 +184,32 @@ func (provider *provider) addSpanMapperRoutes(router *mux.Router) error {
SuccessStatusCode: http.StatusCreated,
ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound, http.StatusConflict},
Deprecated: false,
SecuritySchemes: newSecuritySchemes(types.RoleAdmin),
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceSpanMapper.Scope(coretypes.VerbCreate), coretypes.ResourceMetaResourceSpanMapperGroup.Scope(coretypes.VerbAttach)}),
},
handler.WithResourceDefs(
handler.BasicResourceDef{
Resource: coretypes.ResourceMetaResourceSpanMapper,
Verb: coretypes.VerbCreate,
Category: coretypes.ActionCategoryConfigurationChange,
ID: coretypes.ResponseJSONPath("data.id"),
Selector: coretypes.WildcardSelector,
},
handler.AttachDetachParentChildResourceDef{
Verb: coretypes.VerbAttach,
Category: coretypes.ActionCategoryConfigurationChange,
ParentResource: coretypes.ResourceMetaResourceSpanMapperGroup,
ParentID: coretypes.PathParam("groupId"),
ParentSelector: coretypes.IDSelector,
ChildResource: coretypes.ResourceMetaResourceSpanMapper,
ChildIDs: coretypes.OneID(coretypes.ResponseJSONPath("data.id")),
},
),
)).Methods(http.MethodPost).GetError(); err != nil {
return err
}
if err := router.Handle("/api/v1/span_mapper_groups/{groupId}/span_mappers/{mapperId}", handler.New(
provider.authzMiddleware.AdminAccess(provider.spanMapperHandler.UpdateMapper),
provider.authzMiddleware.CheckResources(provider.spanMapperHandler.UpdateMapper, authtypes.SigNozAdminRoleName),
handler.OpenAPIDef{
ID: "UpdateSpanMapper",
Tags: []string{"spanmapper"},
@@ -161,14 +220,21 @@ func (provider *provider) addSpanMapperRoutes(router *mux.Router) error {
SuccessStatusCode: http.StatusNoContent,
ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},
Deprecated: false,
SecuritySchemes: newSecuritySchemes(types.RoleAdmin),
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceSpanMapper.Scope(coretypes.VerbUpdate)}),
},
handler.WithResourceDefs(handler.BasicResourceDef{
Resource: coretypes.ResourceMetaResourceSpanMapper,
Verb: coretypes.VerbUpdate,
Category: coretypes.ActionCategoryConfigurationChange,
ID: coretypes.PathParam("mapperId"),
Selector: coretypes.IDSelector,
}),
)).Methods(http.MethodPatch).GetError(); err != nil {
return err
}
if err := router.Handle("/api/v1/span_mapper_groups/{groupId}/span_mappers/{mapperId}", handler.New(
provider.authzMiddleware.AdminAccess(provider.spanMapperHandler.DeleteMapper),
provider.authzMiddleware.CheckResources(provider.spanMapperHandler.DeleteMapper, authtypes.SigNozAdminRoleName),
handler.OpenAPIDef{
ID: "DeleteSpanMapper",
Tags: []string{"spanmapper"},
@@ -181,8 +247,26 @@ func (provider *provider) addSpanMapperRoutes(router *mux.Router) error {
SuccessStatusCode: http.StatusNoContent,
ErrorStatusCodes: []int{http.StatusNotFound},
Deprecated: false,
SecuritySchemes: newSecuritySchemes(types.RoleAdmin),
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceSpanMapper.Scope(coretypes.VerbDelete), coretypes.ResourceMetaResourceSpanMapperGroup.Scope(coretypes.VerbDetach)}),
},
handler.WithResourceDefs(
handler.BasicResourceDef{
Resource: coretypes.ResourceMetaResourceSpanMapper,
Verb: coretypes.VerbDelete,
Category: coretypes.ActionCategoryConfigurationChange,
ID: coretypes.PathParam("mapperId"),
Selector: coretypes.IDSelector,
},
handler.AttachDetachParentChildResourceDef{
Verb: coretypes.VerbDetach,
Category: coretypes.ActionCategoryConfigurationChange,
ParentResource: coretypes.ResourceMetaResourceSpanMapperGroup,
ParentID: coretypes.PathParam("groupId"),
ParentSelector: coretypes.IDSelector,
ChildResource: coretypes.ResourceMetaResourceSpanMapper,
ChildIDs: coretypes.OneID(coretypes.PathParam("mapperId")),
},
),
)).Methods(http.MethodDelete).GetError(); err != nil {
return err
}

View File

@@ -266,6 +266,7 @@ func NewSQLMigrationProviderFactories(
sqlmigration.NewAddMetricsFieldTuplesFactory(sqlstore),
sqlmigration.NewAddGCPConnectionMethodFactory(),
sqlmigration.NewDeleteOrphanSARolesFactory(),
sqlmigration.NewAddSpanMapperTuplesFactory(sqlstore),
)
}

View File

@@ -0,0 +1,168 @@
package sqlmigration
import (
"context"
"database/sql"
"encoding/json"
"time"
"github.com/SigNoz/signoz/pkg/factory"
"github.com/SigNoz/signoz/pkg/sqlstore"
"github.com/SigNoz/signoz/pkg/types/authtypes"
"github.com/SigNoz/signoz/pkg/types/coretypes"
"github.com/oklog/ulid/v2"
"github.com/uptrace/bun"
"github.com/uptrace/bun/dialect"
"github.com/uptrace/bun/migrate"
)
type addSpanMapperTuples struct {
sqlstore sqlstore.SQLStore
}
func NewAddSpanMapperTuplesFactory(sqlstore sqlstore.SQLStore) factory.ProviderFactory[SQLMigration, Config] {
return factory.NewProviderFactory(factory.MustNewName("add_span_mapper_tuples"), func(ctx context.Context, ps factory.ProviderSettings, c Config) (SQLMigration, error) {
return &addSpanMapperTuples{sqlstore: sqlstore}, nil
})
}
func (migration *addSpanMapperTuples) Register(migrations *migrate.Migrations) error {
return migrations.Register(migration.Up, migration.Down)
}
func (migration *addSpanMapperTuples) 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{
{authtypes.SigNozAdminRoleName, "metaresource", "span-mapper-group", "read"},
{authtypes.SigNozAdminRoleName, "metaresource", "span-mapper-group", "update"},
{authtypes.SigNozAdminRoleName, "metaresource", "span-mapper-group", "delete"},
{authtypes.SigNozAdminRoleName, "metaresource", "span-mapper-group", "create"},
{authtypes.SigNozAdminRoleName, "metaresource", "span-mapper-group", "list"},
{authtypes.SigNozAdminRoleName, "metaresource", "span-mapper-group", "attach"},
{authtypes.SigNozAdminRoleName, "metaresource", "span-mapper-group", "detach"},
{authtypes.SigNozAdminRoleName, "metaresource", "span-mapper", "update"},
{authtypes.SigNozAdminRoleName, "metaresource", "span-mapper", "delete"},
{authtypes.SigNozAdminRoleName, "metaresource", "span-mapper", "create"},
{authtypes.SigNozEditorRoleName, "metaresource", "span-mapper-group", "read"},
{authtypes.SigNozEditorRoleName, "metaresource", "span-mapper-group", "list"},
{authtypes.SigNozViewerRoleName, "metaresource", "span-mapper-group", "read"},
{authtypes.SigNozViewerRoleName, "metaresource", "span-mapper-group", "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
}
}
}
}
managedRoleGroups := make(map[string]string, len(coretypes.ManagedRoleToTransactions))
for roleName, transactions := range coretypes.ManagedRoleToTransactions {
data, err := json.Marshal(authtypes.NewTransactionGroupsFromTransactions(transactions))
if err != nil {
return err
}
managedRoleGroups[roleName] = string(data)
}
for _, orgID := range orgIDs {
for roleName, data := range managedRoleGroups {
if _, err := tx.NewUpdate().
Model(new(roles)).
Set("transaction_groups = ?", data).
Where("org_id = ?", orgID).
Where("type = ?", authtypes.RoleTypeManaged.StringValue()).
Where("name = ?", roleName).
Exec(ctx); err != nil {
return err
}
}
}
return tx.Commit()
}
func (migration *addSpanMapperTuples) Down(context.Context, *bun.DB) error {
return nil
}

View File

@@ -80,6 +80,8 @@ func (name Kind) Enum() []any {
KindLogsField,
KindTracesField,
KindMetricsField,
KindSpanMapperGroup,
KindSpanMapper,
}
}

View File

@@ -40,6 +40,8 @@ var Kinds = []Kind{
KindLogsField,
KindTracesField,
KindMetricsField,
KindSpanMapperGroup,
KindSpanMapper,
}
var (
@@ -82,4 +84,6 @@ var (
KindLogsField = MustNewKind("logs-field")
KindTracesField = MustNewKind("traces-field")
KindMetricsField = MustNewKind("metrics-field")
KindSpanMapperGroup = MustNewKind("span-mapper-group")
KindSpanMapper = MustNewKind("span-mapper")
)

View File

@@ -218,6 +218,17 @@ var ManagedRoleToTransactions = map[string][]Transaction{
{Verb: VerbRead, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindMetricsField}, WildCardSelectorString)},
{Verb: VerbUpdate, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindMetricsField}, WildCardSelectorString)},
{Verb: VerbList, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindMetricsField}, WildCardSelectorString)},
// span-mapper-group and span-mapper — admin manages, viewer reads
{Verb: VerbRead, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindSpanMapperGroup}, WildCardSelectorString)},
{Verb: VerbUpdate, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindSpanMapperGroup}, WildCardSelectorString)},
{Verb: VerbDelete, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindSpanMapperGroup}, WildCardSelectorString)},
{Verb: VerbCreate, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindSpanMapperGroup}, WildCardSelectorString)},
{Verb: VerbList, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindSpanMapperGroup}, WildCardSelectorString)},
{Verb: VerbAttach, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindSpanMapperGroup}, WildCardSelectorString)},
{Verb: VerbDetach, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindSpanMapperGroup}, WildCardSelectorString)},
{Verb: VerbUpdate, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindSpanMapper}, WildCardSelectorString)},
{Verb: VerbDelete, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindSpanMapper}, WildCardSelectorString)},
{Verb: VerbCreate, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindSpanMapper}, WildCardSelectorString)},
},
SigNozEditorRoleName: {
// cloud-integration — editor can read accounts
@@ -317,6 +328,9 @@ var ManagedRoleToTransactions = map[string][]Transaction{
{Verb: VerbRead, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindMetricsField}, WildCardSelectorString)},
{Verb: VerbUpdate, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindMetricsField}, WildCardSelectorString)},
{Verb: VerbList, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindMetricsField}, WildCardSelectorString)},
// span-mapper-group — read only (admin manages)
{Verb: VerbRead, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindSpanMapperGroup}, WildCardSelectorString)},
{Verb: VerbList, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindSpanMapperGroup}, WildCardSelectorString)},
},
SigNozViewerRoleName: {
// cloud-integration — viewer can read accounts
@@ -381,6 +395,9 @@ var ManagedRoleToTransactions = map[string][]Transaction{
// metrics-field — viewer reads
{Verb: VerbRead, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindMetricsField}, WildCardSelectorString)},
{Verb: VerbList, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindMetricsField}, WildCardSelectorString)},
// span-mapper-group — read only
{Verb: VerbRead, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindSpanMapperGroup}, WildCardSelectorString)},
{Verb: VerbList, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindSpanMapperGroup}, WildCardSelectorString)},
},
SigNozAnonymousRoleName: {
// public-dashboard — anonymous read

View File

@@ -40,6 +40,8 @@ var Resources = []Resource{
ResourceMetaResourceLogsField,
ResourceMetaResourceTracesField,
ResourceMetaResourceMetricsField,
ResourceMetaResourceSpanMapperGroup,
ResourceMetaResourceSpanMapper,
}
var (
@@ -82,4 +84,6 @@ var (
ResourceMetaResourceLogsField = NewResourceMetaResource(KindLogsField)
ResourceMetaResourceTracesField = NewResourceMetaResource(KindTracesField)
ResourceMetaResourceMetricsField = NewResourceMetaResource(KindMetricsField, VerbList, VerbRead, VerbUpdate)
ResourceMetaResourceSpanMapperGroup = NewResourceMetaResource(KindSpanMapperGroup)
ResourceMetaResourceSpanMapper = NewResourceMetaResource(KindSpanMapper, VerbCreate, VerbUpdate, VerbDelete)
)

View File

@@ -117,10 +117,10 @@ type RuleCondition struct {
TargetUnit string `json:"targetUnit,omitempty" description:"schemaVersion v1 only: the unit of target, such as percent or ms. Converted to compositeQuery.unit before comparison when the two differ."`
Algorithm string `json:"algorithm,omitempty" description:"anomaly_rule only: the anomaly detection algorithm. The supported value is standard."`
Seasonality Seasonality `json:"seasonality,omitzero" description:"anomaly_rule only: the seasonal period the history is compared against, hourly, daily or weekly."`
SelectedQuery string `json:"selectedQueryName,omitempty" description:"The name of the query whose result is evaluated, such as A or F1. Must match a query in compositeQuery. When omitted, F1 is used if present, otherwise the enabled query with the highest name."`
SelectedQuery string `json:"selectedQueryName,omitempty" required:"true" description:"The name of the query whose result is evaluated, such as A or F1. Must match a query in compositeQuery."`
RequireMinPoints bool `json:"requireMinPoints,omitempty" description:"Whether a series is skipped until it has at least requiredNumPoints points in the window. Defaults to false."`
RequiredNumPoints int `json:"requiredNumPoints,omitempty" description:"The minimum number of points a series needs before it is evaluated. Must be greater than 0 when requireMinPoints is true."`
Thresholds *RuleThresholdData `json:"thresholds,omitempty" description:"The thresholds to evaluate, as a kind and spec. Required when schemaVersion is v2alpha1; derived from op, target and matchType for v1."`
Thresholds *RuleThresholdData `json:"thresholds,omitempty" required:"true" description:"The thresholds to evaluate, as a kind and spec."`
}
func (rc *RuleCondition) SelectedQueryName() string {

View File

@@ -9,6 +9,7 @@ import (
"unicode/utf8"
"github.com/prometheus/alertmanager/config"
"github.com/swaggest/jsonschema-go"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/types"
@@ -63,7 +64,7 @@ type PostableRule struct {
AlertName valuer.DisplayName `json:"alert" required:"true" description:"The display name of the alert rule."`
AlertType AlertType `json:"alertType" required:"true" description:"The signal the rule evaluates: METRIC_BASED_ALERT, TRACES_BASED_ALERT, LOGS_BASED_ALERT, EXCEPTIONS_BASED_ALERT or AI_TRACES_BASED_ALERT."`
Description string `json:"description,omitempty" description:"A human readable description of what the rule monitors."`
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 queries and is forced to promql_rule for promql queries."`
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."`
EvalWindow valuer.TextDuration `json:"evalWindow,omitzero" description:"The lookback window as a Go duration such as 5m. Only read when schemaVersion is v1, defaulting to 5m; v2alpha1 rules set it in evaluation.spec instead."`
Frequency valuer.TextDuration `json:"frequency,omitzero" description:"How often the rule is evaluated, as a Go duration such as 1m. Only read when schemaVersion is v1, defaulting to 1m; v2alpha1 rules set it in evaluation.spec instead."`
@@ -77,12 +78,12 @@ type PostableRule struct {
PreferredChannels []string `json:"preferredChannels,omitempty" description:"The displayName of each notification channel to notify, for schemaVersion v1 rules. Ignored for v2alpha1, where each threshold carries its own channels."`
Version string `json:"version" description:"The query payload version. Only v5 is accepted and it is filled in when omitted."`
Version string `json:"version" description:"The query payload version. Nothing reads it."`
Evaluation *EvaluationEnvelope `json:"evaluation,omitempty" description:"The evaluation window, as a kind and spec. Required when schemaVersion is v2alpha1; derived from evalWindow and frequency for v1."`
SchemaVersion string `json:"schemaVersion,omitempty" description:"The rule payload schema: v1 (the default when omitted) uses the flat condition fields, v2alpha1 uses condition.thresholds, evaluation and notificationSettings."`
Evaluation *EvaluationEnvelope `json:"evaluation,omitempty" required:"true" description:"The evaluation window, as a kind and spec."`
SchemaVersion string `json:"schemaVersion,omitempty" required:"true" enum:"v2alpha1" description:"The rule payload schema."`
NotificationSettings *NotificationSettings `json:"notificationSettings,omitempty" description:"Grouping, re-notification and routing behaviour. Required when schemaVersion is v2alpha1; derived from the v1 fields otherwise."`
NotificationSettings *NotificationSettings `json:"notificationSettings,omitempty" required:"true" description:"Grouping, re-notification and routing behaviour."`
}
type NotificationSettings struct {
@@ -335,6 +336,19 @@ func (r *PostableRule) UnmarshalJSON(bytes []byte) error {
return r.validate()
}
var _ jsonschema.Preparer = PostableRule{}
// PrepareJSONSchema marks version and source deprecated: nothing reads them,
// they stay only so existing clients keep a stable schema.
func (PostableRule) PrepareJSONSchema(schema *jsonschema.Schema) error {
for _, name := range []string{"version", "source"} {
if property, ok := schema.Properties[name]; ok && property.TypeObject != nil {
property.TypeObject.WithDeprecated(true)
}
}
return nil
}
func isValidLabelName(ln string) bool {
if len(ln) == 0 {
return false

View File

@@ -297,6 +297,28 @@
"list"
]
},
{
"type": "metaresource",
"kind": "span-mapper-group",
"verbs": [
"read",
"update",
"delete",
"create",
"list",
"attach",
"detach"
]
},
{
"type": "metaresource",
"kind": "span-mapper",
"verbs": [
"update",
"delete",
"create"
]
},
{
"type": "metaresource",
"kind": "ttl-setting",
@@ -528,6 +550,14 @@
"list"
]
},
{
"type": "metaresource",
"kind": "span-mapper-group",
"verbs": [
"read",
"list"
]
},
{
"type": "metaresource",
"kind": "ttl-setting",
@@ -707,6 +737,14 @@
"list"
]
},
{
"type": "metaresource",
"kind": "span-mapper-group",
"verbs": [
"read",
"list"
]
},
{
"type": "metaresource",
"kind": "ttl-setting",

View File

@@ -0,0 +1,355 @@
from collections.abc import Callable
from http import HTTPStatus
import pytest
import requests
from wiremock.resources.mappings import Mapping
from fixtures.auth import (
USER_ADMIN_EMAIL,
USER_ADMIN_PASSWORD,
add_license,
change_user_role,
create_active_user,
find_user_by_email,
)
from fixtures.role import find_role_by_name, transaction_group
from fixtures.types import Operation, SigNoz, TestContainerDocker
GROUPS_PATH = "/api/v1/span_mapper_groups"
_EDITOR_EMAIL = "editor+spanmapperauthz@integration.test"
_VIEWER_EMAIL = "viewer+spanmapperauthz@integration.test"
_ACTOR_ROLE_NAME = "span-mapper-fga-actor"
_ACTOR_EMAIL = "customrole+spanmapperauthz@integration.test"
_PASSWORD = "password123Z$"
# Instance verbs are granted on _TARGET_A and its mapper only; _TARGET_B must stay forbidden.
_TARGET_A = "span-mapper-authz-target-a"
_TARGET_B = "span-mapper-authz-target-b"
_MAPPER = {
"name": "span_mapper_authz.target",
"fieldContext": "attribute",
"config": {"sources": [{"key": "authz.source", "context": "attribute", "operation": "copy", "priority": 1, "enabled": True}]},
"enabled": True,
}
_SIMULATE = {
"spans": [{"attributes": {"authz.source": "x"}, "resource": {}}],
"groups": [{"name": _TARGET_A, "condition": {"attributes": [{"value": "authz.a", "enabled": True}], "resource": []}, "enabled": True}],
}
def test_setup_users_and_targets(
signoz: SigNoz,
create_user_admin: Operation, # pylint: disable=unused-argument
get_token: Callable[[str, str], str],
):
admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
headers = {"Authorization": f"Bearer {admin_token}"}
# A --reuse stack may already hold part of this state; create only what is missing.
response = requests.get(signoz.self.host_configs["8080"].get("/api/v2/users"), headers=headers, timeout=5)
assert response.status_code == HTTPStatus.OK, response.text
existing_emails = {user["email"] for user in response.json()["data"]}
for email, role in ((_EDITOR_EMAIL, "signoz-editor"), (_VIEWER_EMAIL, "signoz-viewer")):
if email not in existing_emails:
create_active_user(signoz, admin_token, email=email, role=role, password=_PASSWORD)
response = requests.get(signoz.self.host_configs["8080"].get(GROUPS_PATH), headers=headers, timeout=5)
assert response.status_code == HTTPStatus.OK, response.text
existing_groups = {group["name"] for group in response.json()["data"]["items"]}
for name, substring in ((_TARGET_A, "authz.a"), (_TARGET_B, "authz.b")):
if name in existing_groups:
continue
response = requests.post(
signoz.self.host_configs["8080"].get(GROUPS_PATH),
json={"name": name, "condition": {"attributes": [{"value": substring, "enabled": True}], "resource": []}, "enabled": True},
headers=headers,
timeout=5,
)
assert response.status_code == HTTPStatus.CREATED, response.text
response = requests.get(signoz.self.host_configs["8080"].get(GROUPS_PATH), headers=headers, timeout=5)
assert response.status_code == HTTPStatus.OK, response.text
ids = {group["name"]: group["id"] for group in response.json()["data"]["items"]}
for name in (_TARGET_A, _TARGET_B):
response = requests.get(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{ids[name]}/span_mappers"), headers=headers, timeout=5)
assert response.status_code == HTTPStatus.OK, response.text
if any(mapper["name"] == _MAPPER["name"] for mapper in response.json()["data"]["items"]):
continue
response = requests.post(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{ids[name]}/span_mappers"), json=_MAPPER, headers=headers, timeout=5)
assert response.status_code == HTTPStatus.CREATED, response.text
def test_mapper_is_only_reachable_through_its_own_group(
signoz: SigNoz,
create_user_admin: Operation, # pylint: disable=unused-argument
get_token: Callable[[str, str], str],
):
# The authz check on the mapper routes trusts the group id in the path, so the
# store must refuse a mapper addressed through another group.
headers = {"Authorization": f"Bearer {get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)}"}
response = requests.get(signoz.self.host_configs["8080"].get(GROUPS_PATH), headers=headers, timeout=5)
assert response.status_code == HTTPStatus.OK, response.text
ids = {group["name"]: group["id"] for group in response.json()["data"]["items"]}
response = requests.get(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{ids[_TARGET_B]}/span_mappers"), headers=headers, timeout=5)
assert response.status_code == HTTPStatus.OK, response.text
mapper_b = response.json()["data"]["items"][0]["id"]
response = requests.patch(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{ids[_TARGET_A]}/span_mappers/{mapper_b}"), json={"enabled": True}, headers=headers, timeout=5)
assert response.status_code == HTTPStatus.NOT_FOUND, f"update B's mapper via A: expected 404, got {response.status_code}: {response.text}"
response = requests.delete(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{ids[_TARGET_A]}/span_mappers/{mapper_b}"), headers=headers, timeout=5)
assert response.status_code == HTTPStatus.NOT_FOUND, f"delete B's mapper via A: expected 404, got {response.status_code}: {response.text}"
response = requests.get(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{ids[_TARGET_B]}/span_mappers"), headers=headers, timeout=5)
assert response.status_code == HTTPStatus.OK, response.text
assert {mapper["id"] for mapper in response.json()["data"]["items"]} == {mapper_b}
@pytest.mark.parametrize("email", [_VIEWER_EMAIL, _EDITOR_EMAIL], ids=["viewer", "editor"])
def test_managed_readers_allowed_on_reads_and_simulate(
signoz: SigNoz,
create_user_admin: Operation, # pylint: disable=unused-argument
get_token: Callable[[str, str], str],
email: str,
):
headers = {"Authorization": f"Bearer {get_token(email, _PASSWORD)}"}
response = requests.get(signoz.self.host_configs["8080"].get(GROUPS_PATH), headers=headers, timeout=5)
assert response.status_code == HTTPStatus.OK, response.text
target_a = {group["name"]: group["id"] for group in response.json()["data"]["items"]}[_TARGET_A]
response = requests.get(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{target_a}/span_mappers"), headers=headers, timeout=5)
assert response.status_code == HTTPStatus.OK, response.text
assert {mapper["name"] for mapper in response.json()["data"]["items"]} == {_MAPPER["name"]}
response = requests.post(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/test"), json=_SIMULATE, headers=headers, timeout=5)
assert response.status_code == HTTPStatus.OK, response.text
@pytest.mark.parametrize("email", [_VIEWER_EMAIL, _EDITOR_EMAIL], ids=["viewer", "editor"])
def test_managed_readers_forbidden_on_mutations(
signoz: SigNoz,
create_user_admin: Operation, # pylint: disable=unused-argument
get_token: Callable[[str, str], str],
email: str,
):
headers = {"Authorization": f"Bearer {get_token(email, _PASSWORD)}"}
response = requests.get(signoz.self.host_configs["8080"].get(GROUPS_PATH), headers=headers, timeout=5)
assert response.status_code == HTTPStatus.OK, response.text
target_a = {group["name"]: group["id"] for group in response.json()["data"]["items"]}[_TARGET_A]
response = requests.get(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{target_a}/span_mappers"), headers=headers, timeout=5)
assert response.status_code == HTTPStatus.OK, response.text
mapper_id = response.json()["data"]["items"][0]["id"]
for method, path, body in (
("POST", GROUPS_PATH, {"name": "span-mapper-authz-denied", "condition": {"attributes": [{"value": "authz.denied", "enabled": True}], "resource": []}, "enabled": True}),
("PATCH", f"{GROUPS_PATH}/{target_a}", {"enabled": True}),
("DELETE", f"{GROUPS_PATH}/{target_a}", None),
("POST", f"{GROUPS_PATH}/{target_a}/span_mappers", {**_MAPPER, "name": "span_mapper_authz.denied"}),
("PATCH", f"{GROUPS_PATH}/{target_a}/span_mappers/{mapper_id}", {"enabled": True}),
("DELETE", f"{GROUPS_PATH}/{target_a}/span_mappers/{mapper_id}", None),
):
response = requests.request(method, signoz.self.host_configs["8080"].get(path), json=body, headers=headers, timeout=5)
assert response.status_code == HTTPStatus.FORBIDDEN, f"{method} {path}: expected 403, got {response.status_code}: {response.text}"
def test_apply_license(
signoz: SigNoz,
create_user_admin: Operation, # pylint: disable=unused-argument
make_http_mocks: Callable[[TestContainerDocker, list[Mapping]], None],
get_token: Callable[[str, str], str],
) -> None:
add_license(signoz, make_http_mocks, get_token)
def test_setup_scoped_actor(
signoz: SigNoz,
create_user_admin: Operation, # pylint: disable=unused-argument
get_token: Callable[[str, str], str],
create_role: Callable[..., str],
):
admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
headers = {"Authorization": f"Bearer {admin_token}"}
response = requests.get(signoz.self.host_configs["8080"].get(GROUPS_PATH), headers=headers, timeout=5)
assert response.status_code == HTTPStatus.OK, response.text
target_a = {group["name"]: group["id"] for group in response.json()["data"]["items"]}[_TARGET_A]
response = requests.get(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{target_a}/span_mappers"), headers=headers, timeout=5)
assert response.status_code == HTTPStatus.OK, response.text
mapper_a = response.json()["data"]["items"][0]["id"]
# Adding a mapper needs create on the collection plus attach on the group;
# removing one needs delete on the mapper plus detach on the group.
response = requests.get(signoz.self.host_configs["8080"].get("/api/v1/roles"), headers=headers, timeout=5)
assert response.status_code == HTTPStatus.OK, response.text
if not any(role["name"] == _ACTOR_ROLE_NAME for role in response.json()["data"]):
create_role(
admin_token,
_ACTOR_ROLE_NAME,
[
transaction_group("list", "metaresource", "span-mapper-group", ["*"]),
transaction_group("read", "metaresource", "span-mapper-group", [target_a]),
transaction_group("update", "metaresource", "span-mapper-group", [target_a]),
transaction_group("attach", "metaresource", "span-mapper-group", [target_a]),
transaction_group("detach", "metaresource", "span-mapper-group", [target_a]),
transaction_group("create", "metaresource", "span-mapper", ["*"]),
transaction_group("delete", "metaresource", "span-mapper", ["*"]),
transaction_group("update", "metaresource", "span-mapper", [mapper_a]),
],
)
response = requests.get(signoz.self.host_configs["8080"].get("/api/v2/users"), headers=headers, timeout=5)
assert response.status_code == HTTPStatus.OK, response.text
actor = next((user for user in response.json()["data"] if user["email"] == _ACTOR_EMAIL), None)
user_id = actor["id"] if actor else create_active_user(signoz, admin_token, email=_ACTOR_EMAIL, role="signoz-viewer", password=_PASSWORD)
response = requests.get(signoz.self.host_configs["8080"].get(f"/api/v2/users/{user_id}"), headers=headers, timeout=5)
assert response.status_code == HTTPStatus.OK, response.text
if not any(ur["role"]["name"] == _ACTOR_ROLE_NAME for ur in response.json()["data"]["userRoles"]):
change_user_role(signoz, admin_token, user_id, "signoz-viewer", _ACTOR_ROLE_NAME)
def test_access_scoped_to_granted_group_and_mapper(
signoz: SigNoz,
create_user_admin: Operation, # pylint: disable=unused-argument
get_token: Callable[[str, str], str],
):
headers = {"Authorization": f"Bearer {get_token(_ACTOR_EMAIL, _PASSWORD)}"}
response = requests.get(signoz.self.host_configs["8080"].get(GROUPS_PATH), headers=headers, timeout=5)
assert response.status_code == HTTPStatus.OK, response.text
ids = {group["name"]: group["id"] for group in response.json()["data"]["items"]}
assert {_TARGET_A, _TARGET_B} <= set(ids)
response = requests.get(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{ids[_TARGET_A]}/span_mappers"), headers=headers, timeout=5)
assert response.status_code == HTTPStatus.OK, f"list granted group's mappers: {response.text}"
mapper_a = response.json()["data"]["items"][0]["id"]
response = requests.get(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{ids[_TARGET_B]}/span_mappers"), headers=headers, timeout=5)
assert response.status_code == HTTPStatus.FORBIDDEN, f"list other group's mappers: expected 403, got {response.status_code}: {response.text}"
# Simulate reads saved groups by name, so it needs read on every group.
response = requests.post(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/test"), json=_SIMULATE, headers=headers, timeout=5)
assert response.status_code == HTTPStatus.FORBIDDEN, f"simulate: expected 403, got {response.status_code}: {response.text}"
response = requests.patch(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{ids[_TARGET_A]}"), json={"enabled": True}, headers=headers, timeout=5)
assert response.status_code == HTTPStatus.NO_CONTENT, f"update granted group: {response.text}"
response = requests.patch(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{ids[_TARGET_B]}"), json={"enabled": True}, headers=headers, timeout=5)
assert response.status_code == HTTPStatus.FORBIDDEN, f"update other group: expected 403, got {response.status_code}: {response.text}"
response = requests.post(
signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{ids[_TARGET_A]}/span_mappers"),
json={**_MAPPER, "name": "span_mapper_authz.actor"},
headers=headers,
timeout=5,
)
assert response.status_code == HTTPStatus.CREATED, f"create mapper in granted group: {response.text}"
created = response.json()["data"]["id"]
response = requests.delete(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{ids[_TARGET_A]}/span_mappers/{created}"), headers=headers, timeout=5)
assert response.status_code == HTTPStatus.NO_CONTENT, f"delete mapper in granted group: {response.text}"
response = requests.post(
signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{ids[_TARGET_B]}/span_mappers"),
json={**_MAPPER, "name": "span_mapper_authz.actor"},
headers=headers,
timeout=5,
)
assert response.status_code == HTTPStatus.FORBIDDEN, f"create mapper in other group: expected 403, got {response.status_code}: {response.text}"
# Mapper update is checked on the mapper itself, so the grant on A's mapper
# does not extend to B's.
response = requests.patch(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{ids[_TARGET_A]}/span_mappers/{mapper_a}"), json={"enabled": True}, headers=headers, timeout=5)
assert response.status_code == HTTPStatus.NO_CONTENT, f"update granted mapper: {response.text}"
admin_headers = {"Authorization": f"Bearer {get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)}"}
response = requests.get(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{ids[_TARGET_B]}/span_mappers"), headers=admin_headers, timeout=5)
assert response.status_code == HTTPStatus.OK, response.text
mapper_b = response.json()["data"]["items"][0]["id"]
response = requests.patch(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{ids[_TARGET_B]}/span_mappers/{mapper_b}"), json={"enabled": True}, headers=headers, timeout=5)
assert response.status_code == HTTPStatus.FORBIDDEN, f"update other mapper: expected 403, got {response.status_code}: {response.text}"
response = requests.delete(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{ids[_TARGET_B]}/span_mappers/{mapper_b}"), headers=headers, timeout=5)
assert response.status_code == HTTPStatus.FORBIDDEN, f"delete other mapper: expected 403, got {response.status_code}: {response.text}"
# detach on A plus delete on "*" passes authz for B's mapper addressed through
# A's path; the store must still refuse it.
response = requests.delete(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{ids[_TARGET_A]}/span_mappers/{mapper_b}"), headers=headers, timeout=5)
assert response.status_code == HTTPStatus.NOT_FOUND, f"delete B's mapper via A: expected 404, got {response.status_code}: {response.text}"
response = requests.post(
signoz.self.host_configs["8080"].get(GROUPS_PATH),
json={"name": "span-mapper-authz-actor", "condition": {"attributes": [{"value": "authz.actor", "enabled": True}], "resource": []}, "enabled": True},
headers=headers,
timeout=5,
)
assert response.status_code == HTTPStatus.FORBIDDEN, f"create group: expected 403, got {response.status_code}: {response.text}"
response = requests.delete(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{ids[_TARGET_A]}"), headers=headers, timeout=5)
assert response.status_code == HTTPStatus.FORBIDDEN, f"delete granted group: expected 403, got {response.status_code}: {response.text}"
def test_revoke_group_read(
signoz: SigNoz,
create_user_admin: Operation, # pylint: disable=unused-argument
get_token: Callable[[str, str], str],
):
admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
admin_headers = {"Authorization": f"Bearer {admin_token}"}
headers = {"Authorization": f"Bearer {get_token(_ACTOR_EMAIL, _PASSWORD)}"}
response = requests.get(signoz.self.host_configs["8080"].get(GROUPS_PATH), headers=admin_headers, timeout=5)
assert response.status_code == HTTPStatus.OK, response.text
target_a = {group["name"]: group["id"] for group in response.json()["data"]["items"]}[_TARGET_A]
response = requests.get(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{target_a}/span_mappers"), headers=headers, timeout=5)
assert response.status_code == HTTPStatus.OK, f"read before revoke: {response.text}"
response = requests.put(
signoz.self.host_configs["8080"].get(f"/api/v1/roles/{find_role_by_name(signoz, admin_token, _ACTOR_ROLE_NAME)}"),
json={"description": "", "transactionGroups": [transaction_group("list", "metaresource", "span-mapper-group", ["*"])]},
headers=admin_headers,
timeout=5,
)
assert response.status_code == HTTPStatus.NO_CONTENT, response.text
response = requests.get(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{target_a}/span_mappers"), headers=headers, timeout=5)
assert response.status_code == HTTPStatus.FORBIDDEN, f"read after revoke: expected 403, got {response.status_code}: {response.text}"
def test_span_mapper_authz_cleanup(
signoz: SigNoz,
create_user_admin: Operation, # pylint: disable=unused-argument
get_token: Callable[[str, str], str],
):
admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
headers = {"Authorization": f"Bearer {admin_token}"}
actor = find_user_by_email(signoz, admin_token, _ACTOR_EMAIL)
# Back to viewer so a rerun on the same stack can set the actor up again.
change_user_role(signoz, admin_token, actor["id"], _ACTOR_ROLE_NAME, "signoz-viewer")
response = requests.delete(
signoz.self.host_configs["8080"].get(f"/api/v1/roles/{find_role_by_name(signoz, admin_token, _ACTOR_ROLE_NAME)}"),
headers=headers,
timeout=5,
)
assert response.status_code == HTTPStatus.NO_CONTENT, f"delete {_ACTOR_ROLE_NAME}: {response.text}"
response = requests.get(signoz.self.host_configs["8080"].get(GROUPS_PATH), headers=headers, timeout=5)
assert response.status_code == HTTPStatus.OK, response.text
ids = {group["name"]: group["id"] for group in response.json()["data"]["items"]}
for name in (_TARGET_A, _TARGET_B):
response = requests.delete(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{ids[name]}"), headers=headers, timeout=5)
assert response.status_code == HTTPStatus.NO_CONTENT, f"delete {name}: {response.text}"