fix(rbac): permission-gate alerts, auto-heal, and image updates (#1743)

* fix: gate alerts and auto-heal routes on stack:edit/stack:read permissions

Replace requireAdmin with requirePermission across backend/src/routes/alerts.ts
and backend/src/routes/autoHeal.ts, mirroring the stack:read/stack:edit model
already used by stacks, blueprints, git sources, and settings. Adds the
previously-missing permission gate on the auto-heal history route, and adds
ownership-aware deletion for alerts via a new DatabaseService.getStackAlert(id)
lookup.

* fix: gate image-update fleet, per-stack refresh, and auto-update execute on RBAC permissions

Replace requireAdmin with requirePermission/checkPermission across
backend/src/routes/imageUpdates.ts (imageUpdatesRouter and autoUpdateRouter),
mirroring the permission-aware model already used by alerts and auto-heal.

GET /fleet drops its admin gate to match the auth-only read model shared with
GET / and /detail. POST /fleet/refresh now requires node:manage. A new route,
POST /refresh/:stackName, lets a caller with stack:deploy on that stack trigger
a per-stack recheck, distinct from the node-wide POST /refresh. The auto-update
executor now pre-checks stack:deploy across every resolved target before any
work starts, so a denied stack in a bulk request fails the whole call instead
of partially executing; the "*" wildcard additionally requires global
stack:deploy up front since it expands to every stack on the node, including
the empty case where a per-stack check would otherwise have nothing to gate.

* fix: evaluate permission before checks-enabled state in auto-update execute

The checks-enabled short-circuit in autoUpdateRouter POST /execute ran before
target parsing and before any permission check, so a node with image-update
checks disabled returned 200 to any authenticated caller regardless of
stack:deploy grants. Move the checks-enabled check to run after the resolved
stackNames have cleared requireExactStacks, so permission is always evaluated
first.

Add coverage: a denied role still gets 403 PERMISSION_DENIED (not the
disabled-checks 200) while checks are disabled node-wide, and a scoped-only
user whose stack:deploy grant covers every stack on the node is still denied
target="*" (the wildcard requires global stack:deploy, per the earlier fix),
proving that tradeoff against a real on-disk stack rather than the always-
empty fresh test instance.

* fix: gate alerts, auto-heal, and image-update controls on frontend permission checks

Match the backend RBAC gates for alerts, auto-heal, and per-stack image
updates with matching frontend checks, replacing raw isAdmin/node:manage
gates with scoped can() calls:

- Alerts/Auto-Heal menu items and their keyboard shortcuts now gate on
  stack:read (canViewMonitor), including the window-level keyboard
  shortcut handler that previously bypassed the menu item gate entirely.
- Check updates now gates on stack:deploy (previously node:manage) and
  calls the new per-stack POST /image-updates/refresh/:stackName
  endpoint instead of the node-wide refresh. Since the endpoint runs the
  recheck synchronously and returns the result directly, the old
  node-wide /status polling loop is removed in favor of handling the
  response inline.
- StackAlertSheet's alert and auto-heal policy mutation controls gate on
  stack:edit instead of isAdmin.
- The Fleet Image Updates refresh button (mobile and desktop) gates on
  node:manage, hidden rather than disabled to match the existing
  convention for node:manage-gated affordances.

* fix: cover the stack:edit deny path for StackAlertSheet gates

The useAuth mock in StackAlertSheet.test.tsx returned can: () => true
unconditionally, so canEditAlerts, canEditAutoHeal, and PolicyRow's
canEdit prop were never exercised with a denial. Make the mock
per-test-controllable (matching the vi.fn() pattern already used in
NodeCard.test.tsx) and add one deny-path test per tab asserting the
mutation controls are absent while reads stay visible.

Also adds an aria-label to the alert row's delete button so the deny
test can assert on its absence, matching the aria-label convention
PolicyRow's own toggle/delete controls already use.

* fix: surface accurate warnings and loading feedback on stack update checks

checkUpdatesForStack ignored the backend's StackRecheckResult outcome
and always showed a success toast, even when verification failed or
an update is still present. It also gave no feedback while the
multi-second per-image registry probe was in flight.

Add a loading toast on request start, and branch the result toast on
outcome/warning instead of unconditional success. The backend reuses
its post-update reconciliation copy for this pre-update discovery
check, so the two generic "update command completed" strings are
replaced with accurate pre-update wording; a genuine stack-specific
warning (e.g. a compose render failure) is still shown as-is.

Also update docs/features/rbac.mdx: stack:edit now covers alert and
auto-heal management, stack:deploy covers per-stack image-update
checks, and the Deployer role description reflects both.

* fix: add per-stack cooldown rate limit for image-update recheck route

The per-stack POST /refresh/:stackName route bypassed the existing
node-wide manual-refresh cooldown. A caller with stack:deploy could
hammer the registry with unbounded concurrent recheck calls.

Add tryMarkStackRecheck in ImageUpdateService, sharing the same
2-minute cooldown window, keyed per (nodeId, stackName). The route
handler returns 429 when denied. The mark is written synchronously
before the first await so concurrent calls on the same tick are blocked.
This commit is contained in:
Anso
2026-08-01 21:07:21 -04:00
committed by GitHub
parent 5cc4566eb1
commit 15801318d6
22 changed files with 1095 additions and 129 deletions
+159 -12
View File
@@ -4,18 +4,35 @@
*/
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
import request from 'supertest';
import jwt from 'jsonwebtoken';
import bcrypt from 'bcrypt';
import { setupTestDb, cleanupTestDb, loginAsTestAdmin } from './helpers/setupTestDb';
import { setupTestDb, cleanupTestDb, loginAsTestAdmin, TEST_JWT_SECRET } from './helpers/setupTestDb';
let tmpDir: string;
let app: import('express').Express;
let DatabaseService: typeof import('../services/DatabaseService').DatabaseService;
let ROLE_PERMISSIONS: typeof import('../middleware/permissions').ROLE_PERMISSIONS;
let authCookie: string;
let viewerCookie: string;
type SeedRole = 'admin' | 'node-admin' | 'deployer' | 'viewer' | 'auditor';
/** Seed a user with the given role and return a signed bearer token for it. */
async function seedRoleToken(username: string, role: SeedRole): Promise<string> {
const db = DatabaseService.getInstance();
let user = db.getUserByUsername(username);
if (!user) {
const hash = await bcrypt.hash('password123', 1);
db.addUser({ username, password_hash: hash, role });
user = db.getUserByUsername(username);
}
return jwt.sign({ username, role, tv: user!.token_version }, TEST_JWT_SECRET, { expiresIn: '5m' });
}
beforeAll(async () => {
tmpDir = await setupTestDb();
({ DatabaseService } = await import('../services/DatabaseService'));
({ ROLE_PERMISSIONS } = await import('../middleware/permissions'));
// Mock LicenseService so paid-gated routes are accessible
const { LicenseService } = await import('../services/LicenseService');
@@ -67,6 +84,23 @@ describe('GET /api/alerts', () => {
expect(res.body.length).toBe(1);
expect(res.body[0].stack_name).toBe('web');
});
it('denies a role without stack:read with 403 PERMISSION_DENIED', async () => {
// Every shipped role carries stack:read, so the denial path is exercised
// by temporarily removing it from viewer at runtime, proving the added
// gate actually runs rather than being a no-op.
const original = ROLE_PERMISSIONS.viewer;
ROLE_PERMISSIONS.viewer = original.filter((p) => p !== 'stack:read');
try {
const res = await request(app)
.get('/api/alerts')
.set('Cookie', viewerCookie);
expect(res.status).toBe(403);
expect(res.body.code).toBe('PERMISSION_DENIED');
} finally {
ROLE_PERMISSIONS.viewer = original;
}
});
});
// --- POST /api/alerts ---
@@ -79,13 +113,30 @@ describe('POST /api/alerts', () => {
expect(res.status).toBe(401);
});
it('rejects non-admin users with 403', async () => {
const res = await request(app)
.post('/api/alerts')
.set('Cookie', viewerCookie)
.send({ stack_name: 'test', metric: 'cpu_percent', operator: '>', threshold: 80, duration_mins: 5, cooldown_mins: 60 });
expect(res.status).toBe(403);
});
it.each(['viewer', 'deployer', 'auditor'] as const)(
'rejects %s with 403 PERMISSION_DENIED (lacks stack:edit)',
async (role) => {
const token = await seedRoleToken(`alerts-post-${role}`, role);
const res = await request(app)
.post('/api/alerts')
.set('Authorization', `Bearer ${token}`)
.send({ stack_name: 'perm-gate-post', metric: 'cpu_percent', operator: '>', threshold: 80, duration_mins: 5, cooldown_mins: 60 });
expect(res.status).toBe(403);
expect(res.body.code).toBe('PERMISSION_DENIED');
},
);
it.each(['admin', 'node-admin'] as const)(
'lets %s pass the permission gate',
async (role) => {
const token = await seedRoleToken(`alerts-post-${role}`, role);
const res = await request(app)
.post('/api/alerts')
.set('Authorization', `Bearer ${token}`)
.send({ stack_name: `perm-gate-post-${role}`, metric: 'cpu_percent', operator: '>', threshold: 80, duration_mins: 5, cooldown_mins: 60 });
expect(res.status).toBe(201);
},
);
it('creates alert and returns 201 with created resource', async () => {
const payload = {
@@ -282,11 +333,107 @@ describe('DELETE /api/alerts/:id', () => {
expect(res.status).toBe(401);
});
it('rejects non-admin users with 403', async () => {
it.each(['viewer', 'deployer', 'auditor'] as const)(
'rejects %s with 403 PERMISSION_DENIED (lacks stack:edit)',
async (role) => {
const alert = DatabaseService.getInstance().addStackAlert({
stack_name: `delete-gate-deny-${role}`,
service_name: null,
metric: 'cpu_percent',
operator: '>',
threshold: 90,
duration_mins: 0,
cooldown_mins: 0,
});
const token = await seedRoleToken(`alerts-delete-${role}`, role);
const res = await request(app)
.delete(`/api/alerts/${alert.id}`)
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(403);
expect(res.body.code).toBe('PERMISSION_DENIED');
},
);
it.each(['admin', 'node-admin'] as const)(
'lets %s delete',
async (role) => {
const alert = DatabaseService.getInstance().addStackAlert({
stack_name: `delete-gate-allow-${role}`,
service_name: null,
metric: 'cpu_percent',
operator: '>',
threshold: 90,
duration_mins: 0,
cooldown_mins: 0,
});
const token = await seedRoleToken(`alerts-delete-${role}`, role);
const res = await request(app)
.delete(`/api/alerts/${alert.id}`)
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(200);
expect(res.body.success).toBe(true);
},
);
it('returns 404 for a nonexistent alert id', async () => {
const res = await request(app)
.delete('/api/alerts/1')
.set('Cookie', viewerCookie);
expect(res.status).toBe(403);
.delete('/api/alerts/99999')
.set('Cookie', authCookie);
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: 'Alert not found' });
});
it("authorizes against the alert's own stack, not a caller's scoped grant on a different stack", async () => {
const db = DatabaseService.getInstance();
const defaultNodeId = db.getDefaultNode()!.id!;
const hash = await bcrypt.hash('password123', 1);
const userId = db.addUser({ username: 'alerts-scoped-editor', password_hash: hash, role: 'viewer' });
db.addRoleAssignment({
user_id: userId,
role: 'node-admin',
resource_type: 'stack',
resource_id: 'scoped-allowed-stack',
node_id: defaultNodeId,
});
const user = db.getUserByUsername('alerts-scoped-editor')!;
const token = jwt.sign({ username: user.username, role: user.role, tv: user.token_version }, TEST_JWT_SECRET, { expiresIn: '5m' });
try {
// The scoped grant only covers 'scoped-allowed-stack', so an alert
// belonging to a different stack must still be denied.
const deniedAlert = db.addStackAlert({
stack_name: 'scoped-other-stack',
service_name: null,
metric: 'cpu_percent',
operator: '>',
threshold: 90,
duration_mins: 0,
cooldown_mins: 0,
});
const deniedRes = await request(app)
.delete(`/api/alerts/${deniedAlert.id}`)
.set('Authorization', `Bearer ${token}`);
expect(deniedRes.status).toBe(403);
expect(deniedRes.body.code).toBe('PERMISSION_DENIED');
const allowedAlert = db.addStackAlert({
stack_name: 'scoped-allowed-stack',
service_name: null,
metric: 'cpu_percent',
operator: '>',
threshold: 90,
duration_mins: 0,
cooldown_mins: 0,
});
const allowedRes = await request(app)
.delete(`/api/alerts/${allowedAlert.id}`)
.set('Authorization', `Bearer ${token}`);
expect(allowedRes.status).toBe(200);
expect(allowedRes.body.success).toBe(true);
} finally {
db.deleteRoleAssignmentsByUser(userId);
db.deleteUser(userId);
}
});
it('deletes existing alert rule', async () => {
+96 -10
View File
@@ -11,6 +11,9 @@ let tmpDir: string;
let app: import('express').Express;
let DatabaseService: typeof import('../services/DatabaseService').DatabaseService;
let LicenseService: typeof import('../services/LicenseService').LicenseService;
let ROLE_PERMISSIONS: typeof import('../middleware/permissions').ROLE_PERMISSIONS;
type SeedRole = 'admin' | 'node-admin' | 'deployer' | 'viewer' | 'auditor';
function userToken(username: string): string {
const user = DatabaseService.getInstance().getUserByUsername(username);
@@ -18,6 +21,14 @@ function userToken(username: string): string {
return jwt.sign({ username, role: user.role, tv: user.token_version }, TEST_JWT_SECRET, { expiresIn: '5m' });
}
/** Seed a user with the given role if it doesn't already exist. */
async function seedRoleUser(username: string, role: SeedRole): Promise<void> {
const db = DatabaseService.getInstance();
if (db.getUserByUsername(username)) return;
const hash = await bcrypt.hash('password123', 1);
db.addUser({ username, password_hash: hash, role });
}
function createApiToken(scope: 'read-only' | 'deploy-only' | 'full-admin'): string {
const rawToken = generateApiToken();
const tokenHash = crypto.createHash('sha256').update(rawToken).digest('hex');
@@ -57,6 +68,7 @@ beforeAll(async () => {
tmpDir = await setupTestDb();
({ DatabaseService } = await import('../services/DatabaseService'));
({ LicenseService } = await import('../services/LicenseService'));
({ ROLE_PERMISSIONS } = await import('../middleware/permissions'));
vi.spyOn(LicenseService.getInstance(), 'getTier').mockReturnValue('paid');
const viewerHash = await bcrypt.hash('password123', 1);
@@ -132,17 +144,52 @@ describe('/api/auto-heal routes', () => {
expect(res.body.proxy_entitled_until).toBe(0);
});
it('rejects non-admin policy mutation', async () => {
const res = await request(app)
.post('/api/auto-heal/policies')
.set('Authorization', `Bearer ${userToken('route-viewer')}`)
.send({
stack_name: 'route-stack',
unhealthy_duration_mins: 5,
});
it.each(['viewer', 'deployer', 'auditor'] as const)(
'rejects %s policy mutation with 403 PERMISSION_DENIED',
async (role) => {
await seedRoleUser(`auto-heal-post-${role}`, role);
const res = await request(app)
.post('/api/auto-heal/policies')
.set('Authorization', `Bearer ${userToken(`auto-heal-post-${role}`)}`)
.send({
stack_name: 'route-stack',
unhealthy_duration_mins: 5,
});
expect(res.status).toBe(403);
expect(res.body.code).toBe('ADMIN_REQUIRED');
expect(res.status).toBe(403);
expect(res.body.code).toBe('PERMISSION_DENIED');
},
);
it.each(['admin', 'node-admin'] as const)(
'lets %s pass the policy mutation permission gate',
async (role) => {
await seedRoleUser(`auto-heal-post-${role}`, role);
const res = await request(app)
.post('/api/auto-heal/policies')
.set('Authorization', `Bearer ${userToken(`auto-heal-post-${role}`)}`)
.send({
stack_name: `route-stack-${role}`,
unhealthy_duration_mins: 5,
});
expect(res.status).toBe(201);
},
);
it('denies policy listing with 403 PERMISSION_DENIED when the caller lacks stack:read', async () => {
const original = ROLE_PERMISSIONS.viewer;
ROLE_PERMISSIONS.viewer = original.filter((p) => p !== 'stack:read');
try {
const res = await request(app)
.get('/api/auto-heal/policies')
.set('Authorization', `Bearer ${userToken('route-viewer')}`);
expect(res.status).toBe(403);
expect(res.body.code).toBe('PERMISSION_DENIED');
} finally {
ROLE_PERMISSIONS.viewer = original;
}
});
it('lists only policies for the active node', async () => {
@@ -178,6 +225,45 @@ describe('/api/auto-heal routes', () => {
expect(res.status).toBe(404);
});
it('denies history access with 403 PERMISSION_DENIED when the caller lacks stack:read', async () => {
// Every shipped role carries stack:read, so the denial path is exercised
// by temporarily removing it from viewer at runtime. This proves the
// permission check that was previously entirely absent from this route
// actually runs.
const defaultNodeId = DatabaseService.getInstance().getDefaultNode()?.id ?? 1;
const policy = makePolicy(defaultNodeId, 'history-perm-gate-stack');
const original = ROLE_PERMISSIONS.viewer;
ROLE_PERMISSIONS.viewer = original.filter((p) => p !== 'stack:read');
try {
const res = await request(app)
.get(`/api/auto-heal/policies/${policy.id}/history`)
.set('Authorization', `Bearer ${userToken('route-viewer')}`);
expect(res.status).toBe(403);
expect(res.body.code).toBe('PERMISSION_DENIED');
} finally {
ROLE_PERMISSIONS.viewer = original;
}
});
it('returns 404 for a wrong-node policy id before the permission check runs', async () => {
// A viewer lacks stack:edit, so if the permission check ran before the
// node-ownership check, this would 403 PERMISSION_DENIED instead of 404.
const secondNodeId = insertLegacyLocal('ordering-second-local');
const policy = makePolicy(secondNodeId, 'ordering-stack');
const patchRes = await request(app)
.patch(`/api/auto-heal/policies/${policy.id}`)
.set('Authorization', `Bearer ${userToken('route-viewer')}`)
.send({ enabled: 0 });
expect(patchRes.status).toBe(404);
const deleteRes = await request(app)
.delete(`/api/auto-heal/policies/${policy.id}`)
.set('Authorization', `Bearer ${userToken('route-viewer')}`);
expect(deleteRes.status).toBe(404);
});
it('persists enabled toggles through the patch route', async () => {
const defaultNodeId = DatabaseService.getInstance().getDefaultNode()?.id ?? 1;
const policy = makePolicy(defaultNodeId, 'toggle-stack');
@@ -3,10 +3,13 @@
* Locks down auth, admin gating, rate limiting, and input validation
* before extraction.
*/
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
import { describe, it, expect, beforeEach, afterEach, beforeAll, afterAll, vi } from 'vitest';
import request from 'supertest';
import bcrypt from 'bcrypt';
import { setupTestDb, cleanupTestDb, loginAsTestAdmin } from './helpers/setupTestDb';
import jwt from 'jsonwebtoken';
import fs from 'fs';
import path from 'path';
import { setupTestDb, cleanupTestDb, loginAsTestAdmin, TEST_JWT_SECRET } from './helpers/setupTestDb';
let tmpDir: string;
let app: import('express').Express;
@@ -14,6 +17,24 @@ let DatabaseService: typeof import('../services/DatabaseService').DatabaseServic
let adminCookie: string;
let viewerCookie: string;
/** Sign a JWT for an already-seeded user, using their live token_version. */
function userToken(username: string): string {
const user = DatabaseService.getInstance().getUserByUsername(username);
if (!user) throw new Error(`missing test user ${username}`);
return jwt.sign({ username, role: user.role, tv: user.token_version }, TEST_JWT_SECRET, { expiresIn: '5m' });
}
/** Write a minimal on-disk stack so FileSystemService.getStacks() resolves it. */
function makeOnDiskStack(name: string): void {
const composeDir = process.env.COMPOSE_DIR as string;
fs.mkdirSync(path.join(composeDir, name), { recursive: true });
fs.writeFileSync(path.join(composeDir, name, 'docker-compose.yml'), 'services: {}\n');
}
function removeOnDiskStack(name: string): void {
fs.rmSync(path.join(process.env.COMPOSE_DIR as string, name), { recursive: true, force: true });
}
beforeAll(async () => {
tmpDir = await setupTestDb();
({ DatabaseService } = await import('../services/DatabaseService'));
@@ -29,6 +50,12 @@ beforeAll(async () => {
const viewerRes = await request(app).post('/api/auth/login').send({ username: 'iu-viewer', password: 'viewerpass' });
const cookies = viewerRes.headers['set-cookie'] as string | string[];
viewerCookie = Array.isArray(cookies) ? cookies[0] : cookies;
const deployerHash = await bcrypt.hash('deployerpass', 1);
DatabaseService.getInstance().addUser({ username: 'iu-deployer', password_hash: deployerHash, role: 'deployer' });
const nodeAdminHash = await bcrypt.hash('nodeadminpass', 1);
DatabaseService.getInstance().addUser({ username: 'iu-node-admin', password_hash: nodeAdminHash, role: 'node-admin' });
});
afterAll(() => cleanupTestDb(tmpDir));
@@ -98,6 +125,135 @@ describe('POST /api/image-updates/refresh', () => {
});
});
describe('POST /api/image-updates/refresh/:stackName', () => {
it('rejects unauthenticated requests with 401', async () => {
const res = await request(app).post('/api/image-updates/refresh/some-stack');
expect(res.status).toBe(401);
});
it('rejects an invalid stack name with 400', async () => {
const res = await request(app)
.post(`/api/image-updates/refresh/${encodeURIComponent('bad name')}`)
.set('Cookie', adminCookie);
expect(res.status).toBe(400);
expect(res.body.error).toMatch(/Invalid stack name/);
});
it('rejects a role without stack:deploy with 403 PERMISSION_DENIED', async () => {
const res = await request(app)
.post('/api/image-updates/refresh/per-stack-refresh')
.set('Cookie', viewerCookie);
expect(res.status).toBe(403);
expect(res.body.code).toBe('PERMISSION_DENIED');
});
it('allows a Deployer to trigger a per-stack recheck', async () => {
const { ImageUpdateService } = await import('../services/ImageUpdateService');
const nodeId = DatabaseService.getInstance().getDefaultNode()!.id!;
const recheckSpy = vi.spyOn(ImageUpdateService.getInstance(), 'recheckStack')
.mockResolvedValue({ outcome: 'cleared', warning: null });
try {
const res = await request(app)
.post('/api/image-updates/refresh/per-stack-refresh')
.set('Authorization', `Bearer ${userToken('iu-deployer')}`);
expect(res.status).toBe(200);
expect(res.body).toEqual({ outcome: 'cleared', warning: null });
expect(recheckSpy).toHaveBeenCalledWith(nodeId, 'per-stack-refresh');
} finally {
recheckSpy.mockRestore();
}
});
it('returns 409 with enabled false when checks are disabled', async () => {
DatabaseService.getInstance().updateGlobalSetting('image_update_checks_enabled', '0');
const res = await request(app)
.post('/api/image-updates/refresh/per-stack-refresh')
.set('Cookie', adminCookie);
expect(res.status).toBe(409);
expect(res.body.enabled).toBe(false);
expect(res.body.error).toMatch(/disabled/i);
DatabaseService.getInstance().updateGlobalSetting('image_update_checks_enabled', '1');
});
describe('rate limit', () => {
beforeEach(async () => {
const { ImageUpdateService } = await import('../services/ImageUpdateService');
ImageUpdateService.getInstance().resetStackRecheckCooldowns();
vi.useFakeTimers().setSystemTime(Date.now());
});
afterEach(() => {
vi.useRealTimers();
});
it('rejects a second recheck within the cooldown window with 429', async () => {
const { ImageUpdateService } = await import('../services/ImageUpdateService');
const recheckSpy = vi.spyOn(ImageUpdateService.getInstance(), 'recheckStack')
.mockResolvedValue({ outcome: 'cleared', warning: null });
try {
const first = await request(app)
.post('/api/image-updates/refresh/per-stack-refresh')
.set('Cookie', adminCookie);
expect(first.status).toBe(200);
// Within the same cooldown window (2 min), a second call is denied.
vi.advanceTimersByTime(1_000);
const second = await request(app)
.post('/api/image-updates/refresh/per-stack-refresh')
.set('Cookie', adminCookie);
expect(second.status).toBe(429);
expect(second.body.error).toMatch(/too recently/i);
expect(recheckSpy).toHaveBeenCalledTimes(1);
} finally {
recheckSpy.mockRestore();
}
});
it('allows a recheck after the cooldown window expires', async () => {
const { ImageUpdateService } = await import('../services/ImageUpdateService');
const recheckSpy = vi.spyOn(ImageUpdateService.getInstance(), 'recheckStack')
.mockResolvedValue({ outcome: 'cleared', warning: null });
try {
const first = await request(app)
.post('/api/image-updates/refresh/per-stack-refresh')
.set('Cookie', adminCookie);
expect(first.status).toBe(200);
// Advance past the 2-minute cooldown.
vi.advanceTimersByTime(2 * 60 * 1000 + 1);
const second = await request(app)
.post('/api/image-updates/refresh/per-stack-refresh')
.set('Cookie', adminCookie);
expect(second.status).toBe(200);
expect(recheckSpy).toHaveBeenCalledTimes(2);
} finally {
recheckSpy.mockRestore();
}
});
it('enforces the rate limit independently per-stack', async () => {
const { ImageUpdateService } = await import('../services/ImageUpdateService');
const recheckSpy = vi.spyOn(ImageUpdateService.getInstance(), 'recheckStack')
.mockResolvedValue({ outcome: 'cleared', warning: null });
try {
const a1 = await request(app)
.post('/api/image-updates/refresh/per-stack-refresh')
.set('Cookie', adminCookie);
expect(a1.status).toBe(200);
// A different stack should not be rate-limited by the first.
const b1 = await request(app)
.post('/api/image-updates/refresh/other-stack')
.set('Cookie', adminCookie);
expect(b1.status).toBe(200);
expect(recheckSpy).toHaveBeenCalledTimes(2);
} finally {
recheckSpy.mockRestore();
}
});
});
});
describe('GET /api/image-updates/status', () => {
it('rejects unauthenticated requests with 401', async () => {
const res = await request(app).get('/api/image-updates/status');
@@ -309,11 +465,12 @@ describe('GET /api/image-updates/fleet', () => {
expect(res.status).toBe(401);
});
it('rejects non-admin users with 403', async () => {
// The cross-node aggregation is part of the admin-only readiness surface;
// the single-node GET / endpoint stays open for the sidebar update dot.
it('allows a non-admin authenticated user (auth-only, matching GET / and /detail)', async () => {
// The cross-node aggregation used to be admin-only; it now matches the
// auth-only read model shared with GET /, /detail, and /status.
const res = await request(app).get('/api/image-updates/fleet').set('Cookie', viewerCookie);
expect(res.status).toBe(403);
expect(res.status).toBe(200);
expect(res.body).toBeInstanceOf(Object);
});
it('returns the fleet-wide aggregation map', async () => {
@@ -334,6 +491,22 @@ describe('POST /api/image-updates/fleet/refresh', () => {
expect(res.status).toBe(403);
});
it('rejects a Deployer with 403 PERMISSION_DENIED (requires node:manage)', async () => {
const res = await request(app)
.post('/api/image-updates/fleet/refresh')
.set('Authorization', `Bearer ${userToken('iu-deployer')}`);
expect(res.status).toBe(403);
expect(res.body.code).toBe('PERMISSION_DENIED');
});
it('allows a Node Admin (holds node:manage)', async () => {
const res = await request(app)
.post('/api/image-updates/fleet/refresh')
.set('Authorization', `Bearer ${userToken('iu-node-admin')}`);
expect(res.status).toBe(200);
expect(Array.isArray(res.body.triggered)).toBe(true);
});
it('returns triggered/rateLimited/failed arrays for admin caller', async () => {
const res = await request(app).post('/api/image-updates/fleet/refresh').set('Cookie', adminCookie);
expect(res.status).toBe(200);
@@ -376,12 +549,125 @@ describe('POST /api/auto-update/execute', () => {
expect(res.status).toBe(401);
});
it('rejects non-admin users with 403', async () => {
it('rejects a role without stack:deploy with 403 PERMISSION_DENIED', async () => {
const res = await request(app)
.post('/api/auto-update/execute')
.set('Cookie', viewerCookie)
.send({ target: 'execute-authz-stack' });
expect(res.status).toBe(403);
expect(res.body.code).toBe('PERMISSION_DENIED');
});
it('rejects a role without stack:deploy on target="*" even when the node has no stacks', async () => {
// On a fresh test instance the "*" expansion resolves to zero stacks, which
// would otherwise short-circuit into a "no stacks found" 200 before any
// per-stack permission check has anything to iterate over. The wildcard
// case requires global stack:deploy up front specifically to close that gap.
const res = await request(app)
.post('/api/auto-update/execute')
.set('Cookie', viewerCookie)
.send({ target: '*' });
expect(res.status).toBe(403);
expect(res.body.code).toBe('PERMISSION_DENIED');
});
it('allows a Deployer to execute a single-stack target', async () => {
const res = await request(app)
.post('/api/auto-update/execute')
.set('Authorization', `Bearer ${userToken('iu-deployer')}`)
.send({ target: 'deployer-exec-stack' });
expect(res.status).toBe(200);
expect(typeof res.body.result).toBe('string');
});
it('denies a Deployer stripped of stack:deploy with 403 PERMISSION_DENIED', async () => {
const { ROLE_PERMISSIONS } = await import('../middleware/permissions');
const original = ROLE_PERMISSIONS.deployer;
ROLE_PERMISSIONS.deployer = original.filter((p) => p !== 'stack:deploy');
try {
const res = await request(app)
.post('/api/auto-update/execute')
.set('Authorization', `Bearer ${userToken('iu-deployer')}`)
.send({ target: 'deployer-exec-stack' });
expect(res.status).toBe(403);
expect(res.body.code).toBe('PERMISSION_DENIED');
} finally {
ROLE_PERMISSIONS.deployer = original;
}
});
it('denies the whole bulk request when one target is unauthorized, with no partial execution', async () => {
// Scoped user: global viewer role (no stack:deploy anywhere) plus a
// deployer role assignment scoped to "bulk-allowed" only. Requesting
// ["bulk-allowed", "bulk-denied"] must deny the entire call on the second
// stack and never touch either stack's containers.
const db = DatabaseService.getInstance();
const nodeId = db.getDefaultNode()!.id!;
const hash = await bcrypt.hash('scopedpass', 1);
const scopedUserId = db.addUser({ username: 'iu-bulk-scoped', password_hash: hash, role: 'viewer' });
db.addRoleAssignment({ user_id: scopedUserId, role: 'deployer', resource_type: 'stack', resource_id: 'bulk-allowed', node_id: nodeId });
const DockerController = (await import('../services/DockerController')).default;
const containersSpy = vi.spyOn(DockerController.prototype, 'getContainersByStack');
try {
const res = await request(app)
.post('/api/auto-update/execute')
.set('Authorization', `Bearer ${userToken('iu-bulk-scoped')}`)
.send({ targets: ['bulk-allowed', 'bulk-denied'] });
expect(res.status).toBe(403);
expect(res.body.code).toBe('PERMISSION_DENIED');
expect(containersSpy).not.toHaveBeenCalled();
} finally {
containersSpy.mockRestore();
db.deleteRoleAssignmentsByUser(scopedUserId);
db.deleteUser(scopedUserId);
}
});
it('rejects a role without stack:deploy with 403 even when checks are disabled node-wide', async () => {
// Permission must be evaluated before the checks-enabled setting is
// consulted: a disabled node must not let an unauthorized caller through
// to the "disabled; skipped" 200 that a legitimate caller would see.
DatabaseService.getInstance().updateGlobalSetting('image_update_checks_enabled', '0');
try {
const res = await request(app)
.post('/api/auto-update/execute')
.set('Cookie', viewerCookie)
.send({ target: 'checks-disabled-authz-stack' });
expect(res.status).toBe(403);
expect(res.body.code).toBe('PERMISSION_DENIED');
} finally {
DatabaseService.getInstance().updateGlobalSetting('image_update_checks_enabled', '1');
}
});
it('denies target="*" for a scoped-only user even when their grant covers every stack on the node', async () => {
// A user with ONLY a scoped stack:deploy role_assignment (no global
// stack:deploy role) is denied the wildcard outright, even though the
// same grant would pass requireExactStacks if the caller enumerated the
// stack explicitly via targets instead of relying on "*" to expand it.
// This is the brief-sanctioned "deny without global deploy" tradeoff for
// the wildcard case.
makeOnDiskStack('wildcard-scoped-stack');
const db = DatabaseService.getInstance();
const nodeId = db.getDefaultNode()!.id!;
const hash = await bcrypt.hash('scopedpass', 1);
const scopedUserId = db.addUser({ username: 'iu-wildcard-scoped', password_hash: hash, role: 'viewer' });
db.addRoleAssignment({ user_id: scopedUserId, role: 'deployer', resource_type: 'stack', resource_id: 'wildcard-scoped-stack', node_id: nodeId });
try {
const res = await request(app)
.post('/api/auto-update/execute')
.set('Authorization', `Bearer ${userToken('iu-wildcard-scoped')}`)
.send({ target: '*' });
expect(res.status).toBe(403);
expect(res.body.code).toBe('PERMISSION_DENIED');
} finally {
db.deleteRoleAssignmentsByUser(scopedUserId);
db.deleteUser(scopedUserId);
removeOnDiskStack('wildcard-scoped-stack');
}
});
it('serves a community-licensed admin (no paid gate)', async () => {