Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

Fix an issue where users can't save their notification channel settings

Blue Mouse88c6cb9bfa83
diff --git a/backend/apps/cloud/src/notification-channel/notification-channel.controller.ts b/backend/apps/cloud/src/notification-channel/notification-channel.controller.ts
index 883ece5fc..f12658083 100644
--- a/backend/apps/cloud/src/notification-channel/notification-channel.controller.ts
+++ b/backend/apps/cloud/src/notification-channel/notification-channel.controller.ts
@@ -330,9 +330,9 @@ export class NotificationChannelController {
disabledReason: channel.disabledReason,
created: channel.created,
updated: channel.updated,
- scope: channel.user
+ scope: channel.user?.id
? 'user'
- : channel.organisation
+ : channel.organisation?.id
? 'organisation'
: 'project',
userId: channel.user?.id,
diff --git a/backend/apps/cloud/src/notification-channel/notification-channel.service.ts b/backend/apps/cloud/src/notification-channel/notification-channel.service.ts
index 97ee54acf..d7e0b1b6a 100644
--- a/backend/apps/cloud/src/notification-channel/notification-channel.service.ts
+++ b/backend/apps/cloud/src/notification-channel/notification-channel.service.ts
@@ -5,7 +5,7 @@ import {
NotFoundException,
} from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
-import { EntityManager, In, Repository } from 'typeorm'
+import { EntityManager, FindOptionsWhere, In, Repository } from 'typeorm'
import { randomBytes } from 'crypto'
import { isDeepStrictEqual } from 'util'
@@ -92,10 +92,20 @@ export class NotificationChannelService {
// --- Scope helpers --------------------------------------------------------
+ private findChannels(where: FindOptionsWhere<NotificationChannel>) {
+ return this.channelRepository.find({
+ where,
+ loadRelationIds: {
+ relations: ['user', 'organisation', 'project'],
+ disableMixedMap: true,
+ },
+ })
+ }
+
/** All channel ids manageable by the caller across user/orgs/projects. */
async getVisibleChannels(userId: string): Promise<NotificationChannel[]> {
const [userOwned, ownedProjectChannels, orgChannels] = await Promise.all([
- this.channelRepository.find({ where: { user: { id: userId } } }),
+ this.findChannels({ user: { id: userId } }),
this.getProjectChannelsForUserOwnedProjects(userId),
this.getOrgChannelsForManagedOrganisations(userId),
])
@@ -110,9 +120,7 @@ export class NotificationChannelService {
private async getProjectChannelsForUserOwnedProjects(userId: string) {
const pids = await this.projectService.getProjectIdsViewableByUser(userId)
if (pids.length === 0) return []
- return this.channelRepository.find({
- where: { project: { id: In(pids) } },
- })
+ return this.findChannels({ project: { id: In(pids) } })
}
private async getOrgChannelsForManagedOrganisations(userId: string) {
@@ -128,9 +136,7 @@ export class NotificationChannelService {
.map((m) => m.organisation?.id)
.filter((id): id is string => !!id)
if (orgIds.length === 0) return []
- return this.channelRepository.find({
- where: { organisation: { id: In(orgIds) } },
- })
+ return this.findChannels({ organisation: { id: In(orgIds) } })
}
/** Channels manageable and usable on a given project. */
@@ -144,21 +150,21 @@ export class NotificationChannelService {
const candidates: NotificationChannel[] = []
- const projectChannels = await this.channelRepository.find({
- where: { project: { id: projectId } },
+ const projectChannels = await this.findChannels({
+ project: { id: projectId },
})
candidates.push(...projectChannels)
if (project.admin?.id) {
- const ownerChannels = await this.channelRepository.find({
- where: { user: { id: project.admin.id } },
+ const ownerChannels = await this.findChannels({
+ user: { id: project.admin.id },
})
candidates.push(...ownerChannels)
}
if (project.organisation?.id) {
- const orgChannels = await this.channelRepository.find({
- where: { organisation: { id: project.organisation.id } },
+ const orgChannels = await this.findChannels({
+ organisation: { id: project.organisation.id },
})
candidates.push(...orgChannels)
}
@@ -186,9 +192,7 @@ export class NotificationChannelService {
'You are not allowed to manage this organisation',
)
}
- return this.channelRepository.find({
- where: { organisation: { id: organisationId } },
- })
+ return this.findChannels({ organisation: { id: organisationId } })
}
/** Validate channel ids the user wants to attach to a project alert. */
diff --git a/backend/apps/cloud/src/notification-channel/notification-channel.spec.ts b/backend/apps/cloud/src/notification-channel/notification-channel.spec.ts
new file mode 100644
index 000000000..af173acd2
--- /dev/null
+++ b/backend/apps/cloud/src/notification-channel/notification-channel.spec.ts
@@ -0,0 +1,177 @@
+import 'reflect-metadata'
+import {
+ DataSource,
+ Entity,
+ PrimaryColumn,
+ QueryResult,
+ QueryRunner,
+} from 'typeorm'
+
+jest.mock('../user/entities/user.entity', () => ({ User: class User {} }))
+jest.mock('../project/entity/project.entity', () => ({
+ Project: class Project {},
+}))
+jest.mock('../organisation/entity/organisation.entity', () => ({
+ Organisation: class Organisation {},
+}))
+jest.mock('../alert/entity/alert.entity', () => ({ Alert: class Alert {} }))
+jest.mock('../project/project.service', () => ({ ProjectService: class {} }))
+jest.mock('../organisation/organisation.service', () => ({
+ OrganisationService: class {},
+}))
+jest.mock('../common/constants', () => ({ PID_REGEX: /^[a-zA-Z0-9]{12}$/ }))
+jest.mock('../auth/decorators', () => ({ Auth: () => () => {} }))
+jest.mock('./dispatchers/channel-dispatcher.service', () => ({
+ ChannelDispatcherService: class {},
+}))
+jest.mock('../mailer/mailer.service', () => ({ MailerService: class {} }))
+
+import { User } from '../user/entities/user.entity'
+import { Project } from '../project/entity/project.entity'
+import { Organisation } from '../organisation/entity/organisation.entity'
+import { Alert } from '../alert/entity/alert.entity'
+import {
+ NotificationChannel,
+ NotificationChannelType,
+} from './entity/notification-channel.entity'
+import { NotificationChannelController } from './notification-channel.controller'
+import { NotificationChannelService } from './notification-channel.service'
+
+for (const target of [User, Project, Organisation, Alert]) {
+ Entity()(target)
+ PrimaryColumn('varchar')(target.prototype, 'id')
+}
+
+describe('notification channel list scope', () => {
+ let controller: NotificationChannelController
+
+ beforeEach(async () => {
+ const source = new DataSource({
+ type: 'mysql',
+ database: 'notification_channel_test',
+ entities: [NotificationChannel, User, Project, Organisation, Alert],
+ })
+ await (source as any).buildMetadatas()
+
+ const query = jest.fn(async (_sql: string, parameters: string[]) => {
+ const ownerId = parameters[0]
+ const scope = ownerId.split('-')[0]
+ const result = new QueryResult()
+ result.records = [
+ {
+ NotificationChannel_id: `${scope}-channel`,
+ NotificationChannel_name: 'Slack alerts',
+ NotificationChannel_type: NotificationChannelType.SLACK,
+ NotificationChannel_config: JSON.stringify({
+ url: 'https://hooks.slack.com/services/T000/B000/secret',
+ }),
+ NotificationChannel_isVerified: 1,
+ NotificationChannel_userId: scope === 'user' ? ownerId : null,
+ NotificationChannel_organisationId:
+ scope === 'organisation' ? ownerId : null,
+ NotificationChannel_projectId: scope === 'project' ? ownerId : null,
+ },
+ ]
+ return result
+ })
+ jest.spyOn(source, 'createQueryRunner').mockReturnValue({
+ query,
+ release: jest.fn(),
+ broadcaster: { broadcast: jest.fn() },
+ isTransactionActive: false,
+ isReleased: false,
+ } as unknown as QueryRunner)
+
+ const projects = {
+ getProjectIdsViewableByUser: jest.fn(async () => ['project-id']),
+ getFullProject: jest.fn(async () => ({
+ id: 'project-id',
+ admin: { id: 'user-id' },
+ organisation: { id: 'organisation-id' },
+ })),
+ allowedToManage: jest.fn(),
+ }
+ const organisations = {
+ findMemberships: jest.fn(async () => [
+ { organisation: { id: 'organisation-id' } },
+ ]),
+ }
+ const service = new NotificationChannelService(
+ source.getRepository(NotificationChannel),
+ projects as any,
+ organisations as any,
+ )
+ controller = new NotificationChannelController(
+ service,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ )
+ })
+
+ const expectedChannel = (scope: string) => ({
+ id: `${scope}-channel`,
+ scope,
+ userId: scope === 'user' ? 'user-id' : null,
+ organisationId: scope === 'organisation' ? 'organisation-id' : null,
+ projectId: scope === 'project' ? 'project-id' : null,
+ })
+
+ it('keeps a persisted Slack channel visible in personal settings after reloading', async () => {
+ const channels = await controller.list(
+ 'user-id',
+ undefined,
+ undefined,
+ 'user',
+ )
+
+ expect(channels).toHaveLength(1)
+ expect(channels[0]).toMatchObject({
+ ...expectedChannel('user'),
+ type: 'slack',
+ isVerified: true,
+ config: { url: 'https://hooks.slack.com/services/T000/…' },
+ })
+ })
+
+ it('preserves ownership for all visible channel scopes', async () => {
+ const channels = await controller.list('user-id')
+
+ expect(channels).toHaveLength(3)
+ expect(channels).toEqual(
+ expect.arrayContaining(
+ ['user', 'organisation', 'project'].map((scope) =>
+ expect.objectContaining(expectedChannel(scope)),
+ ),
+ ),
+ )
+ })
+
+ it('preserves ownership for project and inherited channels', async () => {
+ const channels = await controller.list('user-id', 'project-id')
+
+ expect(channels).toHaveLength(3)
+ expect(channels).toEqual(
+ expect.arrayContaining(
+ ['user', 'organisation', 'project'].map((scope) =>
+ expect.objectContaining(expectedChannel(scope)),
+ ),
+ ),
+ )
+ })
+
+ it('preserves ownership for organisation settings', async () => {
+ const channels = await controller.list(
+ 'user-id',
+ undefined,
+ 'organisation-id',
+ )
+
+ expect(channels).toHaveLength(1)
+ expect(channels[0]).toMatchObject(expectedChannel('organisation'))
+ })
+})