Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
206 changes: 206 additions & 0 deletions e2e/flows/policy-violation-notification.spec.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,206 @@
import { uniqueName } from '../api.mjs';
import { test, expect, login, search } from '../test.mjs';

const updateGroup = 'POLICY_VIOLATION_UPDATED';
const reviewedGroup = 'POLICY_VIOLATION_UPDATED_REVIEWED';

async function createAlert(api, notifyOn = []) {
const publishers = await api.get('/v1/notification/publisher');
const publisher = publishers.find(
(candidate) => candidate.name === 'Console',
);
expect(publisher).toBeDefined();
return api.send('PUT', '/v1/notification/rule', {
name: uniqueName('e2e-policy-update-alert'),
scope: 'PORTFOLIO',
triggerType: 'EVENT',
notificationLevel: 'INFORMATIONAL',
publisher: { uuid: publisher.uuid },
notifyOn,
});
}

async function openAlert(page, name) {
await page.goto('admin/notifications/alerts');
await search(page, name);
await page.getByRole('cell', { name, exact: true }).click();
}

async function readAlert(api, alert) {
const rules = await api.get(
`/v1/notification/rule?searchText=${encodeURIComponent(alert.name)}`,
);
const persisted = rules.find((candidate) => candidate.uuid === alert.uuid);
expect(persisted).toBeDefined();
return persisted;
}

test('preserve a creation-only alert without opting into updates', async ({
page,
api,
}) => {
const alert = await createAlert(api, ['POLICY_VIOLATION']);
await login(page);
await openAlert(page, alert.name);
await expect(
page.getByRole('checkbox', { name: 'POLICY_VIOLATION', exact: true }),
).toBeChecked();
for (const group of [updateGroup, reviewedGroup]) {
await expect(
page.getByRole('checkbox', { name: group, exact: true }),
).not.toBeChecked();
}

await page.getByRole('button', { name: 'Submit', exact: true }).click();
await expect(page.getByText('Updated', { exact: true })).toBeVisible();
await page.reload();
await search(page, alert.name);
await page.getByRole('cell', { name: alert.name, exact: true }).click();
const persisted = await readAlert(api, alert);
expect(persisted.notifyOn).toEqual(['POLICY_VIOLATION']);
for (const group of [updateGroup, reviewedGroup]) {
await expect(
page.getByRole('checkbox', { name: group, exact: true }),
).not.toBeChecked();
}
});

for (const groups of [
[],
[updateGroup],
[reviewedGroup],
[updateGroup, reviewedGroup],
]) {
test(`persist independent policy update subscriptions: ${groups.join(', ') || 'none'}`, async ({
page,
api,
}) => {
const alert = await createAlert(api);
await login(page);
await openAlert(page, alert.name);
const update = page.getByRole('checkbox', {
name: updateGroup,
exact: true,
});
const reviewed = page.getByRole('checkbox', {
name: reviewedGroup,
exact: true,
});
await expect(update).not.toBeChecked();
await expect(reviewed).not.toBeChecked();
await expect(update).toHaveAccessibleDescription(
'Notify when the stored message of an existing policy violation changes, excluding approved or suppressed violations. Use a condition that returns a stable message.',
);
await expect(reviewed).toHaveAccessibleDescription(
'Notify when the stored message of an approved or suppressed policy violation changes. Review decisions stay unchanged. Opting in does not replay earlier changes.',
);
for (const group of groups) {
await page.getByRole('checkbox', { name: group, exact: true }).check();
}
const saved = page.waitForResponse(
(response) =>
response.url().endsWith('/api/v1/notification/rule') &&
response.request().method() === 'POST',
);
await page.getByRole('button', { name: 'Submit', exact: true }).click();
const response = await saved;
expect(response.ok()).toBe(true);
expect(response.request().postDataJSON().notifyOn.toSorted()).toEqual(
groups.toSorted(),
);
await expect(page.getByText('Updated', { exact: true })).toBeVisible();

await page.reload();
await search(page, alert.name);
await page.getByRole('cell', { name: alert.name, exact: true }).click();
for (const group of [updateGroup, reviewedGroup]) {
await expect(
page.getByRole('checkbox', { name: group, exact: true }),
).toBeChecked({ checked: groups.includes(group) });
}
await expect(
page.getByRole('checkbox', { name: 'POLICY_VIOLATION', exact: true }),
).not.toBeChecked();
const persisted = await readAlert(api, alert);
expect((persisted.notifyOn || []).toSorted()).toEqual(groups.toSorted());
});
}

test('retain the event restriction of policy update groups', async ({
page,
api,
}) => {
const publishers = await api.get('/v1/notification/publisher');
const publisher = publishers.find(
(candidate) => candidate.name === 'Console',
);
const alert = await api.send('PUT', '/v1/notification/rule/scheduled', {
name: uniqueName('e2e-scheduled-update-alert'),
scope: 'PORTFOLIO',
triggerType: 'SCHEDULE',
scheduleCron: '0 0 * * *',
notificationLevel: 'INFORMATIONAL',
publisher: { uuid: publisher.uuid },
notifyOn: ['NEW_POLICY_VIOLATIONS_SUMMARY'],
});
await login(page);
await openAlert(page, alert.name);
for (const group of [updateGroup, reviewedGroup]) {
await expect(
page.getByRole('checkbox', { name: group, exact: true }),
).toHaveCount(0);
}
await expect(
page.getByRole('checkbox', { name: 'NEW_POLICY_VIOLATIONS_SUMMARY' }),
).toBeChecked();
});

test('keep policy update groups out of system alerts', async ({
page,
api,
}) => {
const publishers = await api.get('/v1/notification/publisher');
const publisher = publishers.find(
(candidate) => candidate.name === 'Console',
);
const alert = await api.send('PUT', '/v1/notification/rule', {
name: uniqueName('e2e-system-update-alert'),
scope: 'SYSTEM',
notificationLevel: 'INFORMATIONAL',
publisher: { uuid: publisher.uuid },
notifyOn: ['FILE_SYSTEM'],
});
await login(page);
await openAlert(page, alert.name);
for (const group of [updateGroup, reviewedGroup]) {
await expect(
page.getByRole('checkbox', { name: group, exact: true }),
).toHaveCount(0);
}
await expect(
page.getByRole('checkbox', { name: 'FILE_SYSTEM', exact: true }),
).toBeChecked();
});

test('unsubscribe from both policy update groups', async ({ page, api }) => {
const alert = await createAlert(api, [updateGroup, reviewedGroup]);
await login(page);
await openAlert(page, alert.name);
for (const group of [updateGroup, reviewedGroup]) {
const checkbox = page.getByRole('checkbox', { name: group, exact: true });
await expect(checkbox).toBeChecked();
await checkbox.uncheck();
}
await page.getByRole('button', { name: 'Submit', exact: true }).click();
await expect(page.getByText('Updated', { exact: true })).toBeVisible();
await page.reload();
await search(page, alert.name);
await page.getByRole('cell', { name: alert.name, exact: true }).click();
const persisted = await readAlert(api, alert);
expect(persisted.notifyOn || []).toEqual([]);
for (const group of [updateGroup, reviewedGroup]) {
await expect(
page.getByRole('checkbox', { name: group, exact: true }),
).not.toBeChecked();
}
});
21 changes: 18 additions & 3 deletions e2e/flows/session.spec.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,16 @@ async function endSession(page) {
});
}

const portfolioMetrics = /^\/api\/v1\/metrics\/portfolio\/\d+\/days$/;

async function loaded(page, path) {
const response = await page.waitForResponse(
(response) =>
path.test(new URL(response.url()).pathname) && response.status() === 200,
);
expect(await response.finished()).toBeNull();
}

test('verify the session only on the first page', async ({ page }) => {
await login(page);
const checks = [];
Expand All @@ -21,18 +31,23 @@ test('verify the session only on the first page', async ({ page }) => {
expect(checks).toEqual([]);
});

for (const [from, to] of [
['Dashboard', 'Licenses'],
['Licenses', 'Dashboard'],
for (const [from, to, sourceData] of [
['Dashboard', 'Licenses', []],
['Licenses', 'Dashboard', [/^\/api\/v1\/license$/, portfolioMetrics]],
]) {
test(`return to login when the session ends before opening ${to}`, async ({
page,
problems,
}) => {
problems.allow(/ 401$/);
const dashboardReady = loaded(page, portfolioMetrics);
await login(page);
await dashboardReady;
const sourceReady = sourceData.map((path) => loaded(page, path));
await page.getByRole('link', { name: from, exact: true }).click();
await expect(page).toHaveURL(new RegExp(`/${from.toLowerCase()}$`));
// Expire a loaded source page, not its still-pending initial data requests.
await Promise.all(sourceReady);
await endSession(page);
await page.getByRole('link', { name: to, exact: true }).click();
await expect(page).toHaveURL(
Expand Down
3 changes: 2 additions & 1 deletion e2e/global-setup.mjs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { execFileSync } from 'node:child_process';
import { readFile } from 'node:fs/promises';
import { fileURLToPath } from 'node:url';
import { request } from '@playwright/test';
import {
ADMIN_PASSWORD,
Expand Down Expand Up @@ -56,7 +57,7 @@ export default async function globalSetup() {
[
'compose',
'-f',
new URL('compose.yaml', import.meta.url).pathname,
fileURLToPath(new URL('compose.yaml', import.meta.url)),
'exec',
'-T',
'postgres',
Expand Down
2 changes: 2 additions & 0 deletions src/i18n/locales/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
"alert_deleted": "Alarm gelöscht",
"alert_log_successful_publish": "Erfolgreiche Alarmierung protokollieren",
"alert_log_successful_publish_help": "Protokolliert die erfolgreiche Alarmierung, anstatt nur bei Problemen zu protokollieren. Dies hilft beim Debuggen fehlender Alarme und macht die Alarmierung überprüfbar.",
"alert_policy_violation_updated_help": null,
"alert_policy_violation_updated_reviewed_help": null,
"alert_schedule_cron_expression": "Cron-Ausdruck",
"alert_schedule_last_triggered_at": "Zuletzt ausgelöst um",
"alert_schedule_next_trigger_at": "Nächste Auslösung um",
Expand Down
2 changes: 2 additions & 0 deletions src/i18n/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
"alert_deleted": "Alert deleted",
"alert_log_successful_publish": "Log successful publish",
"alert_log_successful_publish_help": "Emit a log message upon successful publishing of the alert to the destination, instead of only emitting logs when issues are encountered. Aids in debugging missing alerts, or making alert publishing auditable.",
"alert_policy_violation_updated_help": "Notify when the stored message of an existing policy violation changes, excluding approved or suppressed violations. Use a condition that returns a stable message.",
"alert_policy_violation_updated_reviewed_help": "Notify when the stored message of an approved or suppressed policy violation changes. Review decisions stay unchanged. Opting in does not replay earlier changes.",
"alert_schedule_cron_expression": "Cron expression",
"alert_schedule_last_triggered_at": "Last triggered at",
"alert_schedule_next_trigger_at": "Next trigger at",
Expand Down
2 changes: 2 additions & 0 deletions src/i18n/locales/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
"alert_deleted": "Alerta eliminada",
"alert_log_successful_publish": "Registrar publicación exitosa",
"alert_log_successful_publish_help": "Emita un mensaje de registro tras la publicación exitosa de la alerta en el destino, en lugar de solo emitir registros cuando se encuentren problemas. Ayuda a depurar alertas faltantes o hacer que la publicación de alertas sea auditable.",
"alert_policy_violation_updated_help": null,
"alert_policy_violation_updated_reviewed_help": null,
"alert_schedule_cron_expression": "Expresión cron",
"alert_schedule_last_triggered_at": "Última activación en",
"alert_schedule_next_trigger_at": "Siguiente activador en",
Expand Down
2 changes: 2 additions & 0 deletions src/i18n/locales/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
"alert_deleted": "Alerte supprimée",
"alert_log_successful_publish": "Journaliser les publications réussies",
"alert_log_successful_publish_help": "Émettre un message dans le journal lors d'une publication réussie d'une alerte vers la destination, au lieu d'émettre uniquement des journaux lorsque des problèmes sont rencontrés. Aide au débogage des alertes manquantes ou à rendre la publication des alertes auditable.",
"alert_policy_violation_updated_help": null,
"alert_policy_violation_updated_reviewed_help": null,
"alert_schedule_cron_expression": "Expression cron",
"alert_schedule_last_triggered_at": "Dernière déclenché à",
"alert_schedule_next_trigger_at": "Prochain déclencheur à",
Expand Down
2 changes: 2 additions & 0 deletions src/i18n/locales/hi.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
"alert_deleted": "अलर्ट हटा दिया गया",
"alert_log_successful_publish": "लॉग सफल प्रकाशन",
"alert_log_successful_publish_help": "गंतव्य पर अलर्ट के सफल प्रकाशन पर लॉग संदेश उत्सर्जित करें, न कि केवल समस्या आने पर लॉग उत्सर्जित करें। गायब अलर्ट को डीबग करने या अलर्ट प्रकाशन को ऑडिट करने योग्य बनाने में सहायता करता है।",
"alert_policy_violation_updated_help": null,
"alert_policy_violation_updated_reviewed_help": null,
"alert_schedule_cron_expression": "क्रोन अभिव्यक्ति",
"alert_schedule_last_triggered_at": "अंतिम ट्रिगर",
"alert_schedule_next_trigger_at": "अगला ट्रिगर पर",
Expand Down
2 changes: 2 additions & 0 deletions src/i18n/locales/it.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
"alert_deleted": "Avviso eliminato",
"alert_log_successful_publish": "Registra la pubblicazione riuscita",
"alert_log_successful_publish_help": "Emetti un messaggio di registro dopo la pubblicazione corretta dell'avviso nella destinazione, invece di emettere registri solo quando si verificano problemi. Aiuta nel debug degli avvisi mancanti o nel rendere controllabile la pubblicazione degli avvisi.",
"alert_policy_violation_updated_help": null,
"alert_policy_violation_updated_reviewed_help": null,
"alert_schedule_cron_expression": "Espressione di cron",
"alert_schedule_last_triggered_at": "Ultimo attivato a",
"alert_schedule_next_trigger_at": "Successivo trigger a",
Expand Down
2 changes: 2 additions & 0 deletions src/i18n/locales/ja.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
"alert_deleted": "アラートを削除しました",
"alert_log_successful_publish": "発行成功のログ",
"alert_log_successful_publish_help": "問題が発生したときにのみログを出力するのではなく、アラートが宛先に正常に発行されたときにもログ メッセージを生成します。欠落しているアラートのデバッグや、アラートの発行を検査するのに役立ちます。",
"alert_policy_violation_updated_help": null,
"alert_policy_violation_updated_reviewed_help": null,
"alert_schedule_cron_expression": "クロンの表現",
"alert_schedule_last_triggered_at": "最後にトリガーされました",
"alert_schedule_next_trigger_at": "次のトリガー",
Expand Down
2 changes: 2 additions & 0 deletions src/i18n/locales/ko.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
"alert_deleted": "알림이 삭제되었습니다",
"alert_log_successful_publish": "발행 성공 로그 기록",
"alert_log_successful_publish_help": "문제가 발생했을 때만 로그를 남기는 대신, 알림이 대상으로 성공적으로 발행될 때마다 로그 메시지를 남깁니다. 누락된 알림을 디버깅하거나 알림 발행을 감사 가능하게 만드는 데 도움이 됩니다.",
"alert_policy_violation_updated_help": null,
"alert_policy_violation_updated_reviewed_help": null,
"alert_schedule_cron_expression": "Cron 표현식",
"alert_schedule_last_triggered_at": "마지막 실행 시각",
"alert_schedule_next_trigger_at": "다음 실행 시각",
Expand Down
2 changes: 2 additions & 0 deletions src/i18n/locales/pl.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
"alert_deleted": "Alert usunięty",
"alert_log_successful_publish": "Zaloguj pomyślną publikację",
"alert_log_successful_publish_help": "Emituj komunikat dziennika po pomyślnym opublikowaniu alertu w miejscu docelowym, zamiast emitować dzienniki tylko w przypadku napotkania problemów. Pomaga w debugowaniu brakujących alertów lub umożliwieniu audytu publikowania alertów.",
"alert_policy_violation_updated_help": null,
"alert_policy_violation_updated_reviewed_help": null,
"alert_schedule_cron_expression": "Wyrażenie cron",
"alert_schedule_last_triggered_at": "Ostatnim uruchomiony",
"alert_schedule_next_trigger_at": "Następny spust",
Expand Down
2 changes: 2 additions & 0 deletions src/i18n/locales/pt-BR.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
"alert_deleted": "Alerta excluído",
"alert_log_successful_publish": "Registrar publicação bem-sucedida",
"alert_log_successful_publish_help": "Emita uma mensagem de log após a publicação bem-sucedida do alerta no destino, em vez de emitir logs apenas quando forem encontrados problemas. Ajuda a depurar alertas ausentes ou a tornar a publicação de alertas auditável.",
"alert_policy_violation_updated_help": null,
"alert_policy_violation_updated_reviewed_help": null,
"alert_schedule_cron_expression": "Expressão de Cron",
"alert_schedule_last_triggered_at": "Último desencadeado em",
"alert_schedule_next_trigger_at": "Próximo gatilho em",
Expand Down
2 changes: 2 additions & 0 deletions src/i18n/locales/pt.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
"alert_deleted": "Alerta excluído",
"alert_log_successful_publish": "Registrar publicação bem-sucedida",
"alert_log_successful_publish_help": "Emita uma mensagem de log após a publicação bem-sucedida do alerta no destino, em vez de emitir logs apenas quando forem encontrados problemas. Ajuda a depurar alertas ausentes ou a tornar a publicação de alertas auditável.",
"alert_policy_violation_updated_help": null,
"alert_policy_violation_updated_reviewed_help": null,
"alert_schedule_cron_expression": "Expressão de Cron",
"alert_schedule_last_triggered_at": "Último desencadeado em",
"alert_schedule_next_trigger_at": "Próximo gatilho em",
Expand Down
2 changes: 2 additions & 0 deletions src/i18n/locales/ru.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
"alert_deleted": "Оповещение удалено",
"alert_log_successful_publish": "Успешная публикация журнала",
"alert_log_successful_publish_help": "Создание записи в журнале при успешной публикации оповещения в пункт назначения, а не только при возникновении проблем. Полезно для отладки пропущенных оповещений или обеспечения возможности аудита публикации оповещений.",
"alert_policy_violation_updated_help": null,
"alert_policy_violation_updated_reviewed_help": null,
"alert_schedule_cron_expression": "Выражение крона",
"alert_schedule_last_triggered_at": "Последнее вызвано в",
"alert_schedule_next_trigger_at": "Следующий триггер в",
Expand Down
2 changes: 2 additions & 0 deletions src/i18n/locales/uk-UA.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
"alert_deleted": "Сповіщення видалено",
"alert_log_successful_publish": "Логувати успішну публікацію",
"alert_log_successful_publish_help": "Видавати повідомлення журналу після успішної публікації сповіщення в пункт призначення, замість того, щоб логувати лише виявлені проблеми.\nДопомагає в налагодженні відсутніх сповіщень або уможливлює аудит публікації сповіщень.",
"alert_policy_violation_updated_help": null,
"alert_policy_violation_updated_reviewed_help": null,
"alert_schedule_cron_expression": "Cron вираз",
"alert_schedule_last_triggered_at": "Востаннє спрацювало",
"alert_schedule_next_trigger_at": "Наступне спрацювання",
Expand Down
Loading