fix: harden stack label permissions (#1036)

* fix: harden stack label permissions

* fix: avoid test db init from debug logging
This commit is contained in:
Anso
2026-05-13 11:56:22 -04:00
committed by GitHub
parent 328a98439d
commit b52323036b
9 changed files with 295 additions and 27 deletions
@@ -0,0 +1,149 @@
import { beforeAll, beforeEach, afterAll, describe, expect, it, vi } from 'vitest';
import request from 'supertest';
import jwt from 'jsonwebtoken';
import { setupTestDb, cleanupTestDb, TEST_USERNAME, TEST_JWT_SECRET } from './helpers/setupTestDb';
let mockFsStacks: string[] = [];
const deployStack = vi.fn();
const getContainersByStack = vi.fn();
const stopContainer = vi.fn();
const restartContainer = vi.fn();
const enforcePolicyPreDeploy = vi.fn();
const invalidateNodeCaches = vi.fn();
vi.mock('../services/FileSystemService', () => ({
FileSystemService: {
getInstance: vi.fn(() => ({
getStacks: vi.fn(async () => mockFsStacks),
})),
},
}));
vi.mock('../services/ComposeService', () => ({
ComposeService: {
getInstance: vi.fn(() => ({ deployStack })),
},
}));
vi.mock('../services/DockerController', () => ({
default: {
getInstance: vi.fn(() => ({
getContainersByStack,
stopContainer,
restartContainer,
})),
},
}));
vi.mock('../services/PolicyEnforcement', () => ({
enforcePolicyPreDeploy,
}));
vi.mock('../helpers/cacheInvalidation', () => ({
invalidateNodeCaches,
}));
let tmpDir: string;
let app: import('express').Express;
let authHeader: string;
let db: import('../services/DatabaseService').DatabaseService;
let LicenseService: typeof import('../services/LicenseService').LicenseService;
let activeBulkActions: typeof import('../routes/labels').activeBulkActions;
let labelCounter = 0;
beforeAll(async () => {
tmpDir = await setupTestDb();
({ app } = await import('../index'));
({ LicenseService } = await import('../services/LicenseService'));
({ activeBulkActions } = await import('../routes/labels'));
const { DatabaseService } = await import('../services/DatabaseService');
db = DatabaseService.getInstance();
authHeader = `Bearer ${jwt.sign({ username: TEST_USERNAME }, TEST_JWT_SECRET, { expiresIn: '1m' })}`;
});
afterAll(() => cleanupTestDb(tmpDir));
beforeEach(() => {
vi.restoreAllMocks();
vi.spyOn(LicenseService.getInstance(), 'getTier').mockReturnValue('paid');
mockFsStacks = ['alpha', 'beta'];
deployStack.mockResolvedValue(undefined);
getContainersByStack.mockResolvedValue([{ Id: 'container-1' }]);
stopContainer.mockResolvedValue(undefined);
restartContainer.mockResolvedValue(undefined);
enforcePolicyPreDeploy.mockResolvedValue({ ok: true });
invalidateNodeCaches.mockClear();
activeBulkActions.clear();
db.getDb().prepare('DELETE FROM stack_label_assignments').run();
db.getDb().prepare('DELETE FROM stack_labels').run();
});
async function createAssignedLabel(stacks: string[] = ['alpha']) {
const created = await request(app)
.post('/api/labels')
.set('Authorization', authHeader)
.send({ name: `bulk-${++labelCounter}`, color: 'teal' });
expect(created.status).toBe(201);
for (const stack of stacks) {
const assigned = await request(app)
.put(`/api/stacks/${stack}/labels`)
.set('Authorization', authHeader)
.send({ labelIds: [created.body.id] });
expect(assigned.status).toBe(200);
}
return created.body as { id: number; node_id: number; name: string; color: string };
}
describe('Stack Labels bulk actions', () => {
it('deploys every existing stack assigned to the label', async () => {
const label = await createAssignedLabel(['alpha']);
const res = await request(app)
.post(`/api/labels/${label.id}/action`)
.set('Authorization', authHeader)
.send({ action: 'deploy' });
expect(res.status).toBe(200);
expect(res.body.results).toEqual([{ stackName: 'alpha', success: true }]);
expect(enforcePolicyPreDeploy).toHaveBeenCalledWith('alpha', label.node_id, expect.any(Object));
expect(deployStack).toHaveBeenCalledWith('alpha', undefined, false);
expect(invalidateNodeCaches).toHaveBeenCalledWith(label.node_id);
});
it('reports partial Docker stop failures without aborting other stacks', async () => {
const label = await createAssignedLabel(['alpha', 'beta']);
getContainersByStack.mockImplementation(async (stackName: string) => {
if (stackName === 'beta') throw new Error('socket permission denied');
return [{ Id: `${stackName}-1` }];
});
const res = await request(app)
.post(`/api/labels/${label.id}/action`)
.set('Authorization', authHeader)
.send({ action: 'stop' });
expect(res.status).toBe(200);
expect(res.body.results).toEqual([
{ stackName: 'alpha', success: true },
{ stackName: 'beta', success: false, error: 'socket permission denied' },
]);
expect(stopContainer).toHaveBeenCalledWith('alpha-1');
expect(invalidateNodeCaches).toHaveBeenCalledWith(label.node_id);
});
it('rejects a second bulk action while the node lock is held', async () => {
const label = await createAssignedLabel(['alpha']);
activeBulkActions.add(`bulk:${label.node_id}`);
const res = await request(app)
.post(`/api/labels/${label.id}/action`)
.set('Authorization', authHeader)
.send({ action: 'restart' });
expect(res.status).toBe(429);
expect(res.body.error).toContain('already running');
expect(restartContainer).not.toHaveBeenCalled();
});
});
@@ -12,14 +12,24 @@ import { setupTestDb, cleanupTestDb, TEST_USERNAME, TEST_JWT_SECRET } from './he
let tmpDir: string;
let app: import('express').Express;
let authHeader: string;
let viewerAuthHeader: string;
let nodeAdminAuthHeader: string;
let LicenseService: typeof import('../services/LicenseService').LicenseService;
let DatabaseService: typeof import('../services/DatabaseService').DatabaseService;
beforeAll(async () => {
tmpDir = await setupTestDb();
({ app } = await import('../index'));
({ LicenseService } = await import('../services/LicenseService'));
({ DatabaseService } = await import('../services/DatabaseService'));
DatabaseService.getInstance().addUser({ username: 'labels-viewer', password_hash: 'hash', role: 'viewer' });
DatabaseService.getInstance().addUser({ username: 'labels-node-admin', password_hash: 'hash', role: 'node-admin' });
const token = jwt.sign({ username: TEST_USERNAME }, TEST_JWT_SECRET, { expiresIn: '1m' });
const viewerToken = jwt.sign({ username: 'labels-viewer' }, TEST_JWT_SECRET, { expiresIn: '1m' });
const nodeAdminToken = jwt.sign({ username: 'labels-node-admin' }, TEST_JWT_SECRET, { expiresIn: '1m' });
authHeader = `Bearer ${token}`;
viewerAuthHeader = `Bearer ${viewerToken}`;
nodeAdminAuthHeader = `Bearer ${nodeAdminToken}`;
});
afterAll(() => cleanupTestDb(tmpDir));
@@ -87,6 +97,16 @@ describe('Stack Labels on Community tier', () => {
expect(res.body.success).toBe(true);
});
it('allows node-admins to create labels through the stack edit permission', async () => {
mockTier('community');
const res = await request(app)
.post('/api/labels')
.set('Authorization', nodeAdminAuthHeader)
.send({ name: 'node-admin-label', color: 'green' });
expect(res.status).toBe(201);
expect(res.body).toMatchObject({ name: 'node-admin-label', color: 'green' });
});
it('PUT /api/stacks/:stackName/labels accepts an empty assignment on community', async () => {
mockTier('community');
const res = await request(app)
@@ -96,6 +116,87 @@ describe('Stack Labels on Community tier', () => {
expect(res.status).toBe(200);
expect(res.body.success).toBe(true);
});
it('rejects path traversal stack names before assigning labels', async () => {
mockTier('community');
const res = await request(app)
.put(`/api/stacks/${encodeURIComponent('../secret')}/labels`)
.set('Authorization', authHeader)
.send({ labelIds: [] });
expect(res.status).toBe(400);
expect(res.body.error).toBe('Invalid stack name');
});
});
describe('Stack Labels RBAC', () => {
afterEach(() => vi.restoreAllMocks());
it('allows viewers to read labels but denies label creation', async () => {
mockTier('community');
const list = await request(app).get('/api/labels').set('Authorization', viewerAuthHeader);
expect(list.status).toBe(200);
const create = await request(app)
.post('/api/labels')
.set('Authorization', viewerAuthHeader)
.send({ name: 'viewer-create', color: 'teal' });
expect(create.status).toBe(403);
expect(create.body.code).toBe('PERMISSION_DENIED');
});
it('denies viewers label update, delete, and stack assignment', async () => {
mockTier('community');
const created = await request(app)
.post('/api/labels')
.set('Authorization', authHeader)
.send({ name: 'rbac-target', color: 'blue' });
expect(created.status).toBe(201);
const update = await request(app)
.put(`/api/labels/${created.body.id}`)
.set('Authorization', viewerAuthHeader)
.send({ color: 'rose' });
expect(update.status).toBe(403);
expect(update.body.code).toBe('PERMISSION_DENIED');
const assign = await request(app)
.put('/api/stacks/rbac-stack/labels')
.set('Authorization', viewerAuthHeader)
.send({ labelIds: [created.body.id] });
expect(assign.status).toBe(403);
expect(assign.body.code).toBe('PERMISSION_DENIED');
const remove = await request(app)
.delete(`/api/labels/${created.body.id}`)
.set('Authorization', viewerAuthHeader);
expect(remove.status).toBe(403);
expect(remove.body.code).toBe('PERMISSION_DENIED');
});
});
describe('Stack Labels Developer Mode logging', () => {
afterEach(() => vi.restoreAllMocks());
it('only emits label debug logs when Developer Mode is enabled', async () => {
mockTier('community');
const debugSpy = vi.spyOn(console, 'debug').mockImplementation(() => {});
const db = DatabaseService.getInstance();
db.updateGlobalSetting('developer_mode', '0');
const quiet = await request(app).get('/api/labels').set('Authorization', authHeader);
expect(quiet.status).toBe(200);
expect(debugSpy).not.toHaveBeenCalled();
db.updateGlobalSetting('developer_mode', '1');
const noisy = await request(app).get('/api/labels').set('Authorization', authHeader);
expect(noisy.status).toBe(200);
expect(debugSpy).toHaveBeenCalledWith(
'[Labels:debug] List labels: nodeId=',
expect.any(Number),
'count=',
expect.any(Number),
);
});
});
describe('Stack Labels bulk-action endpoint stays Skipper+', () => {