Skip to content

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

feat: add create v2 api for notification channels (#12638)

Naman Verma861380dc6546
diff --git a/docs/api/openapi.yml b/docs/api/openapi.yml
index 029d4db99a..67cdb85fed 100644
--- a/docs/api/openapi.yml
+++ b/docs/api/openapi.yml
@@ -25,6 +25,379 @@ components:
- data
- orgId
type: object
+ AlertmanagertypesChannelConfig:
+ discriminator:
+ mapping:
+ email: '#/components/schemas/AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelEmailConfig'
+ googlechat: '#/components/schemas/AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelGoogleChatConfig'
+ incidentio: '#/components/schemas/AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelIncidentIOConfig'
+ jira: '#/components/schemas/AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelJiraConfig'
+ jsmops: '#/components/schemas/AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelJSMOpsConfig'
+ msteams: '#/components/schemas/AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelMSTeamsConfig'
+ opsgenie: '#/components/schemas/AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelOpsgenieConfig'
+ pagerduty: '#/components/schemas/AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelPagerdutyConfig'
+ slack: '#/components/schemas/AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelSlackConfig'
+ webhook: '#/components/schemas/AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelWebhookConfig'
+ propertyName: kind
+ oneOf:
+ - $ref: '#/components/schemas/AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelSlackConfig'
+ - $ref: '#/components/schemas/AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelEmailConfig'
+ - $ref: '#/components/schemas/AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelWebhookConfig'
+ - $ref: '#/components/schemas/AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelPagerdutyConfig'
+ - $ref: '#/components/schemas/AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelOpsgenieConfig'
+ - $ref: '#/components/schemas/AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelMSTeamsConfig'
+ - $ref: '#/components/schemas/AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelGoogleChatConfig'
+ - $ref: '#/components/schemas/AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelJiraConfig'
+ - $ref: '#/components/schemas/AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelJSMOpsConfig'
+ - $ref: '#/components/schemas/AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelIncidentIOConfig'
+ type: object
+ AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelEmailConfig:
+ properties:
+ kind:
+ enum:
+ - email
+ type: string
+ spec:
+ $ref: '#/components/schemas/AlertmanagertypesChannelEmailConfig'
+ required:
+ - kind
+ - spec
+ type: object
+ AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelGoogleChatConfig:
+ properties:
+ kind:
+ enum:
+ - googlechat
+ type: string
+ spec:
+ $ref: '#/components/schemas/AlertmanagertypesChannelGoogleChatConfig'
+ required:
+ - kind
+ - spec
+ type: object
+ AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelIncidentIOConfig:
+ properties:
+ kind:
+ enum:
+ - incidentio
+ type: string
+ spec:
+ $ref: '#/components/schemas/AlertmanagertypesChannelIncidentIOConfig'
+ required:
+ - kind
+ - spec
+ type: object
+ AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelJSMOpsConfig:
+ properties:
+ kind:
+ enum:
+ - jsmops
+ type: string
+ spec:
+ $ref: '#/components/schemas/AlertmanagertypesChannelJSMOpsConfig'
+ required:
+ - kind
+ - spec
+ type: object
+ AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelJiraConfig:
+ properties:
+ kind:
+ enum:
+ - jira
+ type: string
+ spec:
+ $ref: '#/components/schemas/AlertmanagertypesChannelJiraConfig'
+ required:
+ - kind
+ - spec
+ type: object
+ AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelMSTeamsConfig:
+ properties:
+ kind:
+ enum:
+ - msteams
+ type: string
+ spec:
+ $ref: '#/components/schemas/AlertmanagertypesChannelMSTeamsConfig'
+ required:
+ - kind
+ - spec
+ type: object
+ AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelOpsgenieConfig:
+ properties:
+ kind:
+ enum:
+ - opsgenie
+ type: string
+ spec:
+ $ref: '#/components/schemas/AlertmanagertypesChannelOpsgenieConfig'
+ required:
+ - kind
+ - spec
+ type: object
+ AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelPagerdutyConfig:
+ properties:
+ kind:
+ enum:
+ - pagerduty
+ type: string
+ spec:
+ $ref: '#/components/schemas/AlertmanagertypesChannelPagerdutyConfig'
+ required:
+ - kind
+ - spec
+ type: object
+ AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelSlackConfig:
+ properties:
+ kind:
+ enum:
+ - slack
+ type: string
+ spec:
+ $ref: '#/components/schemas/AlertmanagertypesChannelSlackConfig'
+ required:
+ - kind
+ - spec
+ type: object
+ AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelWebhookConfig:
+ properties:
+ kind:
+ enum:
+ - webhook
+ type: string
+ spec:
+ $ref: '#/components/schemas/AlertmanagertypesChannelWebhookConfig'
+ required:
+ - kind
+ - spec
+ type: object
+ AlertmanagertypesChannelEmailConfig:
+ properties:
+ headers:
+ additionalProperties:
+ type: string
+ type: object
+ html:
+ type: string
+ sendResolved:
+ nullable: true
+ type: boolean
+ to:
+ type: string
+ required:
+ - to
+ type: object
+ AlertmanagertypesChannelGoogleChatConfig:
+ properties:
+ sendResolved:
+ nullable: true
+ type: boolean
+ text:
+ type: string
+ title:
+ type: string
+ webhookUrl:
+ type: string
+ required:
+ - webhookUrl
+ type: object
+ AlertmanagertypesChannelIncidentIOConfig:
+ properties:
+ description:
+ type: string
+ metadata:
+ additionalProperties:
+ type: string
+ type: object
+ sendResolved:
+ nullable: true
+ type: boolean
+ title:
+ type: string
+ token:
+ type: string
+ url:
+ type: string
+ required:
+ - url
+ - token
+ type: object
+ AlertmanagertypesChannelJSMOpsConfig:
+ properties:
+ apiKey:
+ type: string
+ description:
+ type: string
+ message:
+ type: string
+ priority:
+ type: string
+ sendResolved:
+ nullable: true
+ type: boolean
+ tags:
+ type: string
+ required:
+ - apiKey
+ type: object
+ AlertmanagertypesChannelJiraConfig:
+ properties:
+ apiToken:
+ type: string
+ customFields:
+ additionalProperties: {}
+ type: object
+ description:
+ type: string
+ email:
+ type: string
+ issueType:
+ type: string
+ labels:
+ items:
+ type: string
+ type: array
+ priority:
+ type: string
+ project:
+ type: string
+ reopenDuration:
+ type: string
+ reopenTransition:
+ type: string
+ resolveTransition:
+ type: string
+ sendResolved:
+ nullable: true
+ type: boolean
+ site:
+ type: string
+ summary:
+ type: string
+ wontFixResolution:
+ type: string
+ required:
+ - site
+ - project
+ - issueType
+ - email
+ - apiToken
+ type: object
+ AlertmanagertypesChannelKind:
+ enum:
+ - slack
+ - email
+ - webhook
+ - pagerduty
+ - opsgenie
+ - msteams
+ - googlechat
+ - jira
+ - jsmops
+ - incidentio
+ type: string
+ AlertmanagertypesChannelMSTeamsConfig:
+ properties:
+ sendResolved:
+ nullable: true
+ type: boolean
+ text:
+ type: string
+ title:
+ type: string
+ webhookUrl:
+ type: string
+ required:
+ - webhookUrl
+ type: object
+ AlertmanagertypesChannelOpsgenieConfig:
+ properties:
+ apiKey:
+ type: string
+ apiUrl:
+ type: string
+ description:
+ type: string
+ details:
+ additionalProperties:
+ type: string
+ type: object
+ message:
+ type: string
+ priority:
+ type: string
+ sendResolved:
+ nullable: true
+ type: boolean
+ source:
+ type: string
+ required:
+ - apiKey
+ type: object
+ AlertmanagertypesChannelPagerdutyConfig:
+ properties:
+ class:
+ type: string
+ client:
+ type: string
+ clientUrl:
+ type: string
+ component:
+ type: string
+ description:
+ type: string
+ details:
+ additionalProperties:
+ type: string
+ type: object
+ group:
+ type: string
+ routingKey:
+ type: string
+ sendResolved:
+ nullable: true
+ type: boolean
+ severity:
+ type: string
+ source:
+ type: string
+ url:
+ type: string
+ required:
+ - routingKey
+ type: object
+ AlertmanagertypesChannelSlackConfig:
+ properties:
+ apiUrl:
+ type: string
+ channel:
+ type: string
+ sendResolved:
+ nullable: true
+ type: boolean
+ text:
+ type: string
+ title:
+ type: string
+ required:
+ - apiUrl
+ type: object
+ AlertmanagertypesChannelWebhookConfig:
+ properties:
+ bearerToken:
+ type: string
+ password:
+ type: string
+ sendResolved:
+ nullable: true
+ type: boolean
+ url:
+ type: string
+ username:
+ type: string
+ required:
+ - url
+ type: object
AlertmanagertypesDeprecatedGettableAlert:
properties:
annotations:
@@ -54,6 +427,30 @@ components:
- rule
- policy
type: string
+ AlertmanagertypesGettableNotificationChannel:
+ properties:
+ config:
+ $ref: '#/components/schemas/AlertmanagertypesChannelConfig'
+ createdAt:
+ format: date-time
+ type: string
+ displayName:
+ type: string
+ id:
+ type: string
+ name:
+ type: string
+ updatedAt:
+ format: date-time
+ type: string
+ required:
+ - name
+ - displayName
+ - config
+ - id
+ - createdAt
+ - updatedAt
+ type: object
AlertmanagertypesGettableRoutePolicy:
properties:
channels:
@@ -356,6 +753,19 @@ components:
required:
- name
type: object
+ AlertmanagertypesPostableNotificationChannel:
+ properties:
+ config:
+ $ref: '#/components/schemas/AlertmanagertypesChannelConfig'
+ displayName:
+ type: string
+ generateName:
+ type: boolean
+ name:
+ type: string
+ required:
+ - config
+ type: object
AlertmanagertypesPostablePlannedMaintenance:
properties:
alertIds:
@@ -19309,6 +19719,69 @@ paths:
summary: Get metrics treemap
tags:
- metrics
+ /api/v2/notification_channels:
+ post:
+ deprecated: false
+ description: This endpoint creates a notification channel
+ operationId: CreateNotificationChannel
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/AlertmanagertypesPostableNotificationChannel'
+ responses:
+ "201":
+ content:
+ application/json:
+ schema:
+ properties:
+ data:
+ $ref: '#/components/schemas/AlertmanagertypesGettableNotificationChannel'
+ status:
+ type: string
+ required:
+ - status
+ - data
+ type: object
+ description: Created
+ "400":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Bad Request
+ "401":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Unauthorized
+ "403":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Forbidden
+ "409":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Conflict
+ "500":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Internal Server Error
+ security:
+ - api_key:
+ - notification-channel:create
+ - tokenizer:
+ - notification-channel:create
+ summary: Create notification channel
+ tags:
+ - channels
/api/v2/orgs/me:
get:
deprecated: false
diff --git a/frontend/src/api/generated/services/channels/index.ts b/frontend/src/api/generated/services/channels/index.ts
index 400209ed0e..8a2ef4fb43 100644
--- a/frontend/src/api/generated/services/channels/index.ts
+++ b/frontend/src/api/generated/services/channels/index.ts
@@ -19,8 +19,10 @@ import type {
import type {
AlertmanagertypesPostableChannelDTO,
+ AlertmanagertypesPostableNotificationChannelDTO,
AlertmanagertypesReceiverDTO,
CreateChannel201,
+ CreateNotificationChannel201,
DeleteChannelByIDPathParameters,
GetChannelByID200,
GetChannelByIDPathParameters,
@@ -647,3 +649,87 @@ export const useTestChannelDeprecated = <
> => {
return useMutation(getTestChannelDeprecatedMutationOptions(options));
};
+/**
+ * This endpoint creates a notification channel
+ * @summary Create notification channel
+ */
+export const createNotificationChannel = (
+ alertmanagertypesPostableNotificationChannelDTO?: BodyType<AlertmanagertypesPostableNotificationChannelDTO>,
+ signal?: AbortSignal,
+) => {
+ return GeneratedAPIInstance<CreateNotificationChannel201>({
+ url: `/api/v2/notification_channels`,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ data: alertmanagertypesPostableNotificationChannelDTO,
+ signal,
+ });
+};
+
+export const getCreateNotificationChannelMutationOptions = <
+ TError = ErrorType<RenderErrorResponseDTO>,
+ TContext = unknown,
+>(options?: {
+ mutation?: UseMutationOptions<
+ Awaited<ReturnType<typeof createNotificationChannel>>,
+ TError,
+ { data?: BodyType<AlertmanagertypesPostableNotificationChannelDTO> },
+ TContext
+ >;
+}): UseMutationOptions<
+ Awaited<ReturnType<typeof createNotificationChannel>>,
+ TError,
+ { data?: BodyType<AlertmanagertypesPostableNotificationChannelDTO> },
+ TContext
+> => {
+ const mutationKey = ['createNotificationChannel'];
+ const { mutation: mutationOptions } = options
+ ? options.mutation &&
+ 'mutationKey' in options.mutation &&
+ options.mutation.mutationKey
+ ? options
+ : { ...options, mutation: { ...options.mutation, mutationKey } }
+ : { mutation: { mutationKey } };
+
+ const mutationFn: MutationFunction<
+ Awaited<ReturnType<typeof createNotificationChannel>>,
+ { data?: BodyType<AlertmanagertypesPostableNotificationChannelDTO> }
+ > = (props) => {
+ const { data } = props ?? {};
+
+ return createNotificationChannel(data);
+ };
+
+ return { mutationFn, ...mutationOptions };
+};
+
+export type CreateNotificationChannelMutationResult = NonNullable<
+ Awaited<ReturnType<typeof createNotificationChannel>>
+>;
+export type CreateNotificationChannelMutationBody =
+ | BodyType<AlertmanagertypesPostableNotificationChannelDTO>
+ | undefined;
+export type CreateNotificationChannelMutationError =
+ ErrorType<RenderErrorResponseDTO>;
+
+/**
+ * @summary Create notification channel
+ */
+export const useCreateNotificationChannel = <
+ TError = ErrorType<RenderErrorResponseDTO>,
+ TContext = unknown,
+>(options?: {
+ mutation?: UseMutationOptions<
+ Awaited<ReturnType<typeof createNotificationChannel>>,
+ TError,
+ { data?: BodyType<AlertmanagertypesPostableNotificationChannelDTO> },
+ TContext
+ >;
+}): UseMutationResult<
+ Awaited<ReturnType<typeof createNotificationChannel>>,
+ TError,
+ { data?: BodyType<AlertmanagertypesPostableNotificationChannelDTO> },
+ TContext
+> => {
+ return useMutation(getCreateNotificationChannelMutationOptions(options));
+};
diff --git a/frontend/src/api/generated/services/sigNoz.schemas.ts b/frontend/src/api/generated/services/sigNoz.schemas.ts
index 973c64d2bd..218dd28ebf 100644
--- a/frontend/src/api/generated/services/sigNoz.schemas.ts
+++ b/frontend/src/api/generated/services/sigNoz.schemas.ts
@@ -37,6 +37,476 @@ export interface AlertmanagertypesChannelDTO {
updatedAt?: string;
}
+export enum AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelSlackConfigDTOKind {
+ slack = 'slack',
+}
+export interface AlertmanagertypesChannelSlackConfigDTO {
+ /**
+ * @type string
+ */
+ apiUrl: string;
+ /**
+ * @type string
+ */
+ channel?: string;
+ /**
+ * @type boolean,null
+ */
+ sendResolved?: boolean | null;
+ /**
+ * @type string
+ */
+ text?: string;
+ /**
+ * @type string
+ */
+ title?: string;
+}
+
+export interface AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelSlackConfigDTO {
+ /**
+ * @enum slack
+ * @type string
+ */
+ kind: AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelSlackConfigDTOKind;
+ spec: AlertmanagertypesChannelSlackConfigDTO;
+}
+
+export enum AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelEmailConfigDTOKind {
+ email = 'email',
+}
+export type AlertmanagertypesChannelEmailConfigDTOHeaders = {
+ [key: string]: string;
+};
+
+export interface AlertmanagertypesChannelEmailConfigDTO {
+ /**
+ * @type object
+ */
+ headers?: AlertmanagertypesChannelEmailConfigDTOHeaders;
+ /**
+ * @type string
+ */
+ html?: string;
+ /**
+ * @type boolean,null
+ */
+ sendResolved?: boolean | null;
+ /**
+ * @type string
+ */
+ to: string;
+}
+
+export interface AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelEmailConfigDTO {
+ /**
+ * @enum email
+ * @type string
+ */
+ kind: AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelEmailConfigDTOKind;
+ spec: AlertmanagertypesChannelEmailConfigDTO;
+}
+
+export enum AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelWebhookConfigDTOKind {
+ webhook = 'webhook',
+}
+export interface AlertmanagertypesChannelWebhookConfigDTO {
+ /**
+ * @type string
+ */
+ bearerToken?: string;
+ /**
+ * @type string
+ */
+ password?: string;
+ /**
+ * @type boolean,null
+ */
+ sendResolved?: boolean | null;
+ /**
+ * @type string
+ */
+ url: string;
+ /**
+ * @type string
+ */
+ username?: string;
+}
+
+export interface AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelWebhookConfigDTO {
+ /**
+ * @enum webhook
+ * @type string
+ */
+ kind: AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelWebhookConfigDTOKind;
+ spec: AlertmanagertypesChannelWebhookConfigDTO;
+}
+
+export enum AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelPagerdutyConfigDTOKind {
+ pagerduty = 'pagerduty',
+}
+export type AlertmanagertypesChannelPagerdutyConfigDTODetails = {
+ [key: string]: string;
+};
+
+export interface AlertmanagertypesChannelPagerdutyConfigDTO {
+ /**
+ * @type string
+ */
+ class?: string;
+ /**
+ * @type string
+ */
+ client?: string;
+ /**
+ * @type string
+ */
+ clientUrl?: string;
+ /**
+ * @type string
+ */
+ component?: string;
+ /**
+ * @type string
+ */
+ description?: string;
+ /**
+ * @type object
+ */
+ details?: AlertmanagertypesChannelPagerdutyConfigDTODetails;
+ /**
+ * @type string
+ */
+ group?: string;
+ /**
+ * @type string
+ */
+ routingKey: string;
+ /**
+ * @type boolean,null
+ */
+ sendResolved?: boolean | null;
+ /**
+ * @type string
+ */
+ severity?: string;
+ /**
+ * @type string
+ */
+ source?: string;
+ /**
+ * @type string
+ */
+ url?: string;
+}
+
+export interface AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelPagerdutyConfigDTO {
+ /**
+ * @enum pagerduty
+ * @type string
+ */
+ kind: AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelPagerdutyConfigDTOKind;
+ spec: AlertmanagertypesChannelPagerdutyConfigDTO;
+}
+
+export enum AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelOpsgenieConfigDTOKind {
+ opsgenie = 'opsgenie',
+}
+export type AlertmanagertypesChannelOpsgenieConfigDTODetails = {
+ [key: string]: string;
+};
+
+export interface AlertmanagertypesChannelOpsgenieConfigDTO {
+ /**
+ * @type string
+ */
+ apiKey: string;
+ /**
+ * @type string
+ */
+ apiUrl?: string;
+ /**
+ * @type string
+ */
+ description?: string;
+ /**
+ * @type object
+ */
+ details?: AlertmanagertypesChannelOpsgenieConfigDTODetails;
+ /**
+ * @type string
+ */
+ message?: string;
+ /**
+ * @type string
+ */
+ priority?: string;
+ /**
+ * @type boolean,null
+ */
+ sendResolved?: boolean | null;
+ /**
+ * @type string
+ */
+ source?: string;
+}
+
+export interface AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelOpsgenieConfigDTO {
+ /**
+ * @enum opsgenie
+ * @type string
+ */
+ kind: AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelOpsgenieConfigDTOKind;
+ spec: AlertmanagertypesChannelOpsgenieConfigDTO;
+}
+
+export enum AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelMSTeamsConfigDTOKind {
+ msteams = 'msteams',
+}
+export interface AlertmanagertypesChannelMSTeamsConfigDTO {
+ /**
+ * @type boolean,null
+ */
+ sendResolved?: boolean | null;
+ /**
+ * @type string
+ */
+ text?: string;
+ /**
+ * @type string
+ */
+ title?: string;
+ /**
+ * @type string
+ */
+ webhookUrl: string;
+}
+
+export interface AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelMSTeamsConfigDTO {
+ /**
+ * @enum msteams
+ * @type string
+ */
+ kind: AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelMSTeamsConfigDTOKind;
+ spec: AlertmanagertypesChannelMSTeamsConfigDTO;
+}
+
+export enum AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelGoogleChatConfigDTOKind {
+ googlechat = 'googlechat',
+}
+export interface AlertmanagertypesChannelGoogleChatConfigDTO {
+ /**
+ * @type boolean,null
+ */
+ sendResolved?: boolean | null;
+ /**
+ * @type string
+ */
+ text?: string;
+ /**
+ * @type string
+ */
+ title?: string;
+ /**
+ * @type string
+ */
+ webhookUrl: string;
+}
+
+export interface AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelGoogleChatConfigDTO {
+ /**
+ * @enum googlechat
+ * @type string
+ */
+ kind: AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelGoogleChatConfigDTOKind;
+ spec: AlertmanagertypesChannelGoogleChatConfigDTO;
+}
+
+export enum AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelJiraConfigDTOKind {
+ jira = 'jira',
+}
+export type AlertmanagertypesChannelJiraConfigDTOCustomFields = {
+ [key: string]: unknown;
+};
+
+export interface AlertmanagertypesChannelJiraConfigDTO {
+ /**
+ * @type string
+ */
+ apiToken: string;
+ /**
+ * @type object
+ */
+ customFields?: AlertmanagertypesChannelJiraConfigDTOCustomFields;
+ /**
+ * @type string
+ */
+ description?: string;
+ /**
+ * @type string
+ */
+ email: string;
+ /**
+ * @type string
+ */
+ issueType: string;
+ /**
+ * @type array
+ */
+ labels?: string[];
+ /**
+ * @type string
+ */
+ priority?: string;
+ /**
+ * @type string
+ */
+ project: string;
+ /**
+ * @type string
+ */
+ reopenDuration?: string;
+ /**
+ * @type string
+ */
+ reopenTransition?: string;
+ /**
+ * @type string
+ */
+ resolveTransition?: string;
+ /**
+ * @type boolean,null
+ */
+ sendResolved?: boolean | null;
+ /**
+ * @type string
+ */
+ site: string;
+ /**
+ * @type string
+ */
+ summary?: string;
+ /**
+ * @type string
+ */
+ wontFixResolution?: string;
+}
+
+export interface AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelJiraConfigDTO {
+ /**
+ * @enum jira
+ * @type string
+ */
+ kind: AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelJiraConfigDTOKind;
+ spec: AlertmanagertypesChannelJiraConfigDTO;
+}
+
+export enum AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelJSMOpsConfigDTOKind {
+ jsmops = 'jsmops',
+}
+export interface AlertmanagertypesChannelJSMOpsConfigDTO {
+ /**
+ * @type string
+ */
+ apiKey: string;
+ /**
+ * @type string
+ */
+ description?: string;
+ /**
+ * @type string
+ */
+ message?: string;
+ /**
+ * @type string
+ */
+ priority?: string;
+ /**
+ * @type boolean,null
+ */
+ sendResolved?: boolean | null;
+ /**
+ * @type string
+ */
+ tags?: string;
+}
+
+export interface AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelJSMOpsConfigDTO {
+ /**
+ * @enum jsmops
+ * @type string
+ */
+ kind: AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelJSMOpsConfigDTOKind;
+ spec: AlertmanagertypesChannelJSMOpsConfigDTO;
+}
+
+export enum AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelIncidentIOConfigDTOKind {
+ incidentio = 'incidentio',
+}
+export type AlertmanagertypesChannelIncidentIOConfigDTOMetadata = {
+ [key: string]: string;
+};
+
+export interface AlertmanagertypesChannelIncidentIOConfigDTO {
+ /**
+ * @type string
+ */
+ description?: string;
+ /**
+ * @type object
+ */
+ metadata?: AlertmanagertypesChannelIncidentIOConfigDTOMetadata;
+ /**
+ * @type boolean,null
+ */
+ sendResolved?: boolean | null;
+ /**
+ * @type string
+ */
+ title?: string;
+ /**
+ * @type string
+ */
+ token: string;
+ /**
+ * @type string
+ */
+ url: string;
+}
+
+export interface AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelIncidentIOConfigDTO {
+ /**
+ * @enum incidentio
+ * @type string
+ */
+ kind: AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelIncidentIOConfigDTOKind;
+ spec: AlertmanagertypesChannelIncidentIOConfigDTO;
+}
+
+export type AlertmanagertypesChannelConfigDTO =
+ | AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelSlackConfigDTO
+ | AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelEmailConfigDTO
+ | AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelWebhookConfigDTO
+ | AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelPagerdutyConfigDTO
+ | AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelOpsgenieConfigDTO
+ | AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelMSTeamsConfigDTO
+ | AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelGoogleChatConfigDTO
+ | AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelJiraConfigDTO
+ | AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelJSMOpsConfigDTO
+ | AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelIncidentIOConfigDTO;
+
+export enum AlertmanagertypesChannelKindDTO {
+ slack = 'slack',
+ email = 'email',
+ webhook = 'webhook',
+ pagerduty = 'pagerduty',
+ opsgenie = 'opsgenie',
+ msteams = 'msteams',
+ googlechat = 'googlechat',
+ jira = 'jira',
+ jsmops = 'jsmops',
+ incidentio = 'incidentio',
+}
export interface ModelLabelSetDTO {
[key: string]: string;
}
@@ -88,6 +558,32 @@ export enum AlertmanagertypesExpressionKindDTO {
rule = 'rule',
policy = 'policy',
}
+export interface AlertmanagertypesGettableNotificationChannelDTO {
+ config: AlertmanagertypesChannelConfigDTO;
+ /**
+ * @type string
+ * @format date-time
+ */
+ createdAt: string;
+ /**
+ * @type string
+ */
+ displayName: string;
+ /**
+ * @type string
+ */
+ id: string;
+ /**
+ * @type string
+ */
+ name: string;
+ /**
+ * @type string
+ * @format date-time
+ */
+ updatedAt: string;
+}
+
export interface AlertmanagertypesGettableRoutePolicyDTO {
/**
* @type array,null
@@ -1748,6 +2244,22 @@ export type AlertmanagertypesPostableChannelDTO = unknown & {
wechat_configs?: ConfigWechatConfigDTO[];
};
+export interface AlertmanagertypesPostableNotificationChannelDTO {
+ config: AlertmanagertypesChannelConfigDTO;
+ /**
+ * @type string
+ */
+ displayName?: string;
+ /**
+ * @type boolean
+ */
+ generateName?: boolean;
+ /**
+ * @type string
+ */
+ name?: string;
+}
+
export interface AlertmanagertypesPostablePlannedMaintenanceDTO {
/**
* @type array,null
@@ -12650,6 +13162,14 @@ export type GetMetricsTreemap200 = {
status: string;
};
+export type CreateNotificationChannel201 = {
+ data: AlertmanagertypesGettableNotificationChannelDTO;
+ /**
+ * @type string
+ */
+ status: string;
+};
+
export type GetMyOrganization200 = {
data: TypesOrganizationDTO;
/**
diff --git a/pkg/alertmanager/alertmanager.go b/pkg/alertmanager/alertmanager.go
index ecafc59430..85057646fd 100644
--- a/pkg/alertmanager/alertmanager.go
+++ b/pkg/alertmanager/alertmanager.go
@@ -46,6 +46,10 @@ type Alertmanager interface {
// CreateChannel creates a channel for the organization.
CreateChannel(context.Context, string, *alertmanagertypes.Receiver) (*alertmanagertypes.Channel, error)
+ // CreateNotificationChannel takes the postable rather than a receiver, because
+ // a receiver carries only the display name.
+ CreateNotificationChannel(context.Context, string, *alertmanagertypes.PostableNotificationChannel) (*alertmanagertypes.Channel, error)
+
// DeleteChannelByID deletes a channel for the organization.
DeleteChannelByID(context.Context, string, valuer.UUID) error
diff --git a/pkg/alertmanager/alertmanagertest/alertmanager.go b/pkg/alertmanager/alertmanagertest/alertmanager.go
index bab337884b..d28d2f6391 100644
--- a/pkg/alertmanager/alertmanagertest/alertmanager.go
+++ b/pkg/alertmanager/alertmanagertest/alertmanager.go
@@ -155,8 +155,8 @@ func (_c *MockAlertmanager_Config_Call) RunAndReturn(run func() alertmanagerserv
}
// CreateChannel provides a mock function for the type MockAlertmanager
-func (_mock *MockAlertmanager) CreateChannel(context1 context.Context, s string, v *alertmanagertypes.Receiver) (*alertmanagertypes.Channel, error) {
- ret := _mock.Called(context1, s, v)
+func (_mock *MockAlertmanager) CreateChannel(context1 context.Context, s string, receiver *alertmanagertypes.Receiver) (*alertmanagertypes.Channel, error) {
+ ret := _mock.Called(context1, s, receiver)
if len(ret) == 0 {
panic("no return value specified for CreateChannel")
@@ -165,17 +165,17 @@ func (_mock *MockAlertmanager) CreateChannel(context1 context.Context, s string,
var r0 *alertmanagertypes.Channel
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, string, *alertmanagertypes.Receiver) (*alertmanagertypes.Channel, error)); ok {
- return returnFunc(context1, s, v)
+ return returnFunc(context1, s, receiver)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, string, *alertmanagertypes.Receiver) *alertmanagertypes.Channel); ok {
- r0 = returnFunc(context1, s, v)
+ r0 = returnFunc(context1, s, receiver)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*alertmanagertypes.Channel)
}
}
if returnFunc, ok := ret.Get(1).(func(context.Context, string, *alertmanagertypes.Receiver) error); ok {
- r1 = returnFunc(context1, s, v)
+ r1 = returnFunc(context1, s, receiver)
} else {
r1 = ret.Error(1)
}
@@ -190,12 +190,12 @@ type MockAlertmanager_CreateChannel_Call struct {
// CreateChannel is a helper method to define mock.On call
// - context1 context.Context
// - s string
-// - v *alertmanagertypes.Receiver
-func (_e *MockAlertmanager_Expecter) CreateChannel(context1 interface{}, s interface{}, v interface{}) *MockAlertmanager_CreateChannel_Call {
- return &MockAlertmanager_CreateChannel_Call{Call: _e.mock.On("CreateChannel", context1, s, v)}
+// - receiver *alertmanagertypes.Receiver
+func (_e *MockAlertmanager_Expecter) CreateChannel(context1 interface{}, s interface{}, receiver interface{}) *MockAlertmanager_CreateChannel_Call {
+ return &MockAlertmanager_CreateChannel_Call{Call: _e.mock.On("CreateChannel", context1, s, receiver)}
}
-func (_c *MockAlertmanager_CreateChannel_Call) Run(run func(context1 context.Context, s string, v *alertmanagertypes.Receiver)) *MockAlertmanager_CreateChannel_Call {
+func (_c *MockAlertmanager_CreateChannel_Call) Run(run func(context1 context.Context, s string, receiver *alertmanagertypes.Receiver)) *MockAlertmanager_CreateChannel_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
@@ -223,7 +223,7 @@ func (_c *MockAlertmanager_CreateChannel_Call) Return(channel *alertmanagertypes
return _c
}
-func (_c *MockAlertmanager_CreateChannel_Call) RunAndReturn(run func(context1 context.Context, s string, v *alertmanagertypes.Receiver) (*alertmanagertypes.Channel, error)) *MockAlertmanager_CreateChannel_Call {
+func (_c *MockAlertmanager_CreateChannel_Call) RunAndReturn(run func(context1 context.Context, s string, receiver *alertmanagertypes.Receiver) (*alertmanagertypes.Channel, error)) *MockAlertmanager_CreateChannel_Call {
_c.Call.Return(run)
return _c
}
@@ -291,6 +291,80 @@ func (_c *MockAlertmanager_CreateInhibitRules_Call) RunAndReturn(run func(ctx co
return _c
}
+// CreateNotificationChannel provides a mock function for the type MockAlertmanager
+func (_mock *MockAlertmanager) CreateNotificationChannel(context1 context.Context, s string, postableNotificationChannel *alertmanagertypes.PostableNotificationChannel) (*alertmanagertypes.Channel, error) {
+ ret := _mock.Called(context1, s, postableNotificationChannel)
+
+ if len(ret) == 0 {
+ panic("no return value specified for CreateNotificationChannel")
+ }
+
+ var r0 *alertmanagertypes.Channel
+ var r1 error
+ if returnFunc, ok := ret.Get(0).(func(context.Context, string, *alertmanagertypes.PostableNotificationChannel) (*alertmanagertypes.Channel, error)); ok {
+ return returnFunc(context1, s, postableNotificationChannel)
+ }
+ if returnFunc, ok := ret.Get(0).(func(context.Context, string, *alertmanagertypes.PostableNotificationChannel) *alertmanagertypes.Channel); ok {
+ r0 = returnFunc(context1, s, postableNotificationChannel)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*alertmanagertypes.Channel)
+ }
+ }
+ if returnFunc, ok := ret.Get(1).(func(context.Context, string, *alertmanagertypes.PostableNotificationChannel) error); ok {
+ r1 = returnFunc(context1, s, postableNotificationChannel)
+ } else {
+ r1 = ret.Error(1)
+ }
+ return r0, r1
+}
+
+// MockAlertmanager_CreateNotificationChannel_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreateNotificationChannel'
+type MockAlertmanager_CreateNotificationChannel_Call struct {
+ *mock.Call
+}
+
+// CreateNotificationChannel is a helper method to define mock.On call
+// - context1 context.Context
+// - s string
+// - postableNotificationChannel *alertmanagertypes.PostableNotificationChannel
+func (_e *MockAlertmanager_Expecter) CreateNotificationChannel(context1 interface{}, s interface{}, postableNotificationChannel interface{}) *MockAlertmanager_CreateNotificationChannel_Call {
+ return &MockAlertmanager_CreateNotificationChannel_Call{Call: _e.mock.On("CreateNotificationChannel", context1, s, postableNotificationChannel)}
+}
+
+func (_c *MockAlertmanager_CreateNotificationChannel_Call) Run(run func(context1 context.Context, s string, postableNotificationChannel *alertmanagertypes.PostableNotificationChannel)) *MockAlertmanager_CreateNotificationChannel_Call {
+ _c.Call.Run(func(args mock.Arguments) {
+ var arg0 context.Context
+ if args[0] != nil {
+ arg0 = args[0].(context.Context)
+ }
+ var arg1 string
+ if args[1] != nil {
+ arg1 = args[1].(string)
+ }
+ var arg2 *alertmanagertypes.PostableNotificationChannel
+ if args[2] != nil {
+ arg2 = args[2].(*alertmanagertypes.PostableNotificationChannel)
+ }
+ run(
+ arg0,
+ arg1,
+ arg2,
+ )
+ })
+ return _c
+}
+
+func (_c *MockAlertmanager_CreateNotificationChannel_Call) Return(channel *alertmanagertypes.Channel, err error) *MockAlertmanager_CreateNotificationChannel_Call {
+ _c.Call.Return(channel, err)
+ return _c
+}
+
+func (_c *MockAlertmanager_CreateNotificationChannel_Call) RunAndReturn(run func(context1 context.Context, s string, postableNotificationChannel *alertmanagertypes.PostableNotificationChannel) (*alertmanagertypes.Channel, error)) *MockAlertmanager_CreateNotificationChannel_Call {
+ _c.Call.Return(run)
+ return _c
+}
+
// CreateRoutePolicies provides a mock function for the type MockAlertmanager
func (_mock *MockAlertmanager) CreateRoutePolicies(ctx context.Context, routeRequests []*alertmanagertypes.PostableRoutePolicy) ([]*alertmanagertypes.GettableRoutePolicy, error) {
ret := _mock.Called(ctx, routeRequests)
@@ -1624,8 +1698,8 @@ func (_c *MockAlertmanager_TestAlert_Call) RunAndReturn(run func(ctx context.Con
}
// TestReceiver provides a mock function for the type MockAlertmanager
-func (_mock *MockAlertmanager) TestReceiver(context1 context.Context, s string, v *alertmanagertypes.Receiver) error {
- ret := _mock.Called(context1, s, v)
+func (_mock *MockAlertmanager) TestReceiver(context1 context.Context, s string, receiver *alertmanagertypes.Receiver) error {
+ ret := _mock.Called(context1, s, receiver)
if len(ret) == 0 {
panic("no return value specified for TestReceiver")
@@ -1633,7 +1707,7 @@ func (_mock *MockAlertmanager) TestReceiver(context1 context.Context, s string,
var r0 error
if returnFunc, ok := ret.Get(0).(func(context.Context, string, *alertmanagertypes.Receiver) error); ok {
- r0 = returnFunc(context1, s, v)
+ r0 = returnFunc(context1, s, receiver)
} else {
r0 = ret.Error(0)
}
@@ -1648,12 +1722,12 @@ type MockAlertmanager_TestReceiver_Call struct {
// TestReceiver is a helper method to define mock.On call
// - context1 context.Context
// - s string
-// - v *alertmanagertypes.Receiver
-func (_e *MockAlertmanager_Expecter) TestReceiver(context1 interface{}, s interface{}, v interface{}) *MockAlertmanager_TestReceiver_Call {
- return &MockAlertmanager_TestReceiver_Call{Call: _e.mock.On("TestReceiver", context1, s, v)}
+// - receiver *alertmanagertypes.Receiver
+func (_e *MockAlertmanager_Expecter) TestReceiver(context1 interface{}, s interface{}, receiver interface{}) *MockAlertmanager_TestReceiver_Call {
+ return &MockAlertmanager_TestReceiver_Call{Call: _e.mock.On("TestReceiver", context1, s, receiver)}
}
-func (_c *MockAlertmanager_TestReceiver_Call) Run(run func(context1 context.Context, s string, v *alertmanagertypes.Receiver)) *MockAlertmanager_TestReceiver_Call {
+func (_c *MockAlertmanager_TestReceiver_Call) Run(run func(context1 context.Context, s string, receiver *alertmanagertypes.Receiver)) *MockAlertmanager_TestReceiver_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
@@ -1681,7 +1755,7 @@ func (_c *MockAlertmanager_TestReceiver_Call) Return(err error) *MockAlertmanage
return _c
}
-func (_c *MockAlertmanager_TestReceiver_Call) RunAndReturn(run func(context1 context.Context, s string, v *alertmanagertypes.Receiver) error) *MockAlertmanager_TestReceiver_Call {
+func (_c *MockAlertmanager_TestReceiver_Call) RunAndReturn(run func(context1 context.Context, s string, receiver *alertmanagertypes.Receiver) error) *MockAlertmanager_TestReceiver_Call {
_c.Call.Return(run)
return _c
}
@@ -1750,8 +1824,8 @@ func (_c *MockAlertmanager_UpdateAllRoutePoliciesByRuleId_Call) RunAndReturn(run
}
// UpdateChannelByReceiverAndID provides a mock function for the type MockAlertmanager
-func (_mock *MockAlertmanager) UpdateChannelByReceiverAndID(context1 context.Context, s string, v *alertmanagertypes.Receiver, uUID valuer.UUID) error {
- ret := _mock.Called(context1, s, v, uUID)
+func (_mock *MockAlertmanager) UpdateChannelByReceiverAndID(context1 context.Context, s string, receiver *alertmanagertypes.Receiver, uUID valuer.UUID) error {
+ ret := _mock.Called(context1, s, receiver, uUID)
if len(ret) == 0 {
panic("no return value specified for UpdateChannelByReceiverAndID")
@@ -1759,7 +1833,7 @@ func (_mock *MockAlertmanager) UpdateChannelByReceiverAndID(context1 context.Con
var r0 error
if returnFunc, ok := ret.Get(0).(func(context.Context, string, *alertmanagertypes.Receiver, valuer.UUID) error); ok {
- r0 = returnFunc(context1, s, v, uUID)
+ r0 = returnFunc(context1, s, receiver, uUID)
} else {
r0 = ret.Error(0)
}
@@ -1774,13 +1848,13 @@ type MockAlertmanager_UpdateChannelByReceiverAndID_Call struct {
// UpdateChannelByReceiverAndID is a helper method to define mock.On call
// - context1 context.Context
// - s string
-// - v *alertmanagertypes.Receiver
+// - receiver *alertmanagertypes.Receiver
// - uUID valuer.UUID
-func (_e *MockAlertmanager_Expecter) UpdateChannelByReceiverAndID(context1 interface{}, s interface{}, v interface{}, uUID interface{}) *MockAlertmanager_UpdateChannelByReceiverAndID_Call {
- return &MockAlertmanager_UpdateChannelByReceiverAndID_Call{Call: _e.mock.On("UpdateChannelByReceiverAndID", context1, s, v, uUID)}
+func (_e *MockAlertmanager_Expecter) UpdateChannelByReceiverAndID(context1 interface{}, s interface{}, receiver interface{}, uUID interface{}) *MockAlertmanager_UpdateChannelByReceiverAndID_Call {
+ return &MockAlertmanager_UpdateChannelByReceiverAndID_Call{Call: _e.mock.On("UpdateChannelByReceiverAndID", context1, s, receiver, uUID)}
}
-func (_c *MockAlertmanager_UpdateChannelByReceiverAndID_Call) Run(run func(context1 context.Context, s string, v *alertmanagertypes.Receiver, uUID valuer.UUID)) *MockAlertmanager_UpdateChannelByReceiverAndID_Call {
+func (_c *MockAlertmanager_UpdateChannelByReceiverAndID_Call) Run(run func(context1 context.Context, s string, receiver *alertmanagertypes.Receiver, uUID valuer.UUID)) *MockAlertmanager_UpdateChannelByReceiverAndID_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
@@ -1813,7 +1887,7 @@ func (_c *MockAlertmanager_UpdateChannelByReceiverAndID_Call) Return(err error)
return _c
}
-func (_c *MockAlertmanager_UpdateChannelByReceiverAndID_Call) RunAndReturn(run func(context1 context.Context, s string, v *alertmanagertypes.Receiver, uUID valuer.UUID) error) *MockAlertmanager_UpdateChannelByReceiverAndID_Call {
+func (_c *MockAlertmanager_UpdateChannelByReceiverAndID_Call) RunAndReturn(run func(context1 context.Context, s string, receiver *alertmanagertypes.Receiver, uUID valuer.UUID) error) *MockAlertmanager_UpdateChannelByReceiverAndID_Call {
_c.Call.Return(run)
return _c
}
@@ -1965,6 +2039,52 @@ func (_c *MockHandler_CreateChannel_Call) RunAndReturn(run func(responseWriter h
return _c
}
+// CreateNotificationChannel provides a mock function for the type MockHandler
+func (_mock *MockHandler) CreateNotificationChannel(responseWriter http.ResponseWriter, request *http.Request) {
+ _mock.Called(responseWriter, request)
+ return
+}
+
+// MockHandler_CreateNotificationChannel_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreateNotificationChannel'
+type MockHandler_CreateNotificationChannel_Call struct {
+ *mock.Call
+}
+
+// CreateNotificationChannel is a helper method to define mock.On call
+// - responseWriter http.ResponseWriter
+// - request *http.Request
+func (_e *MockHandler_Expecter) CreateNotificationChannel(responseWriter interface{}, request interface{}) *MockHandler_CreateNotificationChannel_Call {
+ return &MockHandler_CreateNotificationChannel_Call{Call: _e.mock.On("CreateNotificationChannel", responseWriter, request)}
+}
+
+func (_c *MockHandler_CreateNotificationChannel_Call) Run(run func(responseWriter http.ResponseWriter, request *http.Request)) *MockHandler_CreateNotificationChannel_Call {
+ _c.Call.Run(func(args mock.Arguments) {
+ var arg0 http.ResponseWriter
+ if args[0] != nil {
+ arg0 = args[0].(http.ResponseWriter)
+ }
+ var arg1 *http.Request
+ if args[1] != nil {
+ arg1 = args[1].(*http.Request)
+ }
+ run(
+ arg0,
+ arg1,
+ )
+ })
+ return _c
+}
+
+func (_c *MockHandler_CreateNotificationChannel_Call) Return() *MockHandler_CreateNotificationChannel_Call {
+ _c.Call.Return()
+ return _c
+}
+
+func (_c *MockHandler_CreateNotificationChannel_Call) RunAndReturn(run func(responseWriter http.ResponseWriter, request *http.Request)) *MockHandler_CreateNotificationChannel_Call {
+ _c.Run(run)
+ return _c
+}
+
// CreateRoutePolicy provides a mock function for the type MockHandler
func (_mock *MockHandler) CreateRoutePolicy(responseWriter http.ResponseWriter, request *http.Request) {
_mock.Called(responseWriter, request)
diff --git a/pkg/alertmanager/handler.go b/pkg/alertmanager/handler.go
index b93a71c709..afc94de0ef 100644
--- a/pkg/alertmanager/handler.go
+++ b/pkg/alertmanager/handler.go
@@ -19,6 +19,8 @@ type Handler interface {
DeleteChannelByID(http.ResponseWriter, *http.Request)
+ CreateNotificationChannel(http.ResponseWriter, *http.Request)
+
GetAllRoutePolicies(http.ResponseWriter, *http.Request)
GetRoutePolicyByID(http.ResponseWriter, *http.Request)
diff --git a/pkg/alertmanager/signozalertmanager/handler_channel.go b/pkg/alertmanager/signozalertmanager/handler_channel.go
new file mode 100644
index 0000000000..dd514ea10a
--- /dev/null
+++ b/pkg/alertmanager/signozalertmanager/handler_channel.go
@@ -0,0 +1,43 @@
+package signozalertmanager
+
+import (
+ "context"
+ "net/http"
+ "time"
+
+ "github.com/SigNoz/signoz/pkg/http/binding"
+ "github.com/SigNoz/signoz/pkg/http/render"
+ "github.com/SigNoz/signoz/pkg/types/alertmanagertypes"
+ "github.com/SigNoz/signoz/pkg/types/authtypes"
+)
+
+func (handler *handler) CreateNotificationChannel(rw http.ResponseWriter, req *http.Request) {
+ ctx, cancel := context.WithTimeout(req.Context(), 30*time.Second)
+ defer cancel()
+
+ claims, err := authtypes.ClaimsFromContext(ctx)
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ postable := new(alertmanagertypes.PostableNotificationChannel)
+ if err := binding.JSON.BindBody(req.Body, postable); err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ channel, err := handler.alertmanager.CreateNotificationChannel(ctx, claims.OrgID, postable)
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ gettable, err := channel.ToGettableNotificationChannel()
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ render.Success(rw, http.StatusCreated, gettable)
+}
diff --git a/pkg/alertmanager/signozalertmanager/provider.go b/pkg/alertmanager/signozalertmanager/provider.go
index 6c6fb3ad56..4e7bf71fcb 100644
--- a/pkg/alertmanager/signozalertmanager/provider.go
+++ b/pkg/alertmanager/signozalertmanager/provider.go
@@ -244,6 +244,40 @@ func (provider *provider) CreateChannel(ctx context.Context, orgID string, recei
return channel, nil
}
+func (provider *provider) CreateNotificationChannel(ctx context.Context, orgID string, postable *alertmanagertypes.PostableNotificationChannel) (*alertmanagertypes.Channel, error) {
+ receiver, err := postable.ToReceiver()
+ if err != nil {
+ return nil, err
+ }
+
+ config, err := provider.configStore.Get(ctx, orgID)
+ if err != nil {
+ return nil, err
+ }
+
+ if err := config.SetGlobalConfig(provider.config.Signoz.Global); err != nil {
+ return nil, err
+ }
+
+ if err := config.CreateReceiverV2(receiver); err != nil {
+ return nil, err
+ }
+
+ channel, err := alertmanagertypes.NewChannelFromReceiverWithName(receiver, postable.Name, orgID)
+ if err != nil {
+ return nil, err
+ }
+
+ err = provider.configStore.CreateChannel(ctx, channel, alertmanagertypes.WithCb(func(ctx context.Context) error {
+ return provider.configStore.Set(ctx, config)
+ }))
+ if err != nil {
+ return nil, err
+ }
+
+ return channel, nil
+}
+
func (provider *provider) Config() alertmanagerserver.Config {
return provider.config.Signoz.Config
}
diff --git a/pkg/apiserver/signozapiserver/alertmanager.go b/pkg/apiserver/signozapiserver/alertmanager.go
index 6c7c70be1e..c584eff518 100644
--- a/pkg/apiserver/signozapiserver/alertmanager.go
+++ b/pkg/apiserver/signozapiserver/alertmanager.go
@@ -6,6 +6,8 @@ import (
"github.com/SigNoz/signoz/pkg/http/handler"
"github.com/SigNoz/signoz/pkg/types"
"github.com/SigNoz/signoz/pkg/types/alertmanagertypes"
+ "github.com/SigNoz/signoz/pkg/types/authtypes"
+ "github.com/SigNoz/signoz/pkg/types/coretypes"
"github.com/gorilla/mux"
)
@@ -129,6 +131,33 @@ func (provider *provider) addAlertmanagerRoutes(router *mux.Router) error {
return err
}
+ if err := router.Handle("/api/v2/notification_channels", handler.New(
+ provider.authzMiddleware.CheckResources(provider.alertmanagerHandler.CreateNotificationChannel, authtypes.SigNozAdminRoleName),
+ handler.OpenAPIDef{
+ ID: "CreateNotificationChannel",
+ Tags: []string{"channels"},
+ Summary: "Create notification channel",
+ Description: "This endpoint creates a notification channel",
+ Request: new(alertmanagertypes.PostableNotificationChannel),
+ RequestContentType: "application/json",
+ Response: new(alertmanagertypes.GettableNotificationChannel),
+ ResponseContentType: "application/json",
+ SuccessStatusCode: http.StatusCreated,
+ ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusConflict},
+ Deprecated: false,
+ SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceNotificationChannel.Scope(coretypes.VerbCreate)}),
+ },
+ handler.WithResourceDefs(handler.BasicResourceDef{
+ Resource: coretypes.ResourceMetaResourceNotificationChannel,
+ 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/route_policies", handler.New(provider.authzMiddleware.ViewAccess(provider.alertmanagerHandler.GetAllRoutePolicies), handler.OpenAPIDef{
ID: "GetAllRoutePolicies",
Tags: []string{"routepolicies"},
diff --git a/pkg/types/alertmanagertypes/channelapi.go b/pkg/types/alertmanagertypes/channelapi.go
new file mode 100644
index 0000000000..51bd23932f
--- /dev/null
+++ b/pkg/types/alertmanagertypes/channelapi.go
@@ -0,0 +1,106 @@
+package alertmanagertypes
+
+import (
+ "bytes"
+ "encoding/json"
+ "strings"
+ "time"
+
+ "github.com/SigNoz/signoz/pkg/errors"
+ "github.com/SigNoz/signoz/pkg/valuer"
+ "k8s.io/apimachinery/pkg/util/validation"
+)
+
+// ════════════════════════════════════════════════════════════════════════
+// Postable
+// ════════════════════════════════════════════════════════════════════════
+
+// Name is the immutable DNS1123 identity references will point at; DisplayName is the
+// free-text label.
+type PostableNotificationChannel struct {
+ Name string `json:"name"`
+ GenerateName bool `json:"generateName"`
+ DisplayName string `json:"displayName"`
+ Config ChannelConfig `json:"config" required:"true"`
+}
+
+func (p *PostableNotificationChannel) UnmarshalJSON(data []byte) error {
+ dec := json.NewDecoder(bytes.NewReader(data))
+ dec.DisallowUnknownFields()
+
+ type alias PostableNotificationChannel
+ var tmp alias
+ if err := dec.Decode(&tmp); err != nil {
+ if errors.Ast(err, errors.TypeInvalidInput) {
+ return err
+ }
+ return errors.WrapInvalidInputf(err, ErrCodeAlertmanagerChannelInvalid, "%s", err.Error())
+ }
+
+ *p = PostableNotificationChannel(tmp)
+
+ if !p.GenerateName && p.DisplayName == "" {
+ p.DisplayName = p.Name
+ }
+
+ if err := p.Validate(); err != nil {
+ return err
+ }
+
+ if p.GenerateName {
+ p.Name = generateChannelName(p.DisplayName)
+ }
+
+ return nil
+}
+
+func (p *PostableNotificationChannel) Validate() error {
+ if err := p.validateName(); err != nil {
+ return err
+ }
+
+ if p.DisplayName == "" {
+ return errors.NewInvalidInputf(ErrCodeAlertmanagerChannelInvalid, "displayName is required")
+ }
+
+ if p.Name == DefaultReceiverName || p.DisplayName == DefaultReceiverName {
+ return errors.NewInvalidInputf(ErrCodeAlertmanagerChannelInvalid, "name %q is reserved", DefaultReceiverName)
+ }
+
+ return p.Config.Validate()
+}
+
+func (p *PostableNotificationChannel) validateName() error {
+ if p.GenerateName {
+ if p.Name != "" {
+ return errors.NewInvalidInputf(ErrCodeAlertmanagerChannelInvalid, "name must be empty when generateName is true, got %q", p.Name)
+ }
+ if p.DisplayName == "" {
+ return errors.NewInvalidInputf(ErrCodeAlertmanagerChannelInvalid, "displayName is required when generateName is true")
+ }
+ return nil
+ }
+
+ if p.Name == "" {
+ return errors.NewInvalidInputf(ErrCodeAlertmanagerChannelInvalid, "name is required")
+ }
+
+ if errs := validation.IsDNS1123Label(p.Name); len(errs) > 0 {
+ return errors.NewInvalidInputf(ErrCodeAlertmanagerChannelInvalid, "name %q is invalid: %s", p.Name, strings.Join(errs, "; "))
+ }
+
+ return nil
+}
+
+// ════════════════════════════════════════════════════════════════════════
+// Gettable
+// ════════════════════════════════════════════════════════════════════════
+
+type GettableNotificationChannel struct {
+ Name string `json:"name" required:"true"`
+ DisplayName string `json:"displayName" required:"true"`
+ Config ChannelConfig `json:"config" required:"true"`
+ ID valuer.UUID `json:"id" required:"true"`
+ CreatedAt time.Time `json:"createdAt" required:"true"`
+ UpdatedAt time.Time `json:"updatedAt" required:"true"`
+}
diff --git a/pkg/types/alertmanagertypes/channelapi_test.go b/pkg/types/alertmanagertypes/channelapi_test.go
new file mode 100644
index 0000000000..96d3d3645c
--- /dev/null
+++ b/pkg/types/alertmanagertypes/channelapi_test.go
@@ -0,0 +1,138 @@
+package alertmanagertypes
+
+import (
+ "encoding/json"
+ "testing"
+
+ "github.com/SigNoz/signoz/pkg/valuer"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+ "k8s.io/apimachinery/pkg/util/validation"
+)
+
+func TestPostableChannelUnmarshalJSONRejectsBadInput(t *testing.T) {
+ testCases := []struct {
+ description string
+ body string
+ }{
+ {
+ description: "empty kind",
+ body: `{"name":"x","config":{"spec":{"to":"[email protected]"}}}`,
+ },
+ {
+ description: "missing spec",
+ body: `{"name":"x","config":{"kind":"slack"}}`,
+ },
+ {
+ // A custom UnmarshalJSON receives raw bytes, so the request body's own
+ // DisallowUnknownFields never reaches inside config.
+ description: "unknown field alongside kind and spec",
+ body: `{"name":"x","config":{"kind":"slack","bogus":1,"spec":{"apiUrl":"https://a","channel":"#c","title":"slack title","text":"slack text"}}}`,
+ },
+ }
+
+ for _, testCase := range testCases {
+ t.Run(testCase.description, func(t *testing.T) {
+ var postable PostableNotificationChannel
+ assert.Error(t, json.Unmarshal([]byte(testCase.body), &postable))
+ })
+ }
+}
+
+func TestPostableChannelValidate(t *testing.T) {
+ testCases := []struct {
+ description string
+ postable PostableNotificationChannel
+ }{
+ {
+ description: "webhook password without username",
+ postable: PostableNotificationChannel{
+ Name: "hook",
+ DisplayName: "hook",
+ Config: ChannelConfig{Kind: ChannelKindWebhook, Spec: &ChannelWebhookConfig{URL: "https://a", Password: "p"}},
+ },
+ },
+ {
+ description: "jira with an unparseable reopen duration",
+ postable: PostableNotificationChannel{
+ Name: "jira",
+ DisplayName: "jira",
+ Config: ChannelConfig{Kind: ChannelKindJira, Spec: &ChannelJiraConfig{
+ Site: "https://acme.atlassian.net", Project: "OPS", IssueType: "Bug",
+ Email: "[email protected]", APIToken: "api-token",
+ Summary: valuer.MustNewUnsetOrNonEmptyString("jira summary"), Description: valuer.MustNewUnsetOrNonEmptyString("jira description"), ReopenDuration: valuer.MustNewUnsetOrNonEmptyString("three days"),
+ }},
+ },
+ },
+ {
+ description: "nil spec",
+ postable: PostableNotificationChannel{
+ Name: "oncall",
+ DisplayName: "oncall",
+ Config: ChannelConfig{Kind: ChannelKindSlack},
+ },
+ },
+ }
+
+ for _, testCase := range testCases {
+ t.Run(testCase.description, func(t *testing.T) {
+ assert.Error(t, testCase.postable.Validate())
+ })
+ }
+}
+
+// A display name that slugifies to nothing still has to yield a DNS1123 label,
+// because the generated name is what every other resource references.
+func TestPostableChannelUnmarshalJSONGeneratesANameFromAnUnslugifiableDisplayName(t *testing.T) {
+ var postable PostableNotificationChannel
+ require.NoError(t, json.Unmarshal([]byte(`{"generateName":true,"displayName":"###","config":{"kind":"slack","spec":{"apiUrl":"https://a","channel":"#c","title":"slack title","text":"slack text"}}}`), &postable))
+
+ assert.Equal(t, "###", postable.DisplayName)
+ assert.Empty(t, validation.IsDNS1123Label(postable.Name))
+}
+
+// A GettableNotificationChannel must marshal to the PostableNotificationChannel shape plus the
+// server-owned fields, so a client can read one and post it back.
+func TestGettableChannelMarshalsAsPostablePlusServerFields(t *testing.T) {
+ gettable := GettableNotificationChannel{
+ Name: "oncall",
+ DisplayName: "#oncall",
+ Config: ChannelConfig{Kind: ChannelKindSlack, Spec: &ChannelSlackConfig{APIURL: "https://a", Channel: "#c", Title: valuer.MustNewUnsetOrNonEmptyString("slack title"), Text: valuer.MustNewUnsetOrNonEmptyString("slack text")}},
+ }
+
+ raw, err := json.Marshal(gettable)
+ require.NoError(t, err)
+
+ var decoded map[string]any
+ require.NoError(t, json.Unmarshal(raw, &decoded))
+
+ assert.ElementsMatch(t, []string{"name", "displayName", "config", "id", "createdAt", "updatedAt"}, channelKeysOf(decoded))
+
+ config, ok := decoded["config"].(map[string]any)
+ require.True(t, ok)
+ assert.ElementsMatch(t, []string{"kind", "spec"}, channelKeysOf(config))
+ assert.Equal(t, "slack", config["kind"])
+}
+
+// Only a caller assembling the struct can pair a kind with another kind's spec;
+// a decoded config builds the spec from the kind. Left unchecked the conversion
+// to a receiver, which switches on the spec's type, would write a channel of the
+// spec's kind under the declared one.
+func TestChannelConfigValidateRejectsSpecOfAnotherKind(t *testing.T) {
+ config := ChannelConfig{
+ Kind: ChannelKindSlack,
+ Spec: &ChannelEmailConfig{To: "[email protected]", HTML: valuer.MustNewUnsetOrNonEmptyString("<p>body</p>")},
+ }
+
+ err := config.Validate()
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), "does not match kind")
+}
+
+func channelKeysOf(m map[string]any) []string {
+ keys := make([]string, 0, len(m))
+ for key := range m {
+ keys = append(keys, key)
+ }
+ return keys
+}
diff --git a/pkg/types/alertmanagertypes/channelconfig.go b/pkg/types/alertmanagertypes/channelconfig.go
new file mode 100644
index 0000000000..eed0ba00ea
--- /dev/null
+++ b/pkg/types/alertmanagertypes/channelconfig.go
@@ -0,0 +1,1193 @@
+package alertmanagertypes
+
+import (
+ "bytes"
+ "encoding/json"
+ "maps"
+ "net/textproto"
+ "net/url"
+ "reflect"
+ "slices"
+ "strings"
+
+ "github.com/SigNoz/signoz/pkg/errors"
+ "github.com/SigNoz/signoz/pkg/valuer"
+ "github.com/prometheus/alertmanager/config"
+ commoncfg "github.com/prometheus/common/config"
+ "github.com/prometheus/common/model"
+ "github.com/swaggest/jsonschema-go"
+)
+
+var (
+ ErrCodeChannelUnsupportedKind = errors.MustNewCode("channel_unsupported_kind")
+)
+
+// ════════════════════════════════════════════════════════════════════════
+// Kind
+// ════════════════════════════════════════════════════════════════════════
+
+// ChannelKind selects which ChannelSpec a channel carries and which notifier
+// integration is built for it.
+type ChannelKind struct {
+ valuer.String
+}
+
+var (
+ ChannelKindSlack = ChannelKind{valuer.NewString("slack")}
+ ChannelKindEmail = ChannelKind{valuer.NewString("email")}
+ ChannelKindWebhook = ChannelKind{valuer.NewString("webhook")}
+ ChannelKindPagerduty = ChannelKind{valuer.NewString("pagerduty")}
+ ChannelKindOpsgenie = ChannelKind{valuer.NewString("opsgenie")}
+ ChannelKindMSTeams = ChannelKind{valuer.NewString("msteams")}
+ ChannelKindGoogleChat = ChannelKind{valuer.NewString("googlechat")}
+ ChannelKindJira = ChannelKind{valuer.NewString("jira")}
+ ChannelKindJSMOps = ChannelKind{valuer.NewString("jsmops")}
+ ChannelKindIncidentIO = ChannelKind{valuer.NewString("incidentio")}
+)
+
+func (ChannelKind) Enum() []any {
+ kinds := make([]any, 0, len(channelKinds))
+ for _, channelKind := range channelKinds {
+ kinds = append(kinds, channelKind.kind)
+ }
+ return kinds
+}
+
+func (t ChannelKind) IsValid() bool {
+ return slices.ContainsFunc(t.Enum(), func(v any) bool { return v == t })
+}
+
+func ErrUnsupportedChannelKind(s string) error {
+ return errors.Newf(
+ errors.TypeInvalidInput,
+ ErrCodeChannelUnsupportedKind,
+ "unknown notification channel kind %q; allowed values: %s",
+ s, allowedValuesForChannelKind(),
+ )
+}
+
+// ════════════════════════════════════════════════════════════════════════
+// Union
+// ════════════════════════════════════════════════════════════════════════
+
+// ChannelConfig is the discriminated union of per-kind configurations. The
+// envelope sits on config rather than the resource root, so clients narrow on
+// config.kind instead of every request and response flavor becoming a oneOf.
+type ChannelConfig struct {
+ Kind ChannelKind `json:"kind" required:"true"`
+ Spec any `json:"spec" required:"true"`
+}
+
+func (c ChannelConfig) Validate() error {
+ newSpec, ok := newChannelSpec(c.Kind)
+ if !ok {
+ return ErrUnsupportedChannelKind(c.Kind.StringValue())
+ }
+
+ if c.Spec == nil {
+ return errors.NewInvalidInputf(ErrCodeAlertmanagerChannelInvalid, "config.spec is required")
+ }
+
+ spec, ok := c.Spec.(ChannelSpec)
+ if !ok {
+ return errors.NewInternalf(errors.CodeInternal, "config.spec was not decoded into a known type")
+ }
+
+ // A decoded config cannot disagree, because UnmarshalJSON builds the spec
+ // from the kind. A caller assembling the struct can, and the conversion to a
+ // receiver dispatches on the spec, so a mismatch would silently outrank the
+ // declared kind.
+ if reflect.TypeOf(spec) != reflect.TypeOf(newSpec()) {
+ return errors.NewInternalf(errors.CodeInternal, "config.spec does not match kind %q", c.Kind.StringValue())
+ }
+
+ return spec.Validate()
+}
+
+func (c *ChannelConfig) UnmarshalJSON(data []byte) error {
+ channelKindString, specJSON, err := extractKindAndSpec(data)
+ if err != nil {
+ return err
+ }
+
+ factory, ok := newChannelSpec(ChannelKind{valuer.NewString(channelKindString)})
+ if !ok {
+ return ErrUnsupportedChannelKind(channelKindString)
+ }
+
+ spec, err := decodeChannelSpec(specJSON, factory(), channelKindString)
+ if err != nil {
+ return err
+ }
+
+ c.Kind = ChannelKind{valuer.NewString(channelKindString)}
+ c.Spec = *spec
+
+ return nil
+}
+
+// ChannelConfigVariant names one branch of the union. Each instantiation becomes
+// its own OpenAPI component with kind pinned to the one value it accepts.
+type ChannelConfigVariant[S any] struct {
+ Kind string `json:"kind" required:"true"`
+ Spec S `json:"spec" required:"true"`
+}
+
+func (v ChannelConfigVariant[S]) PrepareJSONSchema(s *jsonschema.Schema) error {
+ return restrictKindToOneValue(s, v.Kind)
+}
+
+var (
+ _ jsonschema.OneOfExposer = ChannelConfig{}
+ _ jsonschema.Preparer = ChannelConfig{}
+)
+
+func (ChannelConfig) JSONSchemaOneOf() []any {
+ return []any{
+ ChannelConfigVariant[ChannelSlackConfig]{Kind: ChannelKindSlack.StringValue()},
+ ChannelConfigVariant[ChannelEmailConfig]{Kind: ChannelKindEmail.StringValue()},
+ ChannelConfigVariant[ChannelWebhookConfig]{Kind: ChannelKindWebhook.StringValue()},
+ ChannelConfigVariant[ChannelPagerdutyConfig]{Kind: ChannelKindPagerduty.StringValue()},
+ ChannelConfigVariant[ChannelOpsgenieConfig]{Kind: ChannelKindOpsgenie.StringValue()},
+ ChannelConfigVariant[ChannelMSTeamsConfig]{Kind: ChannelKindMSTeams.StringValue()},
+ ChannelConfigVariant[ChannelGoogleChatConfig]{Kind: ChannelKindGoogleChat.StringValue()},
+ ChannelConfigVariant[ChannelJiraConfig]{Kind: ChannelKindJira.StringValue()},
+ ChannelConfigVariant[ChannelJSMOpsConfig]{Kind: ChannelKindJSMOps.StringValue()},
+ ChannelConfigVariant[ChannelIncidentIOConfig]{Kind: ChannelKindIncidentIO.StringValue()},
+ }
+}
+
+// PrepareJSONSchema marks the envelope with x-signoz-discriminator, which
+// signoz.attachDiscriminators promotes to a real discriminator after reflection.
+func (ChannelConfig) PrepareJSONSchema(s *jsonschema.Schema) error {
+ return markDiscriminator(s, "kind", map[string]string{
+ ChannelKindSlack.StringValue(): channelVariantRef("ChannelSlackConfig"),
+ ChannelKindEmail.StringValue(): channelVariantRef("ChannelEmailConfig"),
+ ChannelKindWebhook.StringValue(): channelVariantRef("ChannelWebhookConfig"),
+ ChannelKindPagerduty.StringValue(): channelVariantRef("ChannelPagerdutyConfig"),
+ ChannelKindOpsgenie.StringValue(): channelVariantRef("ChannelOpsgenieConfig"),
+ ChannelKindMSTeams.StringValue(): channelVariantRef("ChannelMSTeamsConfig"),
+ ChannelKindGoogleChat.StringValue(): channelVariantRef("ChannelGoogleChatConfig"),
+ ChannelKindJira.StringValue(): channelVariantRef("ChannelJiraConfig"),
+ ChannelKindJSMOps.StringValue(): channelVariantRef("ChannelJSMOpsConfig"),
+ ChannelKindIncidentIO.StringValue(): channelVariantRef("ChannelIncidentIOConfig"),
+ })
+}
+
+// ════════════════════════════════════════════════════════════════════════
+// Specs
+// ════════════════════════════════════════════════════════════════════════
+
+type ChannelSpec interface {
+ Validate() error
+ toUndefaultedReceiver(displayName string) (*Receiver, error)
+}
+
+type ChannelSlackConfig struct {
+ SendResolved *bool `json:"sendResolved,omitempty"`
+ APIURL string `json:"apiUrl" required:"true"`
+ Channel string `json:"channel"`
+ Title valuer.UnsetOrNonEmptyString `json:"title"`
+ Text valuer.UnsetOrNonEmptyString `json:"text"`
+}
+
+func (c ChannelSlackConfig) Validate() error {
+ if c.APIURL == "" {
+ return errors.NewInvalidInputf(ErrCodeAlertmanagerChannelInvalid, "config.spec.apiUrl is required for a slack channel")
+ }
+
+ return nil
+}
+
+func (c ChannelSlackConfig) toUndefaultedReceiver(displayName string) (*Receiver, error) {
+ apiURL, err := parseSecretURL(c.APIURL)
+ if err != nil {
+ return nil, err
+ }
+
+ return &Receiver{Receiver: &config.Receiver{
+ Name: displayName,
+ SlackConfigs: []*config.SlackConfig{{
+ NotifierConfig: config.NotifierConfig{VSendResolved: resolveSendResolved(c.SendResolved, config.DefaultSlackConfig.VSendResolved)},
+ APIURL: apiURL,
+ Channel: c.Channel,
+ Title: c.Title.StringValue(),
+ Text: c.Text.StringValue(),
+ }},
+ }}, nil
+}
+
+func newChannelSlackConfigFromReceiver(name string, receiver *Receiver) (ChannelSpec, error) {
+ slack := receiver.SlackConfigs[0]
+ sendResolved := slack.VSendResolved
+
+ if err := rejectAnyHTTPAuth(name, slack.HTTPConfig); err != nil {
+ return nil, err
+ }
+
+ return &ChannelSlackConfig{
+ SendResolved: &sendResolved,
+ APIURL: formatSecretURL(slack.APIURL),
+ Channel: slack.Channel,
+ Title: valuer.UnsetIfEmpty(slack.Title),
+ Text: valuer.UnsetIfEmpty(slack.Text),
+ }, nil
+}
+
+// ChannelEmailConfig carries no SMTP transport fields: the smarthost,
+// credentials and TLS settings come from the deployment's global config, so a
+// channel can only choose recipients and body.
+type ChannelEmailConfig struct {
+ SendResolved *bool `json:"sendResolved,omitempty"`
+ To string `json:"to" required:"true"`
+ HTML valuer.UnsetOrNonEmptyString `json:"html"`
+ Headers map[string]string `json:"headers,omitempty"`
+}
+
+func (c ChannelEmailConfig) Validate() error {
+ if c.To == "" {
+ return errors.NewInvalidInputf(ErrCodeAlertmanagerChannelInvalid, "config.spec.to is required for an email channel")
+ }
+
+ // A read reports header names as textproto canonicalizes them, turning
+ // "subject" into "Subject", so a name that is not already in that form is
+ // rejected rather than answered with one the caller never sent.
+ for _, header := range slices.Sorted(maps.Keys(c.Headers)) {
+ if canonical := textproto.CanonicalMIMEHeaderKey(header); canonical != header {
+ return errors.NewInvalidInputf(ErrCodeAlertmanagerChannelInvalid, "config.spec.headers name %q must be written as %q", header, canonical)
+ }
+ }
+
+ return nil
+}
+
+func (c ChannelEmailConfig) toUndefaultedReceiver(displayName string) (*Receiver, error) {
+ return &Receiver{Receiver: &config.Receiver{
+ Name: displayName,
+ EmailConfigs: []*config.EmailConfig{{
+ NotifierConfig: config.NotifierConfig{VSendResolved: resolveSendResolved(c.SendResolved, config.DefaultEmailConfig.VSendResolved)},
+ To: c.To,
+ HTML: c.HTML.StringValue(),
+ Headers: c.Headers,
+ }},
+ }}, nil
+}
+
+func newChannelEmailConfigFromReceiver(_ string, receiver *Receiver) (ChannelSpec, error) {
+ email := receiver.EmailConfigs[0]
+ sendResolved := email.VSendResolved
+
+ return &ChannelEmailConfig{
+ SendResolved: &sendResolved,
+ To: email.To,
+ HTML: valuer.UnsetIfEmpty(email.HTML),
+ Headers: email.Headers,
+ }, nil
+}
+
+// ChannelWebhookConfig splits apart the two authentication modes the legacy API
+// overloaded onto one password field, where an empty username meant the password
+// was really a bearer token.
+type ChannelWebhookConfig struct {
+ SendResolved *bool `json:"sendResolved,omitempty"`
+ URL string `json:"url" required:"true"`
+ Username string `json:"username"`
+ Password string `json:"password"`
+ BearerToken string `json:"bearerToken"`
+}
+
+func (c ChannelWebhookConfig) Validate() error {
+ if c.URL == "" {
+ return errors.NewInvalidInputf(ErrCodeAlertmanagerChannelInvalid, "config.spec.url is required for a webhook channel")
+ }
+
+ usesBasicAuth := c.Username != "" || c.Password != ""
+
+ if usesBasicAuth && c.BearerToken != "" {
+ return errors.NewInvalidInputf(ErrCodeAlertmanagerChannelInvalid, "config.spec.bearerToken cannot be combined with config.spec.username or config.spec.password")
+ }
+
+ if usesBasicAuth && (c.Username == "" || c.Password == "") {
+ return errors.NewInvalidInputf(ErrCodeAlertmanagerChannelInvalid, "config.spec.username and config.spec.password must both be set for basic auth")
+ }
+
+ return nil
+}
+
+func (c ChannelWebhookConfig) toUndefaultedReceiver(displayName string) (*Receiver, error) {
+ webhook := &config.WebhookConfig{
+ NotifierConfig: config.NotifierConfig{VSendResolved: resolveSendResolved(c.SendResolved, config.DefaultWebhookConfig.VSendResolved)},
+ URL: config.SecretTemplateURL(c.URL),
+ }
+
+ // Seeded from upstream's default rather than a zero value: FollowRedirects
+ // and EnableHTTP2 marshal unconditionally, so a zero value would persist
+ // them as false and read back as a config ChannelWebhookConfig cannot represent.
+ switch {
+ case c.Username != "":
+ httpConfig := commoncfg.DefaultHTTPClientConfig
+ httpConfig.BasicAuth = &commoncfg.BasicAuth{
+ Username: c.Username,
+ Password: commoncfg.Secret(c.Password),
+ }
+ webhook.HTTPConfig = &httpConfig
+ case c.BearerToken != "":
+ httpConfig := commoncfg.DefaultHTTPClientConfig
+ httpConfig.Authorization = &commoncfg.Authorization{
+ Type: bearerAuthorizationType,
+ Credentials: commoncfg.Secret(c.BearerToken),
+ }
+ webhook.HTTPConfig = &httpConfig
+ }
+
+ return &Receiver{Receiver: &config.Receiver{
+ Name: displayName,
+ WebhookConfigs: []*config.WebhookConfig{webhook},
+ }}, nil
+}
+
+func newChannelWebhookConfigFromReceiver(name string, receiver *Receiver) (ChannelSpec, error) {
+ upstream := receiver.WebhookConfigs[0]
+ sendResolved := upstream.VSendResolved
+ if err := rejectUnsupportedHTTPConfig(name, upstream.HTTPConfig); err != nil {
+ return nil, err
+ }
+
+ if err := rejectHTTPBasicAuthBeyondPassword(name, upstream.HTTPConfig); err != nil {
+ return nil, err
+ }
+
+ if err := rejectHTTPAuthorizationBeyondBearer(name, upstream.HTTPConfig); err != nil {
+ return nil, err
+ }
+
+ webhook := &ChannelWebhookConfig{
+ SendResolved: &sendResolved,
+ URL: string(upstream.URL),
+ }
+
+ if upstream.HTTPConfig != nil {
+ if basicAuth := upstream.HTTPConfig.BasicAuth; basicAuth != nil {
+ webhook.Username = basicAuth.Username
+ webhook.Password = string(basicAuth.Password)
+ }
+ if authorization := upstream.HTTPConfig.Authorization; authorization != nil {
+ webhook.BearerToken = string(authorization.Credentials)
+ }
+ }
+
+ return webhook, nil
+}
+
+type ChannelPagerdutyConfig struct {
+ SendResolved *bool `json:"sendResolved,omitempty"`
+ RoutingKey string `json:"routingKey" required:"true"`
+ URL string `json:"url"`
+ Source valuer.UnsetOrNonEmptyString `json:"source"`
+ Client valuer.UnsetOrNonEmptyString `json:"client"`
+ ClientURL valuer.UnsetOrNonEmptyString `json:"clientUrl"`
+ Description valuer.UnsetOrNonEmptyString `json:"description"`
+ Severity string `json:"severity"`
+ Component string `json:"component"`
+ Group string `json:"group"`
+ Class string `json:"class"`
+ Details map[string]string `json:"details,omitempty"`
+}
+
+func (c ChannelPagerdutyConfig) Validate() error {
+ if c.RoutingKey == "" {
+ return errors.NewInvalidInputf(ErrCodeAlertmanagerChannelInvalid, "config.spec.routingKey is required for a pagerduty channel")
+ }
+
+ return nil
+}
+
+func (c ChannelPagerdutyConfig) toUndefaultedReceiver(displayName string) (*Receiver, error) {
+ var eventsURL *config.URL
+ if c.URL != "" {
+ parsed, err := parseUpstreamURL(c.URL)
+ if err != nil {
+ return nil, err
+ }
+ eventsURL = parsed
+ }
+
+ return &Receiver{Receiver: &config.Receiver{
+ Name: displayName,
+ PagerdutyConfigs: []*config.PagerdutyConfig{{
+ NotifierConfig: config.NotifierConfig{VSendResolved: resolveSendResolved(c.SendResolved, config.DefaultPagerdutyConfig.VSendResolved)},
+ RoutingKey: config.Secret(c.RoutingKey),
+ URL: eventsURL,
+ Source: c.Source.StringValue(),
+ Client: c.Client.StringValue(),
+ ClientURL: c.ClientURL.StringValue(),
+ Description: c.Description.StringValue(),
+ Severity: c.Severity,
+ Component: c.Component,
+ Group: c.Group,
+ Class: c.Class,
+ Details: newUpstreamDetails(c.Details),
+ }},
+ }}, nil
+}
+
+func newChannelPagerdutyConfigFromReceiver(name string, receiver *Receiver) (ChannelSpec, error) {
+ pagerduty := receiver.PagerdutyConfigs[0]
+ sendResolved := pagerduty.VSendResolved
+
+ if err := rejectAnyHTTPAuth(name, pagerduty.HTTPConfig); err != nil {
+ return nil, err
+ }
+
+ var details map[string]string
+ if len(pagerduty.Details) > 0 {
+ extracted, err := extractStringDetails(name, pagerduty.Details)
+ if err != nil {
+ return nil, err
+ }
+ details = extracted
+ }
+
+ return &ChannelPagerdutyConfig{
+ SendResolved: &sendResolved,
+ RoutingKey: string(pagerduty.RoutingKey),
+ URL: formatUpstreamURL(pagerduty.URL),
+ Source: valuer.UnsetIfEmpty(pagerduty.Source),
+ Client: valuer.UnsetIfEmpty(pagerduty.Client),
+ ClientURL: valuer.UnsetIfEmpty(pagerduty.ClientURL),
+ Description: valuer.UnsetIfEmpty(pagerduty.Description),
+ Severity: pagerduty.Severity,
+ Component: pagerduty.Component,
+ Group: pagerduty.Group,
+ Class: pagerduty.Class,
+ Details: details,
+ }, nil
+}
+
+type ChannelOpsgenieConfig struct {
+ SendResolved *bool `json:"sendResolved,omitempty"`
+ APIKey string `json:"apiKey" required:"true"`
+ APIURL string `json:"apiUrl"`
+ Message valuer.UnsetOrNonEmptyString `json:"message"`
+ Description valuer.UnsetOrNonEmptyString `json:"description"`
+ Source valuer.UnsetOrNonEmptyString `json:"source"`
+ Details map[string]string `json:"details,omitempty"`
+ Priority string `json:"priority"`
+}
+
+func (c ChannelOpsgenieConfig) Validate() error {
+ if c.APIKey == "" {
+ return errors.NewInvalidInputf(ErrCodeAlertmanagerChannelInvalid, "config.spec.apiKey is required for an opsgenie channel")
+ }
+
+ return nil
+}
+
+func (c ChannelOpsgenieConfig) toUndefaultedReceiver(displayName string) (*Receiver, error) {
+ var apiURL *config.URL
+ if c.APIURL != "" {
+ parsed, err := parseUpstreamURL(c.APIURL)
+ if err != nil {
+ return nil, err
+ }
+ apiURL = parsed
+ }
+
+ return &Receiver{Receiver: &config.Receiver{
+ Name: displayName,
+ OpsGenieConfigs: []*config.OpsGenieConfig{{
+ NotifierConfig: config.NotifierConfig{VSendResolved: resolveSendResolved(c.SendResolved, config.DefaultOpsGenieConfig.VSendResolved)},
+ APIKey: config.Secret(c.APIKey),
+ APIURL: apiURL,
+ Message: c.Message.StringValue(),
+ Description: c.Description.StringValue(),
+ Source: c.Source.StringValue(),
+ Priority: c.Priority,
+ Details: c.Details,
+ }},
+ }}, nil
+}
+
+func newChannelOpsgenieConfigFromReceiver(name string, receiver *Receiver) (ChannelSpec, error) {
+ opsgenie := receiver.OpsGenieConfigs[0]
+ sendResolved := opsgenie.VSendResolved
+
+ if err := rejectAnyHTTPAuth(name, opsgenie.HTTPConfig); err != nil {
+ return nil, err
+ }
+
+ return &ChannelOpsgenieConfig{
+ SendResolved: &sendResolved,
+ APIKey: string(opsgenie.APIKey),
+ APIURL: formatUpstreamURL(opsgenie.APIURL),
+ Message: valuer.UnsetIfEmpty(opsgenie.Message),
+ Description: valuer.UnsetIfEmpty(opsgenie.Description),
+ Source: valuer.UnsetIfEmpty(opsgenie.Source),
+ Priority: opsgenie.Priority,
+ Details: opsgenie.Details,
+ }, nil
+}
+
+type ChannelMSTeamsConfig struct {
+ SendResolved *bool `json:"sendResolved,omitempty"`
+ WebhookURL string `json:"webhookUrl" required:"true"`
+ Title valuer.UnsetOrNonEmptyString `json:"title"`
+ Text valuer.UnsetOrNonEmptyString `json:"text"`
+}
+
+func (c ChannelMSTeamsConfig) Validate() error {
+ if c.WebhookURL == "" {
+ return errors.NewInvalidInputf(ErrCodeAlertmanagerChannelInvalid, "config.spec.webhookUrl is required for an msteams channel")
+ }
+
+ return nil
+}
+
+func (c ChannelMSTeamsConfig) toUndefaultedReceiver(displayName string) (*Receiver, error) {
+ webhookURL, err := parseSecretURL(c.WebhookURL)
+ if err != nil {
+ return nil, err
+ }
+
+ return &Receiver{Receiver: &config.Receiver{
+ Name: displayName,
+ MSTeamsV2Configs: []*config.MSTeamsV2Config{{
+ NotifierConfig: config.NotifierConfig{VSendResolved: resolveSendResolved(c.SendResolved, config.DefaultMSTeamsV2Config.VSendResolved)},
+ WebhookURL: webhookURL,
+ Title: c.Title.StringValue(),
+ Text: c.Text.StringValue(),
+ }},
+ }}, nil
+}
+
+func newChannelMSTeamsConfigFromReceiver(name string, receiver *Receiver) (ChannelSpec, error) {
+ msteams := receiver.MSTeamsV2Configs[0]
+ sendResolved := msteams.VSendResolved
+
+ if err := rejectAnyHTTPAuth(name, msteams.HTTPConfig); err != nil {
+ return nil, err
+ }
+
+ return &ChannelMSTeamsConfig{
+ SendResolved: &sendResolved,
+ WebhookURL: formatSecretURL(msteams.WebhookURL),
+ Title: valuer.UnsetIfEmpty(msteams.Title),
+ Text: valuer.UnsetIfEmpty(msteams.Text),
+ }, nil
+}
+
+type ChannelGoogleChatConfig struct {
+ SendResolved *bool `json:"sendResolved,omitempty"`
+ WebhookURL string `json:"webhookUrl" required:"true"`
+ Title valuer.UnsetOrNonEmptyString `json:"title"`
+ Text valuer.UnsetOrNonEmptyString `json:"text"`
+}
+
+func (c ChannelGoogleChatConfig) Validate() error {
+ if c.WebhookURL == "" {
+ return errors.NewInvalidInputf(ErrCodeAlertmanagerChannelInvalid, "config.spec.webhookUrl is required for a googlechat channel")
+ }
+
+ return nil
+}
+
+func (c ChannelGoogleChatConfig) toUndefaultedReceiver(displayName string) (*Receiver, error) {
+ webhookURL, err := parseSecretURL(c.WebhookURL)
+ if err != nil {
+ return nil, err
+ }
+
+ return &Receiver{
+ Receiver: &config.Receiver{Name: displayName},
+ GoogleChatConfigs: []*GoogleChatReceiverConfig{{
+ NotifierConfig: config.NotifierConfig{VSendResolved: resolveSendResolved(c.SendResolved, DefaultGoogleChatReceiverConfig.VSendResolved)},
+ WebhookURL: webhookURL,
+ Title: c.Title.StringValue(),
+ Text: c.Text.StringValue(),
+ }},
+ }, nil
+}
+
+func newChannelGoogleChatConfigFromReceiver(name string, receiver *Receiver) (ChannelSpec, error) {
+ googlechat := receiver.GoogleChatConfigs[0]
+ sendResolved := googlechat.VSendResolved
+
+ if err := rejectAnyHTTPAuth(name, googlechat.HTTPConfig); err != nil {
+ return nil, err
+ }
+
+ return &ChannelGoogleChatConfig{
+ SendResolved: &sendResolved,
+ WebhookURL: formatSecretURL(googlechat.WebhookURL),
+ Title: valuer.UnsetIfEmpty(googlechat.Title),
+ Text: valuer.UnsetIfEmpty(googlechat.Text),
+ }, nil
+}
+
+type ChannelJiraConfig struct {
+ SendResolved *bool `json:"sendResolved,omitempty"`
+ // Site is the Jira Cloud base URL, https://<site>.atlassian.net. Only Jira
+ // Cloud is supported; the REST base is derived from it.
+ Site string `json:"site" required:"true"`
+ Project string `json:"project" required:"true"`
+ IssueType string `json:"issueType" required:"true"`
+ Summary valuer.UnsetOrNonEmptyString `json:"summary"`
+ Description valuer.UnsetOrNonEmptyString `json:"description"`
+ Priority string `json:"priority"`
+ Labels []string `json:"labels,omitempty"`
+ ResolveTransition string `json:"resolveTransition"`
+ ReopenTransition string `json:"reopenTransition"`
+ ReopenDuration valuer.UnsetOrNonEmptyString `json:"reopenDuration"`
+ WontFixResolution string `json:"wontFixResolution"`
+ CustomFields map[string]any `json:"customFields,omitempty"`
+
+ Email string `json:"email" required:"true"`
+ APIToken string `json:"apiToken" required:"true"`
+}
+
+func (c ChannelJiraConfig) Validate() error {
+ for _, required := range []struct {
+ value string
+ field string
+ }{
+ {c.Site, "site"},
+ {c.Project, "project"},
+ {c.IssueType, "issueType"},
+ {c.Email, "email"},
+ {c.APIToken, "apiToken"},
+ } {
+ if required.value == "" {
+ return errors.NewInvalidInputf(ErrCodeAlertmanagerChannelInvalid, "config.spec.%s is required for a jira channel", required.field)
+ }
+ }
+
+ if !c.ReopenDuration.IsZero() {
+ reopenDuration, err := model.ParseDuration(c.ReopenDuration.StringValue())
+ if err != nil {
+ return errors.WrapInvalidInputf(err, ErrCodeAlertmanagerChannelInvalid, "config.spec.reopenDuration %q is not a valid duration", c.ReopenDuration)
+ }
+
+ // A read reports the duration as model.Duration formats it, collapsing
+ // "72h" into "3d", so a value that is not already in that form is rejected
+ // rather than answered with one the caller never sent.
+ if canonical := reopenDuration.String(); canonical != c.ReopenDuration.StringValue() {
+ return errors.NewInvalidInputf(ErrCodeAlertmanagerChannelInvalid, "config.spec.reopenDuration %q must be written as %q", c.ReopenDuration, canonical)
+ }
+ }
+
+ return nil
+}
+
+func (c ChannelJiraConfig) toUndefaultedReceiver(displayName string) (*Receiver, error) {
+ // Seeded from upstream's default rather than a zero value: FollowRedirects
+ // and EnableHTTP2 marshal unconditionally, so a zero value would persist them
+ // as false and read back as a config ChannelJiraConfig cannot represent.
+ httpConfig := commoncfg.DefaultHTTPClientConfig
+ httpConfig.BasicAuth = &commoncfg.BasicAuth{
+ Username: c.Email,
+ Password: commoncfg.Secret(c.APIToken),
+ }
+
+ jira := &JiraReceiverConfig{
+ // JiraReceiverConfig seeds no send_resolved of its own, so unset means off.
+ NotifierConfig: config.NotifierConfig{VSendResolved: resolveSendResolved(c.SendResolved, false)},
+ Site: c.Site,
+ Project: c.Project,
+ IssueType: c.IssueType,
+ Summary: c.Summary.StringValue(),
+ Description: c.Description.StringValue(),
+ Priority: c.Priority,
+ Labels: c.Labels,
+ ResolveTransition: c.ResolveTransition,
+ ReopenTransition: c.ReopenTransition,
+ WontFixResolution: c.WontFixResolution,
+ CustomFields: c.CustomFields,
+ HTTPConfig: &httpConfig,
+ }
+
+ if !c.ReopenDuration.IsZero() {
+ reopenDuration, err := model.ParseDuration(c.ReopenDuration.StringValue())
+ if err != nil {
+ return nil, errors.WrapInvalidInputf(err, ErrCodeAlertmanagerChannelInvalid, "parse reopenDuration %q", c.ReopenDuration)
+ }
+ jira.ReopenDuration = reopenDuration
+ }
+
+ return &Receiver{
+ Receiver: &config.Receiver{Name: displayName},
+ JiraConfigs: []*JiraReceiverConfig{jira},
+ }, nil
+}
+
+func newChannelJiraConfigFromReceiver(name string, receiver *Receiver) (ChannelSpec, error) {
+ jira := receiver.JiraConfigs[0]
+ sendResolved := jira.VSendResolved
+
+ if err := rejectUnsupportedHTTPConfig(name, jira.HTTPConfig); err != nil {
+ return nil, err
+ }
+
+ if jira.HTTPConfig != nil && jira.HTTPConfig.Authorization != nil {
+ return nil, errors.NewInvalidInputf(ErrCodeAlertmanagerChannelInvalid, "channel %q sets http_config.authorization, which is not supported", name)
+ }
+
+ if err := rejectHTTPBasicAuthBeyondPassword(name, jira.HTTPConfig); err != nil {
+ return nil, err
+ }
+
+ spec := &ChannelJiraConfig{
+ SendResolved: &sendResolved,
+ Site: jira.Site,
+ Project: jira.Project,
+ IssueType: jira.IssueType,
+ Summary: valuer.UnsetIfEmpty(jira.Summary),
+ Description: valuer.UnsetIfEmpty(jira.Description),
+ Priority: jira.Priority,
+ Labels: jira.Labels,
+ ResolveTransition: jira.ResolveTransition,
+ ReopenTransition: jira.ReopenTransition,
+ ReopenDuration: valuer.UnsetIfEmpty(jira.ReopenDuration.String()),
+ WontFixResolution: jira.WontFixResolution,
+ CustomFields: jira.CustomFields,
+ }
+
+ if jira.HTTPConfig != nil && jira.HTTPConfig.BasicAuth != nil {
+ spec.Email = jira.HTTPConfig.BasicAuth.Username
+ spec.APIToken = string(jira.HTTPConfig.BasicAuth.Password)
+ }
+
+ return spec, nil
+}
+
+// ChannelJSMOpsConfig carries no API URL: JSM Ops is a single global gateway
+// keyed by the integration API key, which the notifier pins itself.
+type ChannelJSMOpsConfig struct {
+ SendResolved *bool `json:"sendResolved,omitempty"`
+ APIKey string `json:"apiKey" required:"true"`
+ Message valuer.UnsetOrNonEmptyString `json:"message"`
+ Description valuer.UnsetOrNonEmptyString `json:"description"`
+ Priority string `json:"priority"`
+ // Tags is the comma-separated list JSM Ops attaches to the alert.
+ Tags valuer.UnsetOrNonEmptyString `json:"tags"`
+}
+
+func (c ChannelJSMOpsConfig) Validate() error {
+ if c.APIKey == "" {
+ return errors.NewInvalidInputf(ErrCodeAlertmanagerChannelInvalid, "config.spec.apiKey is required for a jsmops channel")
+ }
+
+ return nil
+}
+
+func (c ChannelJSMOpsConfig) toUndefaultedReceiver(displayName string) (*Receiver, error) {
+ return &Receiver{
+ Receiver: &config.Receiver{Name: displayName},
+ JSMOpsConfigs: []*JSMOpsReceiverConfig{{
+ NotifierConfig: config.NotifierConfig{VSendResolved: resolveSendResolved(c.SendResolved, DefaultJSMOpsReceiverConfig.VSendResolved)},
+ APIKey: config.Secret(c.APIKey),
+ Message: c.Message.StringValue(),
+ Description: c.Description.StringValue(),
+ Priority: c.Priority,
+ Tags: c.Tags.StringValue(),
+ }},
+ }, nil
+}
+
+func newChannelJSMOpsConfigFromReceiver(name string, receiver *Receiver) (ChannelSpec, error) {
+ jsmops := receiver.JSMOpsConfigs[0]
+ sendResolved := jsmops.VSendResolved
+
+ if err := rejectAnyHTTPAuth(name, jsmops.HTTPConfig); err != nil {
+ return nil, err
+ }
+
+ return &ChannelJSMOpsConfig{
+ SendResolved: &sendResolved,
+ APIKey: string(jsmops.APIKey),
+ Message: valuer.UnsetIfEmpty(jsmops.Message),
+ Description: valuer.UnsetIfEmpty(jsmops.Description),
+ Priority: jsmops.Priority,
+ Tags: valuer.UnsetIfEmpty(jsmops.Tags),
+ }, nil
+}
+
+type ChannelIncidentIOConfig struct {
+ SendResolved *bool `json:"sendResolved,omitempty"`
+ URL string `json:"url" required:"true"`
+ Token string `json:"token" required:"true"`
+ Title valuer.UnsetOrNonEmptyString `json:"title"`
+ Description valuer.UnsetOrNonEmptyString `json:"description"`
+ Metadata map[string]string `json:"metadata,omitempty"`
+}
+
+func (c ChannelIncidentIOConfig) Validate() error {
+ if c.URL == "" {
+ return errors.NewInvalidInputf(ErrCodeAlertmanagerChannelInvalid, "config.spec.url is required for an incidentio channel")
+ }
+
+ if c.Token == "" {
+ return errors.NewInvalidInputf(ErrCodeAlertmanagerChannelInvalid, "config.spec.token is required for an incidentio channel")
+ }
+
+ return nil
+}
+
+func (c ChannelIncidentIOConfig) toUndefaultedReceiver(displayName string) (*Receiver, error) {
+ return &Receiver{
+ Receiver: &config.Receiver{Name: displayName},
+ IncidentIOConfigs: []*IncidentIOReceiverConfig{{
+ NotifierConfig: config.NotifierConfig{VSendResolved: resolveSendResolved(c.SendResolved, DefaultIncidentIOReceiverConfig.VSendResolved)},
+ URL: c.URL,
+ Token: config.Secret(c.Token),
+ Title: c.Title.StringValue(),
+ Description: c.Description.StringValue(),
+ Metadata: c.Metadata,
+ }},
+ }, nil
+}
+
+func newChannelIncidentIOConfigFromReceiver(name string, receiver *Receiver) (ChannelSpec, error) {
+ incidentio := receiver.IncidentIOConfigs[0]
+ sendResolved := incidentio.VSendResolved
+
+ if err := rejectAnyHTTPAuth(name, incidentio.HTTPConfig); err != nil {
+ return nil, err
+ }
+
+ return &ChannelIncidentIOConfig{
+ SendResolved: &sendResolved,
+ URL: incidentio.URL,
+ Token: string(incidentio.Token),
+ Title: valuer.UnsetIfEmpty(incidentio.Title),
+ Description: valuer.UnsetIfEmpty(incidentio.Description),
+ Metadata: incidentio.Metadata,
+ }, nil
+}
+
+// ════════════════════════════════════════════════════════════════════════
+// Helpers
+// ════════════════════════════════════════════════════════════════════════
+
+// bearerAuthorizationType is the scheme SigNoz writes for token auth.
+const bearerAuthorizationType = "Bearer"
+
+// parseSecretURL and parseUpstreamURL wrap the two URL types upstream uses for
+// notifier endpoints. Callers holding an optional URL skip the call on an empty
+// string, so the field stays nil and is omitted rather than stored as an empty URL.
+func parseSecretURL(raw string) (*config.SecretURL, error) {
+ parsed, err := parseUpstreamURL(raw)
+ if err != nil {
+ return nil, err
+ }
+
+ return (*config.SecretURL)(parsed), nil
+}
+
+func parseUpstreamURL(raw string) (*config.URL, error) {
+ parsed, err := url.Parse(raw)
+ if err != nil {
+ return nil, errors.WrapInvalidInputf(err, ErrCodeAlertmanagerChannelInvalid, "parse url %q", raw)
+ }
+
+ return &config.URL{URL: parsed}, nil
+}
+
+func formatSecretURL(secretURL *config.SecretURL) string {
+ if secretURL == nil {
+ return ""
+ }
+
+ return formatUpstreamURL((*config.URL)(secretURL))
+}
+
+func formatUpstreamURL(upstreamURL *config.URL) string {
+ if upstreamURL == nil || upstreamURL.URL == nil {
+ return ""
+ }
+
+ return upstreamURL.String()
+}
+
+// PagerDuty is the one notifier whose details upstream types as map[string]any.
+func newUpstreamDetails(details map[string]string) map[string]any {
+ if details == nil {
+ return nil
+ }
+
+ upstream := make(map[string]any, len(details))
+ for key, value := range details {
+ upstream[key] = value
+ }
+
+ return upstream
+}
+
+func extractStringDetails(name string, details map[string]any) (map[string]string, error) {
+ extracted := make(map[string]string, len(details))
+ for key, value := range details {
+ stringValue, ok := value.(string)
+ if !ok {
+ return nil, errors.NewInvalidInputf(
+ ErrCodeAlertmanagerChannelInvalid,
+ "channel %q sets a non-string value for details.%s, which is not supported", name, key,
+ )
+ }
+ extracted[key] = stringValue
+ }
+
+ return extracted, nil
+}
+
+func rejectAnyHTTPAuth(channelName string, httpConfig *commoncfg.HTTPClientConfig) error {
+ if httpConfig == nil {
+ return nil
+ }
+
+ if httpConfig.BasicAuth != nil {
+ return errors.NewInvalidInputf(ErrCodeAlertmanagerChannelInvalid, "channel %q sets http_config.basic_auth, which is not supported", channelName)
+ }
+
+ if httpConfig.Authorization != nil {
+ return errors.NewInvalidInputf(ErrCodeAlertmanagerChannelInvalid, "channel %q sets http_config.authorization, which is not supported", channelName)
+ }
+
+ return rejectUnsupportedHTTPConfig(channelName, httpConfig)
+}
+
+func rejectUnsupportedHTTPConfig(channelName string, httpConfig *commoncfg.HTTPClientConfig) error {
+ if httpConfig == nil {
+ return nil
+ }
+
+ for _, field := range []struct {
+ fieldName string
+ isFieldConfigured bool
+ }{
+ {"oauth2", httpConfig.OAuth2 != nil},
+ {"bearer_token", httpConfig.BearerToken != ""},
+ {"bearer_token_file", httpConfig.BearerTokenFile != ""},
+ {"proxy_url", httpConfig.ProxyURL.URL != nil && httpConfig.ProxyURL.String() != ""},
+ {"no_proxy", httpConfig.NoProxy != ""},
+ {"proxy_from_environment", httpConfig.ProxyFromEnvironment},
+ {"http_headers", httpConfig.HTTPHeaders != nil},
+ {"tls_config", httpConfig.TLSConfig != (commoncfg.TLSConfig{})},
+ {"follow_redirects", !httpConfig.FollowRedirects},
+ {"enable_http2", !httpConfig.EnableHTTP2},
+ } {
+ if field.isFieldConfigured {
+ return errors.NewInvalidInputf(
+ ErrCodeAlertmanagerChannelInvalid,
+ "channel %q sets http_config.%s, which is not supported", channelName, field.fieldName,
+ )
+ }
+ }
+
+ return nil
+}
+
+func rejectHTTPBasicAuthBeyondPassword(channelName string, httpConfig *commoncfg.HTTPClientConfig) error {
+ if httpConfig == nil || httpConfig.BasicAuth == nil {
+ return nil
+ }
+
+ basicAuth := httpConfig.BasicAuth
+ if *basicAuth != (commoncfg.BasicAuth{Username: basicAuth.Username, Password: basicAuth.Password}) {
+ return errors.NewInvalidInputf(ErrCodeAlertmanagerChannelInvalid, "channel %q sets http_config.basic_auth, which is not supported", channelName)
+ }
+
+ return nil
+}
+
+func rejectHTTPAuthorizationBeyondBearer(channelName string, httpConfig *commoncfg.HTTPClientConfig) error {
+ if httpConfig == nil || httpConfig.Authorization == nil {
+ return nil
+ }
+
+ authorization := httpConfig.Authorization
+ if *authorization != (commoncfg.Authorization{Type: bearerAuthorizationType, Credentials: authorization.Credentials}) {
+ return errors.NewInvalidInputf(ErrCodeAlertmanagerChannelInvalid, "channel %q sets http_config.authorization, which is not supported", channelName)
+ }
+
+ return nil
+}
+
+// channelKinds registers each notification kind with the spec constructor
+// UnmarshalJSON picks by kind and the extractor that reads a stored receiver
+// back. The ChannelKind enum derives from it; the JSON schema hooks stay
+// literal lists so each branch reads as one line.
+var channelKinds = []channelKindEntry{
+ {
+ kind: ChannelKindSlack,
+ newSpec: func() ChannelSpec { return new(ChannelSlackConfig) },
+ countConfigs: func(receiver *Receiver) int { return len(receiver.SlackConfigs) },
+ extractSpec: newChannelSlackConfigFromReceiver,
+ },
+ {
+ kind: ChannelKindEmail,
+ newSpec: func() ChannelSpec { return new(ChannelEmailConfig) },
+ countConfigs: func(receiver *Receiver) int { return len(receiver.EmailConfigs) },
+ extractSpec: newChannelEmailConfigFromReceiver,
+ },
+ {
+ kind: ChannelKindWebhook,
+ newSpec: func() ChannelSpec { return new(ChannelWebhookConfig) },
+ countConfigs: func(receiver *Receiver) int { return len(receiver.WebhookConfigs) },
+ extractSpec: newChannelWebhookConfigFromReceiver,
+ },
+ {
+ kind: ChannelKindPagerduty,
+ newSpec: func() ChannelSpec { return new(ChannelPagerdutyConfig) },
+ countConfigs: func(receiver *Receiver) int { return len(receiver.PagerdutyConfigs) },
+ extractSpec: newChannelPagerdutyConfigFromReceiver,
+ },
+ {
+ kind: ChannelKindOpsgenie,
+ newSpec: func() ChannelSpec { return new(ChannelOpsgenieConfig) },
+ countConfigs: func(receiver *Receiver) int { return len(receiver.OpsGenieConfigs) },
+ extractSpec: newChannelOpsgenieConfigFromReceiver,
+ },
+ {
+ kind: ChannelKindMSTeams,
+ newSpec: func() ChannelSpec { return new(ChannelMSTeamsConfig) },
+ countConfigs: func(receiver *Receiver) int { return len(receiver.MSTeamsV2Configs) },
+ extractSpec: newChannelMSTeamsConfigFromReceiver,
+ },
+ {
+ kind: ChannelKindGoogleChat,
+ newSpec: func() ChannelSpec { return new(ChannelGoogleChatConfig) },
+ countConfigs: func(receiver *Receiver) int { return len(receiver.GoogleChatConfigs) },
+ extractSpec: newChannelGoogleChatConfigFromReceiver,
+ },
+ {
+ kind: ChannelKindJira,
+ newSpec: func() ChannelSpec { return new(ChannelJiraConfig) },
+ countConfigs: func(receiver *Receiver) int { return len(receiver.JiraConfigs) },
+ extractSpec: newChannelJiraConfigFromReceiver,
+ },
+ {
+ kind: ChannelKindJSMOps,
+ newSpec: func() ChannelSpec { return new(ChannelJSMOpsConfig) },
+ countConfigs: func(receiver *Receiver) int { return len(receiver.JSMOpsConfigs) },
+ extractSpec: newChannelJSMOpsConfigFromReceiver,
+ },
+ {
+ kind: ChannelKindIncidentIO,
+ newSpec: func() ChannelSpec { return new(ChannelIncidentIOConfig) },
+ countConfigs: func(receiver *Receiver) int { return len(receiver.IncidentIOConfigs) },
+ extractSpec: newChannelIncidentIOConfigFromReceiver,
+ },
+}
+
+type channelKindEntry struct {
+ kind ChannelKind
+ newSpec func() ChannelSpec
+ // countConfigs guards extractSpec, which reads the receiver's first config of
+ // this kind and so must not be called when there is none.
+ countConfigs func(receiver *Receiver) int
+ extractSpec func(name string, receiver *Receiver) (ChannelSpec, error)
+}
+
+func newChannelSpec(kind ChannelKind) (func() ChannelSpec, bool) {
+ for _, channelKind := range channelKinds {
+ if channelKind.kind == kind {
+ return channelKind.newSpec, true
+ }
+ }
+ return nil, false
+}
+
+// resolveSendResolved falls back to the notifier's own upstream default, because
+// send_resolved has no omitempty: a zero value would marshal as an explicit false
+// and overwrite the default rather than leave it in place.
+func resolveSendResolved(sendResolved *bool, upstreamDefault bool) bool {
+ if sendResolved == nil {
+ return upstreamDefault
+ }
+
+ return *sendResolved
+}
+
+func allowedValuesForChannelKind() string {
+ values := make([]string, 0, len(channelKinds))
+ for _, channelKind := range channelKinds {
+ values = append(values, "`"+channelKind.kind.StringValue()+"`")
+ }
+ slices.Sort(values)
+ return strings.Join(values, ", ")
+}
+
+// extractKindAndSpec parses a {"kind": "...", "spec": {...}} envelope. Unknown
+// keys are rejected here rather than by the caller's decoder: a custom
+// UnmarshalJSON receives raw bytes, so DisallowUnknownFields on the request body
+// does not reach inside config.
+func extractKindAndSpec(data []byte) (string, []byte, error) {
+ var head struct {
+ Kind string `json:"kind"`
+ Spec json.RawMessage `json:"spec"`
+ }
+ dec := json.NewDecoder(bytes.NewReader(data))
+ dec.DisallowUnknownFields()
+ if err := dec.Decode(&head); err != nil {
+ return "", nil, errors.WrapInvalidInputf(err, ErrCodeAlertmanagerChannelInvalid, "invalid channel config envelope")
+ }
+ return head.Kind, head.Spec, nil
+}
+
+// decodeChannelSpec rejects unknown fields so a spec meant for another kind is an
+// error rather than a silently empty struct, and validates before returning.
+func decodeChannelSpec[T ChannelSpec](specJSON []byte, target T, channelType string) (*T, error) {
+ if len(specJSON) == 0 {
+ return nil, errors.NewInvalidInputf(ErrCodeAlertmanagerChannelInvalid, "type %q: spec is required", channelType)
+ }
+ dec := json.NewDecoder(bytes.NewReader(specJSON))
+ dec.DisallowUnknownFields()
+ if err := dec.Decode(target); err != nil {
+ return nil, errors.WrapInvalidInputf(err, ErrCodeAlertmanagerChannelInvalid, "type %q: invalid spec JSON", channelType)
+ }
+ if err := target.Validate(); err != nil {
+ return nil, errors.WrapInvalidInputf(err, ErrCodeAlertmanagerChannelInvalid, "type %q: %s", channelType, err.Error())
+ }
+ return &target, nil
+}
+
+// signozDiscriminatorKey is the extension key that signoz.attachDiscriminators
+// promotes into a native OpenAPI 3 discriminator after reflection.
+const signozDiscriminatorKey = "x-signoz-discriminator"
+
+// schemaRef builds a local component schema reference for a discriminator mapping.
+func schemaRef(name string) string {
+ return "#/components/schemas/" + name
+}
+
+// channelVariantRef builds the component reference the reflector derives for a
+// ChannelConfigVariant instantiation: the generic's name followed by the fully
+// qualified type argument.
+func channelVariantRef(spec string) string {
+ return schemaRef("AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypes" + spec)
+}
+
+// markDiscriminator tags a oneOf schema with x-signoz-discriminator, keyed on
+// propertyName with the given value -> schema-ref mapping, so generated clients
+// get a discriminated DTO instead of an intersection.
+func markDiscriminator(s *jsonschema.Schema, propertyName string, mapping map[string]string) error {
+ if s.ExtraProperties == nil {
+ s.ExtraProperties = map[string]any{}
+ }
+ s.ExtraProperties[signozDiscriminatorKey] = map[string]any{
+ "propertyName": propertyName,
+ "mapping": mapping,
+ }
+ return nil
+}
+
+// restrictKindToOneValue pins a variant's kind to its single legal value, so
+// ChannelConfigVariant[ChannelSlackConfig] only accepts "slack".
+func restrictKindToOneValue(schema *jsonschema.Schema, channelType string) error {
+ kindProp, ok := schema.Properties["kind"]
+ if !ok || kindProp.TypeObject == nil {
+ return errors.NewInternalf(errors.CodeInternal, "variant schema missing `kind` property")
+ }
+ kindProp.TypeObject.WithEnum(channelType)
+ schema.Properties["kind"] = kindProp
+ return nil
+}
diff --git a/pkg/types/alertmanagertypes/channelconvertors.go b/pkg/types/alertmanagertypes/channelconvertors.go
new file mode 100644
index 0000000000..0498197065
--- /dev/null
+++ b/pkg/types/alertmanagertypes/channelconvertors.go
@@ -0,0 +1,117 @@
+package alertmanagertypes
+
+import (
+ "encoding/json"
+ "reflect"
+
+ "github.com/SigNoz/signoz/pkg/errors"
+ "github.com/prometheus/alertmanager/config"
+)
+
+// ════════════════════════════════════════════════════════════════════════
+// API -> storage
+// ════════════════════════════════════════════════════════════════════════
+
+// ToReceiver hands the assembled receiver to newDefaultedReceiver, which is the
+// only place upstream applies a notifier's defaults and validation — several
+// integrations panic without them.
+func (p *PostableNotificationChannel) ToReceiver() (*Receiver, error) {
+ spec, ok := p.Config.Spec.(ChannelSpec)
+ if !ok {
+ return nil, errors.NewInternalf(errors.CodeInternal, "config.spec was not decoded into a known type")
+ }
+
+ receiver, err := spec.toUndefaultedReceiver(p.DisplayName)
+ if err != nil {
+ return nil, err
+ }
+
+ return newDefaultedReceiver(receiver)
+}
+
+// ════════════════════════════════════════════════════════════════════════
+// Storage -> API
+// ════════════════════════════════════════════════════════════════════════
+
+// toPostableNotificationChannel derives the kind from the config the receiver
+// actually carries rather than from Channel.Type, so a row written with several
+// notifier kinds is rejected instead of reported under whichever one
+// receiverChannelType happened to pick.
+func (c *Channel) toPostableNotificationChannel() (*PostableNotificationChannel, error) {
+ receiver := &Receiver{Receiver: &config.Receiver{}}
+ if err := json.Unmarshal([]byte(c.Data), receiver); err != nil {
+ return nil, errors.WrapInternalf(err, errors.CodeInternal, "unmarshal channel %q", c.DisplayName)
+ }
+
+ if total := countNotifierConfigs(receiver); total > 1 {
+ return nil, errors.NewInvalidInputf(
+ ErrCodeAlertmanagerChannelInvalid,
+ "channel %q carries %d notifier configurations; only one per channel is supported", c.DisplayName, total,
+ )
+ }
+
+ for _, channelKind := range channelKinds {
+ if channelKind.countConfigs(receiver) == 0 {
+ continue
+ }
+
+ spec, err := channelKind.extractSpec(c.DisplayName, receiver)
+ if err != nil {
+ return nil, err
+ }
+
+ return &PostableNotificationChannel{
+ Name: c.Name,
+ DisplayName: c.DisplayName,
+ Config: ChannelConfig{Kind: channelKind.kind, Spec: spec},
+ }, nil
+ }
+
+ return nil, errors.NewNotFoundf(
+ ErrCodeChannelUnsupportedKind,
+ "channel %q carries no supported notifier configuration", c.DisplayName,
+ )
+}
+
+// countNotifierConfigs totals every *_configs entry on the receiver, including
+// notifier kinds no ChannelSpec models, so a row mixing a modelled kind with
+// an unmodelled one is not mistaken for a single-notifier channel.
+func countNotifierConfigs(receiver *Receiver) int {
+ return countConfigsFields(reflect.ValueOf(*receiver)) +
+ countConfigsFields(reflect.ValueOf(*receiver.Receiver))
+}
+
+func countConfigsFields(v reflect.Value) int {
+ t := v.Type()
+ total := 0
+ for i := 0; i < t.NumField(); i++ {
+ fieldVal := v.Field(i)
+ if fieldVal.Kind() != reflect.Slice || fieldVal.Len() == 0 {
+ continue
+ }
+
+ if !receiverTypeRegex.MatchString(t.Field(i).Tag.Get("yaml")) {
+ continue
+ }
+
+ total += fieldVal.Len()
+ }
+
+ return total
+}
+
+func (c *Channel) ToGettableNotificationChannel() (*GettableNotificationChannel, error) {
+ postable, err := c.toPostableNotificationChannel()
+ if err != nil {
+ return nil, err
+ }
+
+ return &GettableNotificationChannel{
+ Name: postable.Name,
+ DisplayName: postable.DisplayName,
+ Config: postable.Config,
+ ID: c.ID,
+ CreatedAt: c.CreatedAt,
+ UpdatedAt: c.UpdatedAt,
+ }, nil
+}
diff --git a/pkg/types/alertmanagertypes/channelconvertors_test.go b/pkg/types/alertmanagertypes/channelconvertors_test.go
new file mode 100644
index 0000000000..f682b88f0a
--- /dev/null
+++ b/pkg/types/alertmanagertypes/channelconvertors_test.go
@@ -0,0 +1,544 @@
+package alertmanagertypes
+
+import (
+ "reflect"
+ "testing"
+
+ "github.com/SigNoz/signoz/pkg/errors"
+ "github.com/SigNoz/signoz/pkg/valuer"
+ "github.com/prometheus/alertmanager/config"
+ commoncfg "github.com/prometheus/common/config"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+// The spec types and the upstream configs they translate through carry the same
+// field sets, and nothing but this couples them: a field missing from either
+// direction of the mapping is silently dropped. Every field is set so no default
+// can fill the gap and hide it, and the whole spec is compared so a dropped
+// field fails rather than going unasserted. Webhook is covered by
+// TestPostableChannelToReceiverRoundTripsWebhookAuthModes, whose auth modes are
+// mutually exclusive and so cannot all be set at once.
+func TestChannelToPostableChannelRoundTripsEveryFieldOfEveryKind(t *testing.T) {
+ sendResolved := true
+
+ testCases := []struct {
+ description string
+ kind ChannelKind
+ spec any
+ expectedRoundTrip any
+ }{
+ {
+ description: "slack",
+ kind: ChannelKindSlack,
+ spec: &ChannelSlackConfig{
+ SendResolved: &sendResolved,
+ APIURL: "https://hooks.slack.com/services/T/B/X",
+ Channel: "#alerts",
+ Title: valuer.MustNewUnsetOrNonEmptyString("slack title"),
+ Text: valuer.MustNewUnsetOrNonEmptyString("slack text"),
+ },
+ expectedRoundTrip: &ChannelSlackConfig{
+ SendResolved: &sendResolved,
+ APIURL: "https://hooks.slack.com/services/T/B/X",
+ Channel: "#alerts",
+ Title: valuer.MustNewUnsetOrNonEmptyString("slack title"),
+ Text: valuer.MustNewUnsetOrNonEmptyString("slack text"),
+ },
+ },
+ {
+ description: "email",
+ kind: ChannelKindEmail,
+ spec: &ChannelEmailConfig{
+ SendResolved: &sendResolved,
+ HTML: valuer.MustNewUnsetOrNonEmptyString("<p>email body</p>"),
+ Headers: map[string]string{"Subject": "email subject"},
+ },
+ expectedRoundTrip: &ChannelEmailConfig{
+ SendResolved: &sendResolved,
+ HTML: valuer.MustNewUnsetOrNonEmptyString("<p>email body</p>"),
+ Headers: map[string]string{"Subject": "email subject"},
+ },
+ },
+ {
+ description: "pagerduty",
+ kind: ChannelKindPagerduty,
+ spec: &ChannelPagerdutyConfig{
+ SendResolved: &sendResolved,
+ RoutingKey: "routing-key",
+ URL: "https://events.example.com/v2/enqueue",
+ Source: valuer.MustNewUnsetOrNonEmptyString("pagerduty source"),
+ Client: valuer.MustNewUnsetOrNonEmptyString("pagerduty client"),
+ ClientURL: valuer.MustNewUnsetOrNonEmptyString("https://client.example.com"),
+ Description: valuer.MustNewUnsetOrNonEmptyString("pagerduty description"),
+ Severity: "critical",
+ Component: "api",
+ Group: "platform",
+ Class: "deploy",
+ Details: map[string]string{"env": "prod"},
+ },
+ // Map-valued fields are merged with the notifier's defaults rather
+ // than replaced, so a read cannot tell the caller's entries from
+ // upstream's. Clients that diff a read against their own input
+ // (Terraform) see the extra keys.
+ expectedRoundTrip: &ChannelPagerdutyConfig{
+ SendResolved: &sendResolved,
+ RoutingKey: "routing-key",
+ URL: "https://events.example.com/v2/enqueue",
+ Source: valuer.MustNewUnsetOrNonEmptyString("pagerduty source"),
+ Client: valuer.MustNewUnsetOrNonEmptyString("pagerduty client"),
+ ClientURL: valuer.MustNewUnsetOrNonEmptyString("https://client.example.com"),
+ Description: valuer.MustNewUnsetOrNonEmptyString("pagerduty description"),
+ Severity: "critical",
+ Component: "api",
+ Group: "platform",
+ Class: "deploy",
+ Details: map[string]string{
+ "env": "prod",
+ "firing": "{{ .Alerts.Firing | toJson }}",
+ "num_firing": "{{ .Alerts.Firing | len }}",
+ "num_resolved": "{{ .Alerts.Resolved | len }}",
+ "resolved": "{{ .Alerts.Resolved | toJson }}",
+ },
+ },
+ },
+ {
+ description: "opsgenie",
+ kind: ChannelKindOpsgenie,
+ spec: &ChannelOpsgenieConfig{
+ SendResolved: &sendResolved,
+ APIKey: "api-key",
+ APIURL: "https://api.eu.opsgenie.com",
+ Message: valuer.MustNewUnsetOrNonEmptyString("opsgenie message"),
+ Description: valuer.MustNewUnsetOrNonEmptyString("opsgenie description"),
+ Source: valuer.MustNewUnsetOrNonEmptyString("opsgenie source"),
+ Priority: "P1",
+ Details: map[string]string{"env": "prod"},
+ },
+ expectedRoundTrip: &ChannelOpsgenieConfig{
+ SendResolved: &sendResolved,
+ APIKey: "api-key",
+ APIURL: "https://api.eu.opsgenie.com",
+ Message: valuer.MustNewUnsetOrNonEmptyString("opsgenie message"),
+ Description: valuer.MustNewUnsetOrNonEmptyString("opsgenie description"),
+ Source: valuer.MustNewUnsetOrNonEmptyString("opsgenie source"),
+ Priority: "P1",
+ Details: map[string]string{"env": "prod"},
+ },
+ },
+ {
+ description: "msteams",
+ kind: ChannelKindMSTeams,
+ spec: &ChannelMSTeamsConfig{
+ SendResolved: &sendResolved,
+ WebhookURL: "https://teams.example.com/hook",
+ Title: valuer.MustNewUnsetOrNonEmptyString("msteams title"),
+ Text: valuer.MustNewUnsetOrNonEmptyString("msteams text"),
+ },
+ expectedRoundTrip: &ChannelMSTeamsConfig{
+ SendResolved: &sendResolved,
+ WebhookURL: "https://teams.example.com/hook",
+ Title: valuer.MustNewUnsetOrNonEmptyString("msteams title"),
+ Text: valuer.MustNewUnsetOrNonEmptyString("msteams text"),
+ },
+ },
+ {
+ description: "googlechat",
+ kind: ChannelKindGoogleChat,
+ spec: &ChannelGoogleChatConfig{
+ SendResolved: &sendResolved,
+ WebhookURL: "https://chat.googleapis.com/v1/spaces/s/messages",
+ Title: valuer.MustNewUnsetOrNonEmptyString("googlechat title"),
+ Text: valuer.MustNewUnsetOrNonEmptyString("googlechat text"),
+ },
+ expectedRoundTrip: &ChannelGoogleChatConfig{
+ SendResolved: &sendResolved,
+ WebhookURL: "https://chat.googleapis.com/v1/spaces/s/messages",
+ Title: valuer.MustNewUnsetOrNonEmptyString("googlechat title"),
+ Text: valuer.MustNewUnsetOrNonEmptyString("googlechat text"),
+ },
+ },
+ {
+ description: "jira",
+ kind: ChannelKindJira,
+ spec: &ChannelJiraConfig{
+ SendResolved: &sendResolved,
+ Site: "https://acme.atlassian.net",
+ Project: "OPS",
+ IssueType: "Bug",
+ Summary: valuer.MustNewUnsetOrNonEmptyString("jira summary"),
+ Description: valuer.MustNewUnsetOrNonEmptyString("jira description"),
+ Priority: "High",
+ Labels: []string{"signoz", "alert"},
+ ResolveTransition: "Done",
+ ReopenTransition: "Reopen",
+ ReopenDuration: valuer.MustNewUnsetOrNonEmptyString("3d"),
+ WontFixResolution: "Won't Do",
+ CustomFields: map[string]any{"customfield_10010": "Ops"},
+ Email: "[email protected]",
+ APIToken: "api-token",
+ },
+ expectedRoundTrip: &ChannelJiraConfig{
+ SendResolved: &sendResolved,
+ Site: "https://acme.atlassian.net",
+ Project: "OPS",
+ IssueType: "Bug",
+ Summary: valuer.MustNewUnsetOrNonEmptyString("jira summary"),
+ Description: valuer.MustNewUnsetOrNonEmptyString("jira description"),
+ Priority: "High",
+ Labels: []string{"signoz", "alert"},
+ ResolveTransition: "Done",
+ ReopenTransition: "Reopen",
+ ReopenDuration: valuer.MustNewUnsetOrNonEmptyString("3d"),
+ WontFixResolution: "Won't Do",
+ CustomFields: map[string]any{"customfield_10010": "Ops"},
+ Email: "[email protected]",
+ APIToken: "api-token",
+ },
+ },
+ {
+ description: "jsmops",
+ kind: ChannelKindJSMOps,
+ spec: &ChannelJSMOpsConfig{
+ SendResolved: &sendResolved,
+ APIKey: "api-key",
+ Message: valuer.MustNewUnsetOrNonEmptyString("jsmops message"),
+ Description: valuer.MustNewUnsetOrNonEmptyString("jsmops description"),
+ Priority: "P1",
+ Tags: valuer.MustNewUnsetOrNonEmptyString("signoz,oncall"),
+ },
+ expectedRoundTrip: &ChannelJSMOpsConfig{
+ SendResolved: &sendResolved,
+ APIKey: "api-key",
+ Message: valuer.MustNewUnsetOrNonEmptyString("jsmops message"),
+ Description: valuer.MustNewUnsetOrNonEmptyString("jsmops description"),
+ Priority: "P1",
+ Tags: valuer.MustNewUnsetOrNonEmptyString("signoz,oncall"),
+ },
+ },
+ {
+ description: "incidentio",
+ kind: ChannelKindIncidentIO,
+ spec: &ChannelIncidentIOConfig{
+ SendResolved: &sendResolved,
+ URL: "https://api.incident.io/v2/alert_events/http/01ABC",
+ Token: "token",
+ Title: valuer.MustNewUnsetOrNonEmptyString("incidentio title"),
+ Description: valuer.MustNewUnsetOrNonEmptyString("incidentio description"),
+ Metadata: map[string]string{"team": "platform"},
+ },
+ expectedRoundTrip: &ChannelIncidentIOConfig{
+ SendResolved: &sendResolved,
+ URL: "https://api.incident.io/v2/alert_events/http/01ABC",
+ Token: "token",
+ Title: valuer.MustNewUnsetOrNonEmptyString("incidentio title"),
+ Description: valuer.MustNewUnsetOrNonEmptyString("incidentio description"),
+ Metadata: map[string]string{"team": "platform"},
+ },
+ },
+ }
+
+ for _, testCase := range testCases {
+ t.Run(testCase.description, func(t *testing.T) {
+ postable := PostableNotificationChannel{
+ Name: "channel",
+ DisplayName: "channel",
+ Config: ChannelConfig{Kind: testCase.kind, Spec: testCase.spec},
+ }
+ require.NoError(t, postable.Validate())
+
+ receiver, err := postable.ToReceiver()
+ require.NoError(t, err)
+
+ channel, err := NewChannelFromReceiverWithName(receiver, postable.Name, "org-1")
+ require.NoError(t, err)
+
+ roundTripped, err := channel.toPostableNotificationChannel()
+ require.NoError(t, err)
+
+ assert.Equal(t, postable.Name, roundTripped.Name)
+ assert.Equal(t, testCase.kind, roundTripped.Config.Kind)
+ assert.Equal(t, testCase.expectedRoundTrip, roundTripped.Config.Spec)
+ })
+ }
+}
+
+// Email transport is not representable in the channel spec, and no credential
+// may reach storage. stripEmailTransport blanks Smarthost rather than dropping
+// it, so the key survives as an empty string.
+func TestPostableChannelToReceiverOmitsEmailTransportCredentials(t *testing.T) {
+ postable := PostableNotificationChannel{
+ Name: "team",
+ DisplayName: "team",
+ Config: ChannelConfig{
+ Kind: ChannelKindEmail,
+ Spec: &ChannelEmailConfig{To: "[email protected]"},
+ },
+ }
+
+ receiver, err := postable.ToReceiver()
+ require.NoError(t, err)
+
+ channel, err := NewChannelFromReceiverWithName(receiver, postable.Name, "org-1")
+ require.NoError(t, err)
+
+ for _, credentialKey := range []string{"auth_username", "auth_password", "auth_secret", "tls_config"} {
+ assert.NotContains(t, channel.Data, credentialKey)
+ }
+
+ assert.Contains(t, channel.Data, `"smarthost":""`)
+}
+
+// The UI offers basic auth and bearer token for webhooks, so both must survive a
+// round trip. The legacy API overloaded one password field for both.
+func TestPostableChannelToReceiverRoundTripsWebhookAuthModes(t *testing.T) {
+ // The webhook notifier defaults send_resolved to true, so a spec that omits
+ // it reads back with that default rather than as unset.
+ sendResolved := config.DefaultWebhookConfig.VSendResolved
+
+ testCases := []struct {
+ description string
+ spec ChannelWebhookConfig
+ expectedInData string
+ expectedRoundTrip *ChannelWebhookConfig
+ }{
+ {
+ description: "basic auth",
+ spec: ChannelWebhookConfig{URL: "https://example.com/hook", Username: "u", Password: "p"},
+ expectedInData: `"basic_auth"`,
+ expectedRoundTrip: &ChannelWebhookConfig{SendResolved: &sendResolved, URL: "https://example.com/hook", Username: "u", Password: "p"},
+ },
+ {
+ description: "bearer token",
+ spec: ChannelWebhookConfig{URL: "https://example.com/hook", BearerToken: "tok"},
+ expectedInData: `"authorization"`,
+ expectedRoundTrip: &ChannelWebhookConfig{SendResolved: &sendResolved, URL: "https://example.com/hook", BearerToken: "tok"},
+ },
+ {
+ description: "no auth",
+ spec: ChannelWebhookConfig{URL: "https://example.com/hook"},
+ expectedInData: `"url"`,
+ expectedRoundTrip: &ChannelWebhookConfig{SendResolved: &sendResolved, URL: "https://example.com/hook"},
+ },
+ }
+
+ for _, testCase := range testCases {
+ t.Run(testCase.description, func(t *testing.T) {
+ postable := PostableNotificationChannel{
+ Name: "hook",
+ DisplayName: "hook",
+ Config: ChannelConfig{Kind: ChannelKindWebhook, Spec: &testCase.spec},
+ }
+ require.NoError(t, postable.Validate())
+
+ receiver, err := postable.ToReceiver()
+ require.NoError(t, err)
+
+ channel, err := NewChannelFromReceiverWithName(receiver, postable.Name, "org-1")
+ require.NoError(t, err)
+ assert.Contains(t, channel.Data, testCase.expectedInData)
+
+ roundTripped, err := channel.toPostableNotificationChannel()
+ require.NoError(t, err)
+ assert.Equal(t, testCase.expectedRoundTrip, roundTripped.Config.Spec)
+ })
+ }
+}
+
+// The SigNoz notifiers validate in their UnmarshalYAML, which ToReceiver reaches
+// only through the defaulting round-trip. A spec that passes Validate can still
+// be rejected there, and the request has to fail as invalid input rather than as
+// an internal error.
+func TestPostableChannelToReceiverReportsNotifierValidationAsInvalidInput(t *testing.T) {
+ postable := PostableNotificationChannel{
+ Name: "channel",
+ DisplayName: "channel",
+ Config: ChannelConfig{Kind: ChannelKindIncidentIO, Spec: &ChannelIncidentIOConfig{
+ URL: "https://api.incident.io/v2/incidents", Token: "token",
+ Title: valuer.MustNewUnsetOrNonEmptyString("incidentio title"), Description: valuer.MustNewUnsetOrNonEmptyString("incidentio description"),
+ }},
+ }
+ require.NoError(t, postable.Validate())
+
+ _, err := postable.ToReceiver()
+ require.Error(t, err)
+ assert.True(t, errors.Ast(err, errors.TypeInvalidInput), "got %v", err)
+}
+
+// rejectUnsupportedHTTPConfig enumerates the fields it rejects, so one added
+// upstream would pass unnoticed and be dropped on read. Pinning the counts turns
+// a dependency bump into a failing test rather than silent data loss.
+func TestRejectUnrepresentableHTTPConfigCoversEveryUpstreamMember(t *testing.T) {
+ assert.Equal(t, 10, reflect.TypeFor[commoncfg.HTTPClientConfig]().NumField())
+ assert.Equal(t, 5, reflect.TypeFor[commoncfg.ProxyConfig]().NumField())
+}
+
+func TestChannelToPostableChannelRejectsUnrepresentableChannels(t *testing.T) {
+ testCases := []struct {
+ description string
+ channel Channel
+ }{
+ {
+ description: "two notifier kinds in one channel",
+ channel: Channel{
+ DisplayName: "mixed",
+ Data: `{"name":"mixed","slack_configs":[{"channel":"#a"}],"email_configs":[{"to":"[email protected]"}]}`,
+ },
+ },
+ {
+ // Only the first would survive the read, and the second would be
+ // dropped on the next write.
+ description: "two configs of the same notifier kind",
+ channel: Channel{
+ DisplayName: "two-slacks",
+ Data: `{"name":"two-slacks","slack_configs":[{"channel":"#a"},{"channel":"#b"}]}`,
+ },
+ },
+ {
+ description: "no notifier configuration",
+ channel: Channel{
+ DisplayName: "empty",
+ Data: `{"name":"empty"}`,
+ },
+ },
+ {
+ description: "notifier kind outside the supported set",
+ channel: Channel{
+ DisplayName: "tg",
+ Data: `{"name":"tg","telegram_configs":[{"chat_id":1}]}`,
+ },
+ },
+ {
+ description: "legacy msteams v1 configs",
+ channel: Channel{
+ DisplayName: "old-teams",
+ Data: `{"name":"old-teams","msteams_configs":[{"webhook_url":"https://a"}]}`,
+ },
+ },
+ {
+ // Dropping these on read would unauthenticate the channel on the
+ // next write, so the read fails instead.
+ description: "webhook http_config beyond basic auth and bearer token",
+ channel: Channel{
+ DisplayName: "proxied",
+ Data: `{"name":"proxied","webhook_configs":[{"url":"https://a","http_config":{"proxy_url":"https://proxy","tls_config":{"insecure_skip_verify":true}}}]}`,
+ },
+ },
+ {
+ description: "a modelled notifier kind alongside an unmodelled one",
+ channel: Channel{
+ DisplayName: "slack-and-telegram",
+ Data: `{"name":"slack-and-telegram","slack_configs":[{"api_url":"https://a","channel":"#a"}],"telegram_configs":[{"chat_id":1,"bot_token":"t"}]}`,
+ },
+ },
+ {
+ // The spec models one config per kind, so the second would be lost.
+ description: "two configs of one notifier kind",
+ channel: Channel{
+ DisplayName: "two-slacks",
+ Data: `{"name":"two-slacks","slack_configs":[{"api_url":"https://a","channel":"#a"},{"api_url":"https://b","channel":"#b"}]}`,
+ },
+ },
+ {
+ // The spec carries the credentials but not the scheme, so any other
+ // scheme would be rewritten as Bearer on the next write.
+ description: "webhook authorization scheme other than bearer",
+ channel: Channel{
+ DisplayName: "token-auth",
+ Data: `{"name":"token-auth","webhook_configs":[{"url":"https://a","http_config":{"authorization":{"type":"Token","credentials":"abc"},"follow_redirects":true,"enable_http2":true}}]}`,
+ },
+ },
+ {
+ description: "webhook credentials sourced from a file",
+ channel: Channel{
+ DisplayName: "file-auth",
+ Data: `{"name":"file-auth","webhook_configs":[{"url":"https://a","http_config":{"authorization":{"type":"Bearer","credentials_file":"/run/token"},"follow_redirects":true,"enable_http2":true}}]}`,
+ },
+ },
+ {
+ description: "webhook basic auth password sourced from a file",
+ channel: Channel{
+ DisplayName: "file-password",
+ Data: `{"name":"file-password","webhook_configs":[{"url":"https://a","http_config":{"basic_auth":{"username":"u","password_file":"/run/pass"},"follow_redirects":true,"enable_http2":true}}]}`,
+ },
+ },
+ {
+ description: "webhook inline tls material",
+ channel: Channel{
+ DisplayName: "inline-tls",
+ Data: `{"name":"inline-tls","webhook_configs":[{"url":"https://a","http_config":{"tls_config":{"ca":"---PEM---","min_version":"TLS12"},"follow_redirects":true,"enable_http2":true}}]}`,
+ },
+ },
+ {
+ // The upstream kinds lift nothing out of http_config, so any credential
+ // or transport setting stored there would be dropped on the next write.
+ description: "slack basic auth",
+ channel: Channel{
+ DisplayName: "slack-basic",
+ Data: `{"name":"slack-basic","slack_configs":[{"api_url":"https://a","channel":"#a","http_config":{"basic_auth":{"username":"u","password":"p"},"follow_redirects":true,"enable_http2":true}}]}`,
+ },
+ },
+ {
+ description: "opsgenie proxy",
+ channel: Channel{
+ DisplayName: "og-proxy",
+ Data: `{"name":"og-proxy","opsgenie_configs":[{"api_key":"k","http_config":{"proxy_url":"https://proxy","follow_redirects":true,"enable_http2":true}}]}`,
+ },
+ },
+ {
+ description: "pagerduty authorization header",
+ channel: Channel{
+ DisplayName: "pd-bearer",
+ Data: `{"name":"pd-bearer","pagerduty_configs":[{"routing_key":"k","http_config":{"authorization":{"type":"Bearer","credentials":"tok"},"follow_redirects":true,"enable_http2":true}}]}`,
+ },
+ },
+ {
+ description: "msteams inline tls material",
+ channel: Channel{
+ DisplayName: "teams-tls",
+ Data: `{"name":"teams-tls","msteamsv2_configs":[{"webhook_url":"https://a","http_config":{"tls_config":{"ca":"---PEM---"},"follow_redirects":true,"enable_http2":true}}]}`,
+ },
+ },
+ {
+ description: "googlechat basic auth",
+ channel: Channel{
+ DisplayName: "chat-basic",
+ Data: `{"name":"chat-basic","googlechat_configs":[{"webhook_url":"https://chat.googleapis.com/v1/spaces/A/messages","http_config":{"basic_auth":{"username":"u","password":"p"},"follow_redirects":true,"enable_http2":true}}]}`,
+ },
+ },
+ {
+ // ChannelJiraConfig lifts only basic auth out of http_config, because
+ // that is all Jira Cloud accepts.
+ description: "jira authorization header",
+ channel: Channel{
+ DisplayName: "jira-bearer",
+ Data: `{"name":"jira-bearer","jira_configs":[{"site":"https://acme.atlassian.net","project":"OPS","issue_type":"Bug","http_config":{"authorization":{"type":"Bearer","credentials":"tok"},"follow_redirects":true,"enable_http2":true}}]}`,
+ },
+ },
+ {
+ // JSM Ops and incident.io authenticate through their own spec fields,
+ // so their specs model no http_config credentials at all.
+ description: "jsmops basic auth",
+ channel: Channel{
+ DisplayName: "jsm-basic",
+ Data: `{"name":"jsm-basic","jsmops_configs":[{"api_key":"key","http_config":{"basic_auth":{"username":"u","password":"p"},"follow_redirects":true,"enable_http2":true}}]}`,
+ },
+ },
+ {
+ description: "incidentio authorization header",
+ channel: Channel{
+ DisplayName: "io-bearer",
+ Data: `{"name":"io-bearer","incidentio_configs":[{"url":"https://api.incident.io/v2/alert_events/http/01ABC","token":"t","http_config":{"authorization":{"type":"Bearer","credentials":"tok"},"follow_redirects":true,"enable_http2":true}}]}`,
+ },
+ },
+ }
+
+ for _, testCase := range testCases {
+ t.Run(testCase.description, func(t *testing.T) {
+ _, err := testCase.channel.toPostableNotificationChannel()
+ assert.Error(t, err)
+ })
+ }
+}
diff --git a/pkg/types/alertmanagertypes/config.go b/pkg/types/alertmanagertypes/config.go
index 82c52e8aad..8ee6c67312 100644
--- a/pkg/types/alertmanagertypes/config.go
+++ b/pkg/types/alertmanagertypes/config.go
@@ -334,12 +334,32 @@ func cloneReceiver(receiver *Receiver) (*Receiver, error) {
func (c *Config) CreateReceiver(receiver *Receiver) error {
// check that receiver name is not already used
- for _, existingReceiver := range c.alertmanagerConfig.Receivers {
- if existingReceiver.Name == receiver.Name {
- return errors.New(errors.TypeInvalidInput, ErrCodeAlertmanagerConfigConflict, "the receiver name has to be unique, please choose a different name")
- }
+ if c.hasReceiver(receiver.Name) {
+ return errors.New(errors.TypeInvalidInput, ErrCodeAlertmanagerConfigConflict, "the receiver name has to be unique, please choose a different name")
+ }
+
+ return c.createReceiver(receiver)
+}
+
+// CreateReceiverV2 differs from CreateReceiver only in reporting a name already in
+// use as a conflict rather than as invalid input. The v2 create path is the sole
+// caller: v1 create, NewConfigFromChannels and TestReceiver stay on CreateReceiver
+// so their responses keep the status code clients already see.
+func (c *Config) CreateReceiverV2(receiver *Receiver) error {
+ if c.hasReceiver(receiver.Name) {
+ return errors.Newf(errors.TypeAlreadyExists, ErrCodeAlertmanagerChannelAlreadyExists, "channel with display name %q already exists", receiver.Name)
}
+ return c.createReceiver(receiver)
+}
+
+func (c *Config) hasReceiver(name string) bool {
+ return slices.ContainsFunc(c.alertmanagerConfig.Receivers, func(existing config.Receiver) bool {
+ return existing.Name == name
+ })
+}
+
+func (c *Config) createReceiver(receiver *Receiver) error {
owned, err := cloneReceiver(receiver)
if err != nil {
return err
diff --git a/pkg/types/alertmanagertypes/receiver.go b/pkg/types/alertmanagertypes/receiver.go
index 1c84c0cd61..8f429da4c4 100644
--- a/pkg/types/alertmanagertypes/receiver.go
+++ b/pkg/types/alertmanagertypes/receiver.go
@@ -41,6 +41,10 @@ func NewReceiver(input string) (*Receiver, error) {
return nil, err
}
+ return newDefaultedReceiver(receiver)
+}
+
+func newDefaultedReceiver(receiver *Receiver) (*Receiver, error) {
withDefaults, err := defaultedBaseReceiver(receiver.Receiver)
if err != nil {
return nil, err
diff --git a/pkg/valuer/unset_or_non_empty_string.go b/pkg/valuer/unset_or_non_empty_string.go
index ecf52f2c92..ac0bd65e03 100644
--- a/pkg/valuer/unset_or_non_empty_string.go
+++ b/pkg/valuer/unset_or_non_empty_string.go
@@ -33,6 +33,13 @@ func MustNewUnsetOrNonEmptyString(val string) UnsetOrNonEmptyString {
return nonEmptyString
}
+// UnsetIfEmpty reads a value back from a store, where an empty string is how
+// unset is spelled. It is the only way to reach the zero value from a string, so
+// it must never be used on caller input, which has to reject "" instead.
+func UnsetIfEmpty(val string) UnsetOrNonEmptyString {
+ return UnsetOrNonEmptyString{val: val}
+}
+
func (enum UnsetOrNonEmptyString) IsZero() bool {
return enum.val == ""
}
@@ -73,16 +80,18 @@ func (enum *UnsetOrNonEmptyString) Scan(val any) error {
return errors.Newf(errors.TypeInternal, ErrCodeUnknownValuerScan, "unset_or_non_empty_string: (nil \"%T\")", enum)
}
+ if val == nil {
+ *enum = UnsetOrNonEmptyString{}
+ return nil
+ }
+
str, ok := val.(string)
if !ok {
return errors.Newf(errors.TypeInternal, ErrCodeUnknownValuerScan, "unset_or_non_empty_string: (non-string \"%T\")", val)
}
- var err error
- *enum, err = NewUnsetOrNonEmptyString(str)
- if err != nil {
- return err
- }
+ // scan is run when reading stored data where we can assume "" means unset, so no errors on seeing "".
+ *enum = UnsetIfEmpty(str)
return nil
}
diff --git a/pkg/valuer/unset_or_non_empty_string_test.go b/pkg/valuer/unset_or_non_empty_string_test.go
index 47f0179992..4fd5d19057 100644
--- a/pkg/valuer/unset_or_non_empty_string_test.go
+++ b/pkg/valuer/unset_or_non_empty_string_test.go
@@ -63,14 +63,22 @@ func TestUnsetOrNonEmptyStringMarshalJSON(t *testing.T) {
assert.JSONEq(t, `"Alert"`, string(raw))
}
-func TestUnsetOrNonEmptyStringScanRejectsAnEmptyString(t *testing.T) {
- var nonEmptyString UnsetOrNonEmptyString
+// A store spells unset as an empty or null column, so scanning one is the unset
+// case rather than a failure. Only a non-string column is an error.
+func TestUnsetOrNonEmptyStringScanReadsAnEmptyColumnAsUnset(t *testing.T) {
+ var unsetOrNonEmpty UnsetOrNonEmptyString
- require.NoError(t, nonEmptyString.Scan("oncall"))
- assert.Equal(t, "oncall", nonEmptyString.StringValue())
+ require.NoError(t, unsetOrNonEmpty.Scan("oncall"))
+ assert.Equal(t, "oncall", unsetOrNonEmpty.StringValue())
+
+ require.NoError(t, unsetOrNonEmpty.Scan(""))
+ assert.True(t, unsetOrNonEmpty.IsZero())
- assert.Error(t, nonEmptyString.Scan(""))
- assert.Error(t, nonEmptyString.Scan(nil))
+ require.NoError(t, unsetOrNonEmpty.Scan("oncall"))
+ require.NoError(t, unsetOrNonEmpty.Scan(nil))
+ assert.True(t, unsetOrNonEmpty.IsZero())
+
+ assert.Error(t, unsetOrNonEmpty.Scan(42))
}
func TestUnsetOrNonEmptyStringUnmarshalTextRejectsAnEmptyString(t *testing.T) {
@@ -90,3 +98,8 @@ func TestUnsetOrNonEmptyStringUnmarshalParamRejectsAnEmptyString(t *testing.T) {
assert.Error(t, nonEmptyString.UnmarshalParam(""))
}
+
+func TestUnsetIfEmpty(t *testing.T) {
+ assert.True(t, UnsetIfEmpty("").IsZero())
+ assert.Equal(t, MustNewUnsetOrNonEmptyString("oncall"), UnsetIfEmpty("oncall"))
+}
diff --git a/tests/fixtures/notification_channel.py b/tests/fixtures/notification_channel.py
index c0547e2f40..73c510ad6a 100644
--- a/tests/fixtures/notification_channel.py
+++ b/tests/fixtures/notification_channel.py
@@ -210,6 +210,32 @@ def create_notification_channel(
logger.error("Failed to delete channel: %s", {"channel_id": channel_id, "status": response.status_code, "response": response.text})
[email protected](name="cleanup_notification_channels", scope="function")
+def cleanup_notification_channels(
+ signoz: types.SigNoz,
+ create_user_admin: None, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+) -> Callable[[], list]:
+ """Yields a list to append channel IDs to; each is deleted on teardown.
+
+ Deletion goes through v1, which owns the same rows as v2.
+ """
+ admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+
+ channel_ids = []
+
+ yield channel_ids
+
+ for channel_id in channel_ids:
+ response = requests.delete(
+ signoz.self.host_configs["8080"].get(f"/api/v1/channels/{channel_id}"),
+ headers={"Authorization": f"Bearer {admin_token}"},
+ timeout=5,
+ )
+ if response.status_code != HTTPStatus.NO_CONTENT:
+ logger.error("Failed to delete channel: %s", {"channel_id": channel_id, "status": response.status_code, "response": response.text})
+
+
@pytest.fixture(name="create_webhook_notification_channel", scope="function")
def create_webhook_notification_channel(
signoz: types.SigNoz,
diff --git a/tests/integration/tests/alertmanager/04_notification_channels_v2.py b/tests/integration/tests/alertmanager/04_notification_channels_v2.py
new file mode 100644
index 0000000000..94e558389f
--- /dev/null
+++ b/tests/integration/tests/alertmanager/04_notification_channels_v2.py
@@ -0,0 +1,438 @@
+import re
+import uuid
+from collections.abc import Callable
+from http import HTTPStatus
+
+import pytest
+import requests
+
+from fixtures import types
+from fixtures.auth import (
+ USER_ADMIN_EMAIL,
+ USER_ADMIN_PASSWORD,
+ create_active_user,
+)
+
+TIMEOUT = 10
+
+V2_BASE_URL = "/api/v2/notification_channels"
+
+DNS1123_LABEL = re.compile(r"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$")
+
+_EDITOR_EMAIL = "[email protected]"
+_VIEWER_EMAIL = "[email protected]"
+_PASSWORD = "password123Z$"
+
+
+ "kind,spec,assert_field,assert_value",
+ [
+ pytest.param("slack", {"apiUrl": "https://hooks.slack.test/services/T/B/X", "channel": "#alerts", "title": "Alert", "text": "{{ .CommonLabels.alertname }}"}, "channel", "#alerts", id="slack"),
+ pytest.param("email", {"to": "[email protected]", "html": "<p>{{ .CommonLabels.alertname }}</p>"}, "to", "[email protected]", id="email"),
+ pytest.param("webhook", {"url": "https://webhook.test/hook", "username": "bob", "password": "s3cret"}, "username", "bob", id="webhook"),
+ pytest.param("pagerduty", {"routingKey": "pd-routing-key", "severity": "critical", "class": "db", "description": "{{ .CommonLabels.alertname }}"}, "severity", "critical", id="pagerduty"),
+ pytest.param("opsgenie", {"apiKey": "og-api-key", "message": "{{ .CommonLabels.alertname }}", "description": "{{ .CommonLabels.alertname }}", "priority": "P2"}, "priority", "P2", id="opsgenie"),
+ pytest.param("msteams", {"webhookUrl": "https://teams.test/webhook/abc", "title": "Alert", "text": "{{ .CommonLabels.alertname }}"}, "title", "Alert", id="msteams"),
+ # The google chat notifier only accepts https URLs on chat.googleapis.com.
+ pytest.param("googlechat", {"webhookUrl": "https://chat.googleapis.com/v1/spaces/A/messages?key=k&token=t", "title": "Alert", "text": "{{ .CommonLabels.alertname }}"}, "title", "Alert", id="googlechat"),
+ # The jira notifier only accepts Jira Cloud sites and basic auth.
+ pytest.param("jira", {"site": "https://acme.atlassian.net", "project": "OPS", "issueType": "Bug", "email": "[email protected]", "apiToken": "jira-api-token", "summary": "Alert", "description": "{{ .CommonLabels.alertname }}", "customFields": {"customfield_10010": "Ops"}}, "project", "OPS", id="jira"),
+ pytest.param("jsmops", {"apiKey": "jsm-api-key", "message": "Alert", "description": "{{ .CommonLabels.alertname }}", "priority": "P2"}, "priority", "P2", id="jsmops"),
+ # The incident.io notifier only accepts an alert source's events URL.
+ pytest.param("incidentio", {"url": "https://api.incident.io/v2/alert_events/http/01ABCDEF", "token": "incidentio-token", "title": "Alert", "description": "{{ .CommonLabels.alertname }}"}, "title", "Alert", id="incidentio"),
+ ],
+)
+def test_create_returns_the_channel_for_every_kind( # pylint: disable=too-many-arguments,too-many-positional-arguments
+ signoz: types.SigNoz,
+ create_user_admin: None, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+ cleanup_notification_channels: list[str],
+ kind: str,
+ spec: dict,
+ assert_field: str,
+ assert_value: str,
+) -> None:
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ name = f"v2-{kind}-{uuid.uuid4().hex[:8]}"
+
+ response = requests.post(
+ signoz.self.host_configs["8080"].get(V2_BASE_URL),
+ json={"name": name, "displayName": f"Display {name}", "config": {"kind": kind, "spec": spec}},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=TIMEOUT,
+ )
+ assert response.status_code == HTTPStatus.CREATED, response.text
+
+ created = response.json()["data"]
+ cleanup_notification_channels.append(created["id"])
+
+ assert created["name"] == name
+ assert created["displayName"] == f"Display {name}"
+ assert created["config"]["kind"] == kind
+ assert created["config"]["spec"][assert_field] == assert_value
+ assert created["createdAt"]
+ assert created["updatedAt"]
+
+
+ "kind,spec,expected_send_resolved",
+ [
+ pytest.param("slack", {"apiUrl": "https://hooks.slack.test/services/T/B/X", "title": "Alert", "text": "body"}, False, id="slack"),
+ pytest.param("email", {"to": "[email protected]", "html": "<p>body</p>"}, False, id="email"),
+ pytest.param("webhook", {"url": "https://webhook.test/hook"}, True, id="webhook"),
+ pytest.param("pagerduty", {"routingKey": "pd-routing-key", "description": "body"}, True, id="pagerduty"),
+ pytest.param("opsgenie", {"apiKey": "og-api-key", "message": "subject", "description": "body", "priority": "P2"}, True, id="opsgenie"),
+ pytest.param("msteams", {"webhookUrl": "https://teams.test/webhook/abc", "title": "Alert", "text": "body"}, True, id="msteams"),
+ pytest.param("googlechat", {"webhookUrl": "https://chat.googleapis.com/v1/spaces/A/messages?key=k&token=t", "title": "Alert", "text": "body"}, False, id="googlechat"),
+ pytest.param("jira", {"site": "https://acme.atlassian.net", "project": "OPS", "issueType": "Bug", "email": "[email protected]", "apiToken": "jira-api-token", "summary": "Alert", "description": "body"}, False, id="jira"),
+ pytest.param("jsmops", {"apiKey": "jsm-api-key", "message": "Alert", "description": "body"}, False, id="jsmops"),
+ pytest.param("incidentio", {"url": "https://api.incident.io/v2/alert_events/http/01ABCDEF", "token": "incidentio-token", "title": "Alert", "description": "body"}, False, id="incidentio"),
+ ],
+)
+def test_create_without_send_resolved_returns_the_notifier_default( # pylint: disable=too-many-arguments,too-many-positional-arguments
+ signoz: types.SigNoz,
+ create_user_admin: None, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+ cleanup_notification_channels: list[str],
+ kind: str,
+ spec: dict,
+ expected_send_resolved: bool,
+) -> None:
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ name = f"v2-sendresolved-{kind}-{uuid.uuid4().hex[:8]}"
+
+ response = requests.post(
+ signoz.self.host_configs["8080"].get(V2_BASE_URL),
+ json={"name": name, "config": {"kind": kind, "spec": spec}},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=TIMEOUT,
+ )
+ assert response.status_code == HTTPStatus.CREATED, response.text
+
+ created = response.json()["data"]
+ cleanup_notification_channels.append(created["id"])
+
+ assert created["config"]["spec"]["sendResolved"] is expected_send_resolved
+
+
+ "kind,spec,template_fields",
+ [
+ pytest.param("slack", {"apiUrl": "https://hooks.slack.test/services/T/B/X"}, ["title", "text"], id="slack"),
+ pytest.param("email", {"to": "[email protected]"}, ["html"], id="email"),
+ pytest.param("pagerduty", {"routingKey": "pd-routing-key"}, ["description"], id="pagerduty"),
+ pytest.param("opsgenie", {"apiKey": "og-api-key"}, ["message", "description"], id="opsgenie"),
+ pytest.param("msteams", {"webhookUrl": "https://teams.test/webhook/abc"}, ["title", "text"], id="msteams"),
+ pytest.param("googlechat", {"webhookUrl": "https://chat.googleapis.com/v1/spaces/A/messages?key=k&token=t"}, ["title", "text"], id="googlechat"),
+ pytest.param("jira", {"site": "https://acme.atlassian.net", "project": "OPS", "issueType": "Bug", "email": "[email protected]", "apiToken": "jira-api-token"}, ["summary", "description"], id="jira"),
+ pytest.param("jsmops", {"apiKey": "jsm-api-key"}, ["message", "description"], id="jsmops"),
+ pytest.param("incidentio", {"url": "https://api.incident.io/v2/alert_events/http/01ABCDEF", "token": "incidentio-token"}, ["title", "description"], id="incidentio"),
+ ],
+)
+def test_create_without_templates_returns_the_notifier_defaults( # pylint: disable=too-many-arguments,too-many-positional-arguments
+ signoz: types.SigNoz,
+ create_user_admin: None, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+ cleanup_notification_channels: list[str],
+ kind: str,
+ spec: dict,
+ template_fields: list[str],
+) -> None:
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ name = f"v2-templates-{kind}-{uuid.uuid4().hex[:8]}"
+
+ response = requests.post(
+ signoz.self.host_configs["8080"].get(V2_BASE_URL),
+ json={"name": name, "config": {"kind": kind, "spec": spec}},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=TIMEOUT,
+ )
+ assert response.status_code == HTTPStatus.CREATED, response.text
+
+ created = response.json()["data"]
+ cleanup_notification_channels.append(created["id"])
+
+ for field in template_fields:
+ assert "{{" in created["config"]["spec"][field], f"{field} should come back carrying the notifier's default template"
+
+
+def test_create_defaults_display_name_to_name(
+ signoz: types.SigNoz,
+ create_user_admin: None, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+ cleanup_notification_channels: list[str],
+) -> None:
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ name = f"v2-nodisplay-{uuid.uuid4().hex[:8]}"
+
+ response = requests.post(
+ signoz.self.host_configs["8080"].get(V2_BASE_URL),
+ json={"name": name, "config": {"kind": "email", "spec": {"to": "[email protected]", "html": "<p>body</p>"}}},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=TIMEOUT,
+ )
+ assert response.status_code == HTTPStatus.CREATED, response.text
+
+ created = response.json()["data"]
+ cleanup_notification_channels.append(created["id"])
+
+ assert created["name"] == name
+ assert created["displayName"] == name
+
+
+def test_create_with_generate_name_derives_a_dns1123_name(
+ signoz: types.SigNoz,
+ create_user_admin: None, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+ cleanup_notification_channels: list[str],
+) -> None:
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ display_name = f"On Call Escalation {uuid.uuid4().hex[:8]}"
+
+ response = requests.post(
+ signoz.self.host_configs["8080"].get(V2_BASE_URL),
+ json={
+ "generateName": True,
+ "displayName": display_name,
+ "config": {"kind": "email", "spec": {"to": "[email protected]", "html": "<p>body</p>"}},
+ },
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=TIMEOUT,
+ )
+ assert response.status_code == HTTPStatus.CREATED, response.text
+
+ created = response.json()["data"]
+ cleanup_notification_channels.append(created["id"])
+
+ assert created["displayName"] == display_name
+ assert DNS1123_LABEL.match(created["name"]), created["name"]
+ assert created["name"].startswith("on-call-escalation-")
+ assert created["name"] != display_name
+
+
+def test_create_generates_a_distinct_name_for_the_same_display_name(
+ signoz: types.SigNoz,
+ create_user_admin: None, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+ cleanup_notification_channels: list[str],
+) -> None:
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ display_name = f"Duplicate Display {uuid.uuid4().hex[:8]}"
+ names = []
+
+ for suffix in ("a", "b"):
+ response = requests.post(
+ signoz.self.host_configs["8080"].get(V2_BASE_URL),
+ json={
+ "generateName": True,
+ # The display name has to differ, because it is still the
+ # receiver name in the alertmanager config and must be unique.
+ "displayName": f"{display_name} {suffix}",
+ "config": {"kind": "email", "spec": {"to": f"{suffix}@integration.test", "html": "<p>body</p>"}},
+ },
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=TIMEOUT,
+ )
+ assert response.status_code == HTTPStatus.CREATED, response.text
+ created = response.json()["data"]
+ cleanup_notification_channels.append(created["id"])
+ names.append(created["name"])
+
+ assert names[0] != names[1]
+
+
+def test_create_rejects_a_duplicate_name_with_conflict(
+ signoz: types.SigNoz,
+ create_user_admin: None, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+ cleanup_notification_channels: list[str],
+) -> None:
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ name = f"v2-dupname-{uuid.uuid4().hex[:8]}"
+
+ response = requests.post(
+ signoz.self.host_configs["8080"].get(V2_BASE_URL),
+ json={"name": name, "displayName": f"{name} first", "config": {"kind": "email", "spec": {"to": "[email protected]", "html": "<p>body</p>"}}},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=TIMEOUT,
+ )
+ assert response.status_code == HTTPStatus.CREATED, response.text
+ cleanup_notification_channels.append(response.json()["data"]["id"])
+
+ # Same name, different display name: only the unique index on
+ # (org_id, name) can catch this one.
+ response = requests.post(
+ signoz.self.host_configs["8080"].get(V2_BASE_URL),
+ json={"name": name, "displayName": f"{name} second", "config": {"kind": "email", "spec": {"to": "[email protected]", "html": "<p>body</p>"}}},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=TIMEOUT,
+ )
+ assert response.status_code == HTTPStatus.CONFLICT, response.text
+
+
+def test_create_rejects_a_duplicate_display_name(
+ signoz: types.SigNoz,
+ create_user_admin: None, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+ cleanup_notification_channels: list[str],
+) -> None:
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ display_name = f"v2-dupdisplay-{uuid.uuid4().hex[:8]}"
+
+ response = requests.post(
+ signoz.self.host_configs["8080"].get(V2_BASE_URL),
+ json={"name": f"{display_name}-one", "displayName": display_name, "config": {"kind": "email", "spec": {"to": "[email protected]", "html": "<p>body</p>"}}},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=TIMEOUT,
+ )
+ assert response.status_code == HTTPStatus.CREATED, response.text
+ cleanup_notification_channels.append(response.json()["data"]["id"])
+
+ # The display name is the receiver name in the alertmanager config, which
+ # rejects duplicates before the row is ever written.
+ response = requests.post(
+ signoz.self.host_configs["8080"].get(V2_BASE_URL),
+ json={"name": f"{display_name}-two", "displayName": display_name, "config": {"kind": "email", "spec": {"to": "[email protected]", "html": "<p>body</p>"}}},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=TIMEOUT,
+ )
+ assert response.status_code == HTTPStatus.CONFLICT, response.text
+ # Both v2 conflicts share a status and an error code, so only the message
+ # separates a clashing display name from a clashing name.
+ assert "display name" in response.text
+
+
+ "body",
+ [
+ pytest.param({"name": "Not_A_Label", "config": {"kind": "email", "spec": {"to": "[email protected]", "html": "<p>body</p>"}}}, id="name_not_dns1123_label"),
+ pytest.param({"config": {"kind": "email", "spec": {"to": "[email protected]", "html": "<p>body</p>"}}}, id="no_name_and_no_generate_name"),
+ pytest.param({"name": "explicit", "generateName": True, "displayName": "Explicit", "config": {"kind": "email", "spec": {"to": "[email protected]", "html": "<p>body</p>"}}}, id="name_with_generate_name"),
+ pytest.param({"generateName": True, "config": {"kind": "email", "spec": {"to": "[email protected]", "html": "<p>body</p>"}}}, id="generate_name_without_display_name"),
+ pytest.param({"name": "default-receiver", "config": {"kind": "email", "spec": {"to": "[email protected]", "html": "<p>body</p>"}}}, id="reserved_receiver_name"),
+ pytest.param({"name": "no-config"}, id="no_config"),
+ pytest.param({"name": "telegram-kind", "config": {"kind": "telegram", "spec": {"chatId": 1}}}, id="unmodelled_kind"),
+ pytest.param({"name": "slack-unknown-field", "config": {"kind": "slack", "spec": {"apiUrl": "https://hooks.slack.test/services/T/B/X", "channel": "#a", "text": "body", "iconEmoji": ":tada:"}}}, id="unknown_spec_field"),
+ pytest.param({"name": "slack-with-email-spec", "config": {"kind": "slack", "spec": {"to": "[email protected]", "html": "<p>body</p>"}}}, id="spec_of_another_kind"),
+ pytest.param({"name": "extra-field", "config": {"kind": "email", "spec": {"to": "[email protected]", "html": "<p>body</p>"}}, "type": "email"}, id="unknown_envelope_field"),
+ pytest.param({"name": "webhook-both-auth", "config": {"kind": "webhook", "spec": {"url": "https://webhook.test/hook", "username": "u", "password": "p", "bearerToken": "t"}}}, id="webhook_basic_auth_with_bearer_token"),
+ pytest.param({"name": "webhook-half-auth", "config": {"kind": "webhook", "spec": {"url": "https://webhook.test/hook", "username": "u"}}}, id="webhook_basic_auth_without_password"),
+ # The last three reach the notifier's own validation rather than the
+ # spec's, so they assert it still surfaces as a 400 through v2.
+ pytest.param({"name": "jira-server-site", "config": {"kind": "jira", "spec": {"site": "https://jira.acme.com", "project": "OPS", "issueType": "Bug", "email": "[email protected]", "apiToken": "t", "summary": "Alert", "description": "body"}}}, id="jira_site_not_jira_cloud"),
+ pytest.param(
+ {"name": "jira-short-reopen", "config": {"kind": "jira", "spec": {"site": "https://acme.atlassian.net", "project": "OPS", "issueType": "Bug", "email": "[email protected]", "apiToken": "t", "summary": "Alert", "description": "body", "reopenDuration": "30s"}}}, id="jira_reopen_duration_below_a_minute"
+ ),
+ pytest.param({"name": "incidentio-bearer", "config": {"kind": "incidentio", "spec": {"url": "https://api.incident.io/v2/alert_events/http/01ABCDEF", "token": "Bearer incidentio-token", "title": "Alert", "description": "body"}}}, id="incidentio_token_with_bearer_prefix"),
+ pytest.param({"name": "slack-empty-title", "config": {"kind": "slack", "spec": {"apiUrl": "https://hooks.slack.test/services/T/B/X", "title": ""}}}, id="empty_string_on_a_defaulted_field"),
+ pytest.param({"name": "jsmops-empty-tags", "config": {"kind": "jsmops", "spec": {"apiKey": "jsm-api-key", "tags": ""}}}, id="empty_string_on_a_defaulted_signoz_field"),
+ pytest.param({"name": "jira-noncanonical-reopen", "config": {"kind": "jira", "spec": {"site": "https://acme.atlassian.net", "project": "OPS", "issueType": "Bug", "email": "[email protected]", "apiToken": "t", "reopenDuration": "72h"}}}, id="jira_reopen_duration_not_as_reported"),
+ pytest.param({"name": "email-lowercase-header", "config": {"kind": "email", "spec": {"to": "[email protected]", "headers": {"subject": "Alert"}}}}, id="email_header_name_not_as_reported"),
+ ],
+)
+def test_create_rejects_invalid_bodies(
+ signoz: types.SigNoz,
+ create_user_admin: None, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+ body: dict,
+) -> None:
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+
+ response = requests.post(
+ signoz.self.host_configs["8080"].get(V2_BASE_URL),
+ json=body,
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=TIMEOUT,
+ )
+ assert response.status_code == HTTPStatus.BAD_REQUEST, response.text
+
+
+ "kind,spec",
+ [
+ pytest.param("slack", {"channel": "#alerts", "title": "Alert", "text": "body"}, id="slack_without_api_url"),
+ pytest.param("email", {"html": "<p>body</p>"}, id="email_without_to"),
+ pytest.param("webhook", {}, id="webhook_without_url"),
+ pytest.param("pagerduty", {"description": "body"}, id="pagerduty_without_routing_key"),
+ pytest.param("opsgenie", {"message": "subject", "description": "body"}, id="opsgenie_without_api_key"),
+ pytest.param("msteams", {"title": "Alert", "text": "body"}, id="msteams_without_webhook_url"),
+ pytest.param("googlechat", {"title": "Alert", "text": "body"}, id="googlechat_without_webhook_url"),
+ pytest.param("jira", {"project": "OPS", "issueType": "Bug", "email": "[email protected]", "apiToken": "jira-api-token"}, id="jira_without_site"),
+ pytest.param("jira", {"site": "https://acme.atlassian.net", "issueType": "Bug", "email": "[email protected]", "apiToken": "jira-api-token"}, id="jira_without_project"),
+ pytest.param("jira", {"site": "https://acme.atlassian.net", "project": "OPS", "email": "[email protected]", "apiToken": "jira-api-token"}, id="jira_without_issue_type"),
+ pytest.param("jira", {"site": "https://acme.atlassian.net", "project": "OPS", "issueType": "Bug", "apiToken": "jira-api-token"}, id="jira_without_email"),
+ pytest.param("jira", {"site": "https://acme.atlassian.net", "project": "OPS", "issueType": "Bug", "email": "[email protected]"}, id="jira_without_api_token"),
+ pytest.param("jsmops", {}, id="jsmops_without_api_key"),
+ pytest.param("incidentio", {"token": "incidentio-token"}, id="incidentio_without_url"),
+ pytest.param("incidentio", {"url": "https://api.incident.io/v2/alert_events/http/01ABCDEF"}, id="incidentio_without_token"),
+ ],
+)
+def test_create_rejects_a_spec_missing_a_required_field(
+ signoz: types.SigNoz,
+ create_user_admin: None, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+ kind: str,
+ spec: dict,
+) -> None:
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+
+ response = requests.post(
+ signoz.self.host_configs["8080"].get(V2_BASE_URL),
+ json={"name": f"v2-missing-{uuid.uuid4().hex[:8]}", "config": {"kind": kind, "spec": spec}},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=TIMEOUT,
+ )
+ assert response.status_code == HTTPStatus.BAD_REQUEST, response.text
+
+
+def test_create_accepts_an_opsgenie_channel_without_a_priority(
+ signoz: types.SigNoz,
+ create_user_admin: None, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+ cleanup_notification_channels: list[str],
+) -> None:
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+
+ # Nothing seeds priority, so v1 channels created without one hold an empty
+ # value; requiring it here would make those rows unsaveable through v2.
+ response = requests.post(
+ signoz.self.host_configs["8080"].get(V2_BASE_URL),
+ json={
+ "name": f"v2-og-nopriority-{uuid.uuid4().hex[:8]}",
+ "config": {"kind": "opsgenie", "spec": {"apiKey": "og-api-key", "message": "subject", "description": "body"}},
+ },
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=TIMEOUT,
+ )
+ assert response.status_code == HTTPStatus.CREATED, response.text
+
+ created = response.json()["data"]
+ cleanup_notification_channels.append(created["id"])
+
+ assert created["config"]["spec"]["priority"] == ""
+
+
+def test_create_echoes_an_empty_value_on_a_field_with_no_default(
+ signoz: types.SigNoz,
+ create_user_admin: None, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+ cleanup_notification_channels: list[str],
+) -> None:
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+
+ response = requests.post(
+ signoz.self.host_configs["8080"].get(V2_BASE_URL),
+ json={
+ "name": f"v2-pd-empty-{uuid.uuid4().hex[:8]}",
+ "config": {"kind": "pagerduty", "spec": {"routingKey": "pd-routing-key", "severity": "", "class": ""}},
+ },
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=TIMEOUT,
+ )
+ assert response.status_code == HTTPStatus.CREATED, response.text
+
+ created = response.json()["data"]
+ cleanup_notification_channels.append(created["id"])
+
+ assert created["config"]["spec"]["severity"] == ""
+ assert created["config"]["spec"]["class"] == ""