Skip to content
Merged
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
13 changes: 13 additions & 0 deletions .changeset/35192-notification-settings-read-only.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
---
'@object-ui/app-shell': patch
'@object-ui/i18n': patch
---

fix(console): Notification Settings is read-only, with its reason, for a caller who cannot change their notification preferences

Clause-②: no
Metadata-protocol: none

An external member (the `org_external` identity, `external_default` permission set) could open the Account app's Notification Settings page and was shown every switch, the digest choice and the quiet hours as editable, yet each change answered `403`: that set grants no create or edit on `sys_notification_preference`. The page now reads the caller's own grant on that object from the console's permission answer (`/me/permissions`, through `usePermissions()`), and when the caller holds neither a create nor an edit grant it draws the same settings read-only: every control disabled, one visible line saying why (`notificationSettings.readOnly`, in every built-in locale), named by each disabled control as its accessible description, and no write sent.

What does not change: a member and an organization administrator see and use the page as before. With no permission answer mounted, the page stays writable and the server's refusal decides, as every other console grant read does. No metadata key, value, default or permission changes; the server's refusal is unchanged.
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ vi.mock('@object-ui/auth', async (importOriginal) => ({
}));

import { AdapterCtx, SchemaRendererProvider } from '@object-ui/react';
import { MePermissionsProvider, type MePermissionsAuthenticatedResponse } from '@object-ui/permissions';
import { builtInLocales } from '@object-ui/i18n/locales';
import { NotificationSettingsPage } from './NotificationSettingsPage';
import { MY_PREFERENCES_URL } from './myPreferences';
Expand Down Expand Up @@ -254,3 +255,114 @@ describe('the account app names the page', () => {
expect(await screen.findByTestId('notification-settings-matrix')).toBeInTheDocument();
});
});

/**
* Who may change the page: the caller's grant on `sys_notification_preference`,
* read from the real `MePermissionsProvider` over each persona's `/me/permissions`
* answer, shaped as the default sets serve it (plugin-security
* `default-permission-sets.ts`): `external_default` names no row for the
* object and carries no `'*'`, `member_default` grants create and edit on it,
* and `organization_admin` reaches it through its `'*'` row.
*/
describe('the caller\'s grant on sys_notification_preference decides whether the page writes', () => {
function served(objects: Record<string, Record<string, boolean>>, positions: string[]): MePermissionsAuthenticatedResponse {
return {
authenticated: true,
userId: 'alice',
tenantId: null,
positions,
hasAnyQueue: false,
objectsUsingQueues: [],
permissionSets: [],
objects,
fields: {},
} as MePermissionsAuthenticatedResponse;
}

const EXTERNAL = served(
{
sys_user: { allowRead: true, allowCreate: false, allowEdit: true, allowDelete: false },
sys_user_preference: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: false },
sys_notification_receipt: { allowRead: true, allowCreate: false, allowEdit: false, allowDelete: false },
},
['org_external'],
);
const MEMBER = served(
{ sys_notification_preference: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: false } },
['org_member'],
);
const ORG_ADMIN = served(
{
'*': { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true },
},
['org_admin'],
);

function hostAs(
permissions: MePermissionsAuthenticatedResponse,
apiFetch: ReturnType<typeof vi.fn>,
adapter: { create: ReturnType<typeof vi.fn>; update: ReturnType<typeof vi.fn> },
) {
const Inner = host(apiFetch, adapter);
return ({ children }: { children: ReactNode }) => (
<MePermissionsProvider initialPermissions={permissions}>
<Inner>{children}</Inner>
</MePermissionsProvider>
);
}

it('an external member sees every control disabled with the reason, and no write is sent', async () => {
const orgQuiet: General = { ...BUILTIN_GENERAL, quietHours: { value: { start: '22:00', end: '07:00' }, source: 'default' } };
const apiFetch = vi.fn(async () => json(answer(false, undefined, orgQuiet)));
const adapter = { create: vi.fn(), update: vi.fn() };
render(<NotificationSettingsPage />, { wrapper: hostAs(EXTERNAL, apiFetch, adapter) });

const reason = await screen.findByTestId('notification-settings-read-only');
expect(reason).toHaveTextContent('«notificationSettings.readOnly»');
const reasonId = reason.querySelector('[id]')!.id;

const cell = screen.getByTestId('notification-settings-cell-task.assigned-email');
const digest = screen.getByTestId('notification-settings-digest');
const save = screen.getByTestId('notification-settings-quiet-hours-save');
for (const control of [cell, digest, save]) {
expect(control).toBeDisabled();
expect(control).toHaveAttribute('aria-describedby', reasonId);
}
// The quiet hours read as text, not as inputs to edit.
expect(screen.queryByTestId('quiet-hours-start')).toBeNull();
// What is in force is still drawn.
expect(screen.getByTestId('notification-settings-topic-task.assigned')).toHaveTextContent('«notificationSettings.sourceDefault»');

fireEvent.click(cell);
fireEvent.change(digest, { target: { value: 'weekly' } });
fireEvent.click(save);
expect(adapter.create).not.toHaveBeenCalled();
expect(adapter.update).not.toHaveBeenCalled();
expect(apiFetch).toHaveBeenCalledTimes(1);
});

it.each([
['a member (member_default grants create and edit)', MEMBER],
['an organization administrator (the wildcard row)', ORG_ADMIN],
])('%s sees no change: no reason, and a switch writes', async (_persona, permissions) => {
const apiFetch = vi.fn().mockResolvedValueOnce(json(answer(false))).mockResolvedValueOnce(json(answer(true, 'row-new')));
const adapter = { create: vi.fn(async () => ({ id: 'row-new' })), update: vi.fn() };
render(<NotificationSettingsPage />, { wrapper: hostAs(permissions, apiFetch, adapter) });

const cell = await screen.findByTestId('notification-settings-cell-task.assigned-email');
expect(screen.queryByTestId('notification-settings-read-only')).toBeNull();
expect(cell).not.toBeDisabled();
expect(cell).not.toHaveAttribute('aria-describedby');
expect(screen.getByTestId('notification-settings-digest')).not.toBeDisabled();

fireEvent.click(cell);
await waitFor(() =>
expect(adapter.create).toHaveBeenCalledWith('sys_notification_preference', {
user_id: 'alice',
topic: 'task.assigned',
channel: 'email',
enabled: true,
}),
);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,19 @@
* Channels are columns as the door lists them, so a channel the deployment
* adds later (Slack, …) appears without a change here; a channel the
* deployment cannot send on yet says so in its header.
*
* A caller who holds neither a create nor an edit grant on
* `sys_notification_preference` (an external member: `external_default`
* grants none) sees the same page read-only: every control disabled, one
* visible reason that each control names as its description, and no write
* sent. The grant is the framework's own answer for the caller, the
* `/me/permissions` read `usePermissions()` serves; the page names no
* identity. With no permission answer at all (no provider, or not loaded
* yet) it stays writable and the server's refusal decides, as every other
* console grant read does.
*/

import { Suspense, useCallback, useContext, useEffect, useState } from 'react';
import { Suspense, useCallback, useContext, useEffect, useId, useState } from 'react';
import { BellRing } from 'lucide-react';
import { useAuth } from '@object-ui/auth';
import {
Expand All @@ -45,6 +55,7 @@ import {
} from '@object-ui/components';
import { getLazyFieldWidget } from '@object-ui/fields';
import { useObjectTranslation } from '@object-ui/i18n';
import { usePermissions } from '@object-ui/permissions';
import { SchemaRendererContext, useAdapter } from '@object-ui/react';
import { PageHeader } from '../../layout/PageHeader.js';
import {
Expand All @@ -53,6 +64,7 @@ import {
quietHoursSaveable,
generalWrite,
loadMyPreferences,
PREFERENCE_OBJECT,
PREFERENCE_WILDCARD,
sendPreferenceWrite,
type DigestCadence,
Expand Down Expand Up @@ -91,6 +103,12 @@ export function NotificationSettingsPage() {
const { user } = useAuth();
const adapter = useAdapter();
const apiFetch = useContext(SchemaRendererContext)?.apiFetch;
const perms = usePermissions();
// A write is a create (no own row yet) or an edit (the person's own row):
// holding neither, every control is read-only.
const writeGranted =
!perms.isLoaded || perms.can(PREFERENCE_OBJECT, 'create') || perms.can(PREFERENCE_OBJECT, 'update');
const readOnlyReasonId = useId();
const [load, setLoad] = useState<Load>({ state: 'loading' });
const [saving, setSaving] = useState(false);
const [saveError, setSaveError] = useState<string | null>(null);
Expand Down Expand Up @@ -118,7 +136,7 @@ export function NotificationSettingsPage() {

const apply = useCallback(
async (write: PreferenceWrite | null) => {
if (!write || !adapter) return;
if (!write || !adapter || !writeGranted) return;
setSaving(true);
setSaveError(null);
try {
Expand All @@ -131,7 +149,7 @@ export function NotificationSettingsPage() {
setSaving(false);
}
},
[adapter, read],
[adapter, read, writeGranted],
);

const header = (
Expand Down Expand Up @@ -163,7 +181,9 @@ export function NotificationSettingsPage() {

const { prefs } = load;
const userId = user?.id;
const canWrite = !!userId && !!adapter && !saving;
const canWrite = !!userId && !!adapter && !saving && writeGranted;
// Every disabled control names the one visible reason as its description.
const readOnlyDescribedBy = writeGranted ? undefined : readOnlyReasonId;
const quietValue = quietDraft === undefined ? prefs.general.quietHours.value : quietDraft;

const topicLabel = (topic: PreferenceTopic) =>
Expand All @@ -176,6 +196,11 @@ export function NotificationSettingsPage() {
<div data-testid="notification-settings-page">
{header}
<div className="space-y-6 p-4 sm:p-6">
{!writeGranted && (
<Alert data-testid="notification-settings-read-only">
<AlertDescription id={readOnlyReasonId}>{t('notificationSettings.readOnly')}</AlertDescription>
</Alert>
)}
{saveError !== null && (
<Alert variant="destructive" data-testid="notification-settings-save-failed">
<AlertDescription>{t('notificationSettings.saveFailed', { reason: saveError })}</AlertDescription>
Expand All @@ -196,6 +221,7 @@ export function NotificationSettingsPage() {
className="block h-9 w-full max-w-xs rounded-md border bg-background px-2 text-sm"
value={prefs.general.digest.value}
disabled={!canWrite}
aria-describedby={readOnlyDescribedBy}
onChange={(e) => {
const digest = e.target.value as DigestCadence;
// `none` is offered only while it is already the value, so it never reaches a write.
Expand Down Expand Up @@ -232,6 +258,7 @@ export function NotificationSettingsPage() {
size="sm"
data-testid="notification-settings-quiet-hours-save"
disabled={!canWrite || !quietHoursSaveable(quietDraft)}
aria-describedby={readOnlyDescribedBy}
onClick={() => {
if (quietHoursSaveable(quietDraft)) void apply(generalWrite(userId!, prefs.general, { quiet_hours: quietDraft }));
}}
Expand Down Expand Up @@ -294,6 +321,7 @@ export function NotificationSettingsPage() {
data-testid={`notification-settings-cell-${topic.topic}-${c.channel}`}
checked={cell.enabled}
disabled={!canWrite || topic.mandatory}
aria-describedby={readOnlyDescribedBy}
onCheckedChange={(on: boolean) => void apply(cellWrite(userId!, topic, cell, on))}
/>
<span className="text-xs text-muted-foreground">{t(SOURCE_KEY[cell.source])}</span>
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/ar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5821,6 +5821,7 @@ const ar = {
loading: "جارٍ تحميل إعدادات الإشعارات…",
loadFailed: "تعذّرت قراءة إعدادات الإشعارات. أعد تحميل الصفحة وحاول مرة أخرى.",
saveFailed: "لم يُحفظ التغيير: {{reason}}",
readOnly: "يمكنك عرض هذه الإعدادات، لكن صلاحياتك لا تسمح لك بتغييرها. يمكن لمسؤول في مؤسستك تغييرها نيابةً عنك.",
general: "عام",
generalWarning: "يؤدي تغيير الملخص أو ساعات الهدوء إلى حفظ إعدادك العام الخاص. ويسري بعدها على كل موضوع وقناة لم تضبطهما بنفسك، بدلاً من الإعدادات الافتراضية لمؤسستك.",
digest: "الملخص",
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/de.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5223,6 +5223,7 @@ const de = {
loading: "Ihre Benachrichtigungseinstellungen werden geladen…",
loadFailed: "Ihre Benachrichtigungseinstellungen konnten nicht gelesen werden. Laden Sie die Seite neu und versuchen Sie es erneut.",
saveFailed: "Die Änderung wurde nicht gespeichert: {{reason}}",
readOnly: "Sie können diese Einstellungen ansehen, aber Ihre Berechtigungen erlauben keine Änderung. Eine Administratorin oder ein Administrator Ihrer Organisation kann sie für Sie ändern.",
general: "Allgemein",
generalWarning: "Wenn Sie Zusammenfassung oder Ruhezeiten ändern, wird Ihre eigene allgemeine Einstellung gespeichert. Sie gilt dann für jedes Thema und jeden Kanal, die Sie nicht selbst festgelegt haben, anstelle der Standardwerte Ihrer Organisation.",
digest: "Zusammenfassung",
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6139,6 +6139,7 @@ const en = {
loading: "Loading your notification settings…",
loadFailed: "Could not read your notification settings. Reload the page to try again.",
saveFailed: "The change was not saved: {{reason}}",
readOnly: "You can view these settings, but your access does not let you change them. An administrator of your organization can change them for you.",
general: "General",
generalWarning: "Changing your digest or quiet hours saves your own general setting. It then applies to every topic and channel you have not set yourself, in place of your organization's defaults.",
digest: "Digest",
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/es.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5372,6 +5372,7 @@ const es = {
loading: "Cargando tu configuración de notificaciones…",
loadFailed: "No se pudo leer tu configuración de notificaciones. Recarga la página para intentarlo de nuevo.",
saveFailed: "El cambio no se guardó: {{reason}}",
readOnly: "Puedes ver estos ajustes, pero tus permisos no te permiten cambiarlos. Un administrador de tu organización puede cambiarlos por ti.",
general: "General",
generalWarning: "Al cambiar el resumen o las horas de silencio se guarda tu propia configuración general. A partir de entonces se aplica a cada tema y canal que no hayas configurado tú, en lugar de los valores predeterminados de tu organización.",
digest: "Resumen",
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/fr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5368,6 +5368,7 @@ const fr = {
loading: "Chargement de vos paramètres de notification…",
loadFailed: "Impossible de lire vos paramètres de notification. Rechargez la page pour réessayer.",
saveFailed: "La modification n'a pas été enregistrée : {{reason}}",
readOnly: "Vous pouvez consulter ces paramètres, mais vos droits ne vous permettent pas de les modifier. Un administrateur de votre organisation peut les modifier pour vous.",
general: "Général",
generalWarning: "Modifier le résumé ou les heures calmes enregistre votre propre paramètre général. Il s'applique ensuite à chaque sujet et canal que vous n'avez pas réglés vous-même, à la place des valeurs par défaut de votre organisation.",
digest: "Résumé",
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/ja.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5224,6 +5224,7 @@ const ja = {
loading: "通知設定を読み込んでいます…",
loadFailed: "通知設定を読み込めませんでした。ページを再読み込みしてもう一度お試しください。",
saveFailed: "変更は保存されませんでした: {{reason}}",
readOnly: "これらの設定は表示できますが、あなたの権限では変更できません。組織の管理者が代わりに変更できます。",
general: "全般",
generalWarning: "ダイジェストやおやすみ時間を変更すると、あなた自身の全般設定が保存されます。以後、個別に設定していないすべてのトピックとチャネルで、組織の既定値の代わりにこの設定が適用されます。",
digest: "ダイジェスト",
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/ko.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5221,6 +5221,7 @@ const ko = {
loading: "알림 설정을 불러오는 중…",
loadFailed: "알림 설정을 읽을 수 없습니다. 페이지를 새로 고친 후 다시 시도하세요.",
saveFailed: "변경 내용이 저장되지 않았습니다: {{reason}}",
readOnly: "이 설정을 볼 수는 있지만 권한이 없어 변경할 수 없습니다. 조직 관리자가 대신 변경할 수 있습니다.",
general: "일반",
generalWarning: "요약 또는 방해 금지 시간을 변경하면 본인의 일반 설정이 저장됩니다. 이후 직접 설정하지 않은 모든 주제와 채널에 조직 기본값 대신 이 설정이 적용됩니다.",
digest: "요약",
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/pt-BR.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5367,6 +5367,7 @@ const pt = {
loading: "Carregando suas configurações de notificação…",
loadFailed: "Não foi possível ler suas configurações de notificação. Recarregue a página para tentar novamente.",
saveFailed: "A alteração não foi salva: {{reason}}",
readOnly: "Você pode ver estas configurações, mas suas permissões não permitem alterá-las. Um administrador da sua organização pode alterá-las por você.",
general: "Geral",
generalWarning: "Alterar o resumo ou o horário silencioso salva sua própria configuração geral. A partir daí ela vale para todo tópico e canal que você não configurou, no lugar dos padrões da sua organização.",
digest: "Resumo",
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/ru.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5530,6 +5530,7 @@ const ru = {
loading: "Загрузка настроек уведомлений…",
loadFailed: "Не удалось прочитать ваши настройки уведомлений. Перезагрузите страницу и попробуйте снова.",
saveFailed: "Изменение не сохранено: {{reason}}",
readOnly: "Вы можете просматривать эти настройки, но ваши права не позволяют их изменять. Администратор вашей организации может изменить их за вас.",
general: "Общие",
generalWarning: "Изменение сводки или тихих часов сохраняет вашу собственную общую настройку. После этого она действует для каждой темы и канала, которые вы не настроили сами, вместо значений вашей организации по умолчанию.",
digest: "Сводка",
Expand Down
Loading
Loading