b118695474
* feat(permissions): granular permission gating + role editor & presets Make every admin feature permission-gateable so multi-user studios can split capability across roles (#747, and phase 1 of #743). - Split the catch-all settings.edit into dedicated dangerous-config perms (banking / domains / security / integrations / features): a team member can no longer change IBAN, domains, SSO, webhooks, API tokens or feature flags. Reads keep an OR with settings.view so existing roles keep visibility. The site-URL write inside /general is change-gated on settings.domains. - Add dedicated perms for admin surfaces miscategorised under settings.* (whatsapp, event_types, image_security, notifications, system) plus roles.manage and vat_codes.view; gate the previously-ungated VAT read. - Boot self-heal (_permissionsBoot.js): super_admin always holds every permission (tracks-all) so new perms never need a compensation migration; all other roles stay frozen (no silent escalation on upgrade). - Seed two presets: Solo Photographer (full operator) and Team Photographer (contributor — view events + manage photos + read-only CRM; no settings/users/billing edits, no events.edit). - Role editor: adminRoles CRUD (create/edit/clone/delete + permission matrix; system roles protected, super_admin immutable) and a Roles tab with a category-grouped matrix and preset cloning. - Settings page tabs are permission-gated with snap-back; i18n en/de. Migration 174. Backward-compatible: admin/editor/viewer unchanged. * feat(permissions): hide in-page action buttons a role can't use Wrap mutating controls on the surfaces restricted roles actually reach (Events list, Archives, gallery photo grid, event detail) in PermissionGate so they are HIDDEN when the user lacks the permission, rather than shown-then-403: - Events list: create / bulk archive / bulk delete / row archive / row delete / download-archive. - Archives: restore / download / delete. - Photo grid: single + bulk delete (photos.delete), per-photo download (photos.download), bulk move/hide/show (photos.edit). - Event detail: edit / rename / publish (events.edit), duplicate (events.create), archive (events.archive), create-invoice (bills.manage); the Actions card is hidden entirely for view-only roles. - Photos tab: upload / external import (photos.upload), export menu (photos.download). Backend already enforces these with 403; this is the matching UX so a Team Photographer never sees delete/settings controls. * fix(permissions): close settings-split bypass via generic settings writers Security review found the settings.edit split was bypassable: the generic settings writers (/general, /analytics, /seo, /security) upsert arbitrary setting_keys, so a role holding only settings.edit (or settings.security) could write keys owned by a narrower permission — repointing the public site URL (settings.domains), security policy (settings.security) or VAT/accounting config (settings.banking) via the wrong endpoint. Add stripUnauthorizedProtectedKeys(): before every generic upsert, drop any protected key the caller isn't permitted to write (general_site_url → settings.domains, security_* → settings.security, accounting_* → settings.banking). Dedicated routes still work because their caller holds the matching perm. Replaces the narrower in-handler site-URL guard. Also fix two tests affected by the RBAC changes: - authzPermissionGaps: API-token management moved to settings.integrations, so grant that (not settings.edit) to exercise the ownership 404. - AdminPhotoGrid.viewToggle: stub PermissionGate (its buttons are now gated and the test renders without a PermissionsProvider). * fix(permissions): address upstream review (#1045) - Renumber migration 174 -> 175 (174 now taken by 174_sqlite_nullable_event_dates from #1035; the collision made picpeakImportService's forward-only restore guard treat both as order 174 and accept a newer .picpeak onto an older schema). - Contain the roles.manage blast radius (delegation, not root escalation): a non-super_admin can no longer edit their own role, nor grant any permission their own role doesn't already hold (createRole + updateRole). - Protected-key denial now 403s (naming the keys + required perms) instead of silently stripping and reporting "saved" (adminSettings generic writers). - Reserve team_photographer so a custom role can't squat the preset name. - Boot self-heal: per-step try/catch so a role_permissions insert race on one replica doesn't skip preset seeding. - Forward-project the feature .manage perms that also replaced settings.edit gates (whatsapp/event_types/image_security/notifications/system), matching the settings.* split projection so the pattern is symmetric for phase-2. - Guard exports.down's roles/admin_users queries with hasTable. * fix(permissions): change-detection on protected-key 403 + commit guard tests (#1045) Round-2 review: - The protected-key 403 fired on key PRESENCE. The General tab re-posts general_site_url on every save, so a settings.edit-only role (the office manager this PR enables) got 403'd on every General save even when the URL was unchanged. Restore change-detection: compare the incoming value against the stored one and 403 only on an actual change; unchanged protected keys are dropped so the rest of the save proceeds. Only /general is affected. - Commit the self-amplification guard test (was run locally, never staged): adminRolesGuards.test.js — non-super can't grant perms it lacks, can't edit its own role, can't escalate another role; super_admin bypasses; team_photographer name reserved. - Add adminSettingsProtectedKeys.test.js pinning the change-detection: an unchanged general_site_url saves, an actual change 403s, super_admin changes it.
87 lines
3.4 KiB
JavaScript
87 lines
3.4 KiB
JavaScript
/**
|
|
* Role-editor self-amplification guard (migration 175 / adminRoles).
|
|
*
|
|
* `roles.manage` must be a DELEGATION primitive, not root escalation: a
|
|
* non-super_admin holder can only grant permissions their OWN role already
|
|
* holds, and can't edit their own role. super_admin bypasses. Pins
|
|
* userManagementService.createRole / updateRole (assertActorMayGrant).
|
|
*/
|
|
const path = require('path');
|
|
const fs = require('fs');
|
|
const os = require('os');
|
|
|
|
process.env.NODE_ENV = 'test';
|
|
process.env.TEST_DATABASE_PATH = path.join(
|
|
fs.mkdtempSync(path.join(os.tmpdir(), 'picpeak-roleguard-')), 'db.sqlite',
|
|
);
|
|
process.env.JWT_SECRET = process.env.JWT_SECRET || 'roleguard-test-secret';
|
|
process.env.STORAGE_PATH = fs.mkdtempSync(path.join(os.tmpdir(), 'picpeak-roleguard-storage-'));
|
|
|
|
const { bootCrmDb, seedMinimal, assignAdminRole } = require('../integration/helpers/crmDb');
|
|
const svc = require('../../src/services/userManagementService');
|
|
const { clearPermissionCache } = require('../../src/middleware/permissions');
|
|
|
|
describe('role editor — self-amplification guard', () => {
|
|
let db; let cleanup;
|
|
let superId; let mgrRoleId; let mgrId;
|
|
|
|
beforeAll(async () => {
|
|
({ db, cleanup } = await bootCrmDb());
|
|
({ adminId: superId } = await seedMinimal(db));
|
|
await assignAdminRole(db, superId, 'super_admin');
|
|
|
|
// A non-super role that CAN manage roles but only holds a couple of perms.
|
|
const mgrRole = await svc.createRole(
|
|
{ name: 'limited_mgr', permissions: ['roles.manage', 'events.view'] },
|
|
superId,
|
|
);
|
|
mgrRoleId = mgrRole.id;
|
|
const ins = await db('admin_users').insert({
|
|
username: 'mgr', email: 'mgr@example.com', password_hash: 'x',
|
|
role_id: mgrRoleId, must_change_password: false, created_at: new Date(),
|
|
}).returning('id');
|
|
mgrId = ins[0]?.id ?? ins[0];
|
|
clearPermissionCache();
|
|
}, 120000);
|
|
|
|
afterAll(async () => { if (cleanup) await cleanup(); });
|
|
|
|
it('super_admin can grant any permission', async () => {
|
|
const r = await svc.createRole(
|
|
{ name: 'power_role', permissions: ['settings.banking', 'users.delete'] },
|
|
superId,
|
|
);
|
|
expect(r.permissions).toEqual(expect.arrayContaining(['settings.banking', 'users.delete']));
|
|
});
|
|
|
|
it('non-super cannot grant a permission its own role lacks', async () => {
|
|
await expect(
|
|
svc.createRole({ name: 'sneaky', permissions: ['events.view', 'settings.banking'] }, mgrId),
|
|
).rejects.toThrow(/only grant permissions your own role/i);
|
|
});
|
|
|
|
it('non-super can create a role within its own permissions', async () => {
|
|
const r = await svc.createRole({ name: 'viewer_lite', permissions: ['events.view'] }, mgrId);
|
|
expect(r.permissions).toEqual(['events.view']);
|
|
});
|
|
|
|
it('non-super cannot edit its own role', async () => {
|
|
await expect(
|
|
svc.updateRole(mgrRoleId, { permissions: ['roles.manage', 'events.view'] }, mgrId),
|
|
).rejects.toThrow(/cannot edit your own role/i);
|
|
});
|
|
|
|
it('non-super cannot escalate another role beyond its own permissions', async () => {
|
|
const adminRole = await db('roles').where({ name: 'admin' }).first();
|
|
await expect(
|
|
svc.updateRole(adminRole.id, { permissions: ['settings.banking'] }, mgrId),
|
|
).rejects.toThrow(/only grant permissions your own role/i);
|
|
});
|
|
|
|
it('the built-in team_photographer name is reserved', async () => {
|
|
await expect(
|
|
svc.createRole({ name: 'team_photographer', permissions: [] }, superId),
|
|
).rejects.toThrow(/reserved/i);
|
|
});
|
|
});
|