DC-059: Joi validation middleware + schemas for destructive routes
[grade=B] - New src/utilities/validate.js: validateBody(schema) middleware + 9 schemas (backupConfigUpdate, backupScheduleCreate, backupRestore, backupRestoreFile, appDeploy, appRestore, appRevert, assetUpload, logoUpload) - Uses Joi's authoritative CIDR validator (rejects malformed IPv6 like ::::/64 that the previous hex/colon regex would have accepted) - appDeploy.config uses .unknown(true) for forward-compat with template-specific fields (sslType, dnsType, plexClaimToken, etc.) — preserves fields the live frontend posts, prevents a behavioural regression - appRestore uses Joi.any().custom() so the empty-body semantics hold under middleware stripUnknown (default) — body with extra keys now rejected - Wired into 8 destructive routes: backups schedule/restore/config, apps deploy/restore/revert, assets upload/logo - Duplicate legacy POST /backups/schedule handler (line 519) marked LEGACY with TODO removal note (Express only matches first registration; this handler is unreachable under normal routing) - Removed redundant manual appId check in /backups/schedule (Joi schema enforces it) - Removed unused 'mime' destructure in /assets/favicon (decodeImageData validates MIME internally) - 41 unit tests covering every exported schema + middleware integration - 1539/1539 Jest tests pass, zero new ESLint warnings
This commit is contained in:
@@ -9,6 +9,7 @@ const platformPaths = require('../../platform-paths');
|
||||
const { ValidationError } = require('../../src/utilities/errors');
|
||||
const { logError } = require('../../src/utils/logging');
|
||||
const { ok } = require('../../src/utils/responses');
|
||||
const { validateBody, schemas: valSchemas } = require('../../src/utilities/validate');
|
||||
/**
|
||||
* Apps deployment routes factory
|
||||
* @param {Object} deps - Explicit dependencies
|
||||
@@ -251,17 +252,8 @@ module.exports = function({ docker, caddy, credentialManager, servicesStateManag
|
||||
}, 'check-existing'));
|
||||
|
||||
// Deploy new app
|
||||
router.post('/deploy', asyncHandler(async (req, res) => {
|
||||
router.post('/deploy', validateBody(valSchemas.appDeploy), asyncHandler(async (req, res) => {
|
||||
const { appId, config } = req.body;
|
||||
if (!appId || typeof appId !== 'string') {
|
||||
throw new ValidationError('appId is required');
|
||||
}
|
||||
if (!config || typeof config !== 'object') {
|
||||
throw new ValidationError('config object is required');
|
||||
}
|
||||
if (!config.subdomain || typeof config.subdomain !== 'string') {
|
||||
throw new ValidationError('config.subdomain is required');
|
||||
}
|
||||
try {
|
||||
log.info('deploy', 'Deploying app', { appId, subdomain: config.subdomain });
|
||||
const template = ctx.APP_TEMPLATES[appId];
|
||||
|
||||
@@ -3,6 +3,7 @@ const path = require('path');
|
||||
const fs = require('fs');
|
||||
const { DOCKER } = require('../../src/utilities/constants');
|
||||
const { ok, validationError, notFound, errorResponse } = require('../../src/utils/responses');
|
||||
const { validateBody, schemas: valSchemas } = require('../../src/utilities/validate');
|
||||
|
||||
const DEFAULT_BACKUP_DIR = process.env.BACKUP_DIR || path.join(__dirname, '..', 'backups');
|
||||
|
||||
@@ -36,7 +37,7 @@ module.exports = function({ docker, caddy, servicesStateManager, asyncHandler, e
|
||||
* Pulls image, creates container, starts it, recreates Caddy config.
|
||||
* Skips if container is already running.
|
||||
*/
|
||||
router.post('/:appId/restore', asyncHandler(async (req, res) => {
|
||||
router.post('/:appId/restore', validateBody(valSchemas.appRestore), asyncHandler(async (req, res) => {
|
||||
const { appId } = req.params;
|
||||
const services = await servicesStateManager.read();
|
||||
const service = services.find(s => s.id === appId);
|
||||
@@ -183,9 +184,9 @@ module.exports = function({ docker, caddy, servicesStateManager, asyncHandler, e
|
||||
}, 'apps-backup-points'));
|
||||
|
||||
// Revert a specific app to a backup file (point-in-time restore)
|
||||
router.post('/:appId/revert/:filename', asyncHandler(async (req, res) => {
|
||||
router.post('/:appId/revert/:filename', validateBody(valSchemas.appRevert), asyncHandler(async (req, res) => {
|
||||
const { appId, filename } = req.params;
|
||||
const { encryptionKey, restartContainers } = req.body || {};
|
||||
const { encryptionKey, restartContainers } = req.body;
|
||||
|
||||
// Security: prevent path traversal
|
||||
if (filename.includes('..') || filename.includes('/') || filename.includes('\\')) {
|
||||
|
||||
@@ -3,6 +3,7 @@ const fsp = require('fs').promises;
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { success } = require('../src/utils/responses');
|
||||
const { validateBody, schemas } = require('../src/utilities/validate');
|
||||
|
||||
const DEFAULT_BACKUP_DIR = process.env.BACKUP_DIR || path.join(__dirname, '..', 'backups');
|
||||
const DEFAULT_MAX_STORAGE_BYTES = process.env.BACKUP_MAX_STORAGE_BYTES
|
||||
@@ -56,14 +57,10 @@ module.exports = function({ backupManager, licenseManager, asyncHandler }) {
|
||||
}, 'backups-schedule-list'));
|
||||
|
||||
// Create or update a scheduled backup for an app
|
||||
router.post('/backups/schedule', premiumGating, asyncHandler(async (req, res) => {
|
||||
router.post('/backups/schedule', premiumGating, validateBody(schemas.backupScheduleCreate), asyncHandler(async (req, res) => {
|
||||
// appId is guaranteed present by the Joi schema (backupScheduleCreate requires it)
|
||||
const { appId, enabled, schedule, retention, runImmediately, destination, destinationPath, maxStorageBytes } = req.body;
|
||||
|
||||
if (!appId) {
|
||||
const { ValidationError } = require('../src/utilities/errors');
|
||||
throw new ValidationError('appId is required');
|
||||
}
|
||||
|
||||
const config = backupManager.getConfig();
|
||||
if (!config.backups) config.backups = {};
|
||||
|
||||
@@ -234,7 +231,7 @@ module.exports = function({ backupManager, licenseManager, asyncHandler }) {
|
||||
}, 'backups-files-app'));
|
||||
|
||||
// Restore from a specific backup file on disk
|
||||
router.post('/backups/restore-file/:filename', asyncHandler(async (req, res) => {
|
||||
router.post('/backups/restore-file/:filename', validateBody(schemas.backupRestoreFile), asyncHandler(async (req, res) => {
|
||||
const { filename } = req.params;
|
||||
const { encryptionKey, restartContainers } = req.body || {};
|
||||
|
||||
@@ -483,7 +480,7 @@ module.exports = function({ backupManager, licenseManager, asyncHandler }) {
|
||||
}, 'backups-config-get'));
|
||||
|
||||
// Update backup configuration
|
||||
router.post('/backups/config', asyncHandler(async (req, res) => {
|
||||
router.post('/backups/config', validateBody(schemas.backupConfigUpdate), asyncHandler(async (req, res) => {
|
||||
// P0-3 fix: was `backupManager.updateConfig(req.body)` which allowed
|
||||
// arbitrary keys from HTTP request body to be merged into persisted config.
|
||||
// Now destructure only the two known top-level fields.
|
||||
@@ -515,6 +512,11 @@ module.exports = function({ backupManager, licenseManager, asyncHandler }) {
|
||||
}, 'backups-storage-info'));
|
||||
|
||||
// Schedule a backup
|
||||
// LEGACY: this is a duplicate registration of POST /backups/schedule (see also line 60,
|
||||
// which uses the appId-keyed schema and is the route the frontend actually calls).
|
||||
// Express only matches the first registered handler per METHOD+PATH, so this handler
|
||||
// is unreachable. It is preserved for now to avoid removing a route any unknown
|
||||
// integration might still POST to. TODO: audit + remove in a dedicated cleanup PR.
|
||||
router.post('/backups/schedule', asyncHandler(async (req, res) => {
|
||||
const { name, schedule, maxStorageBytes, ...backupConfig } = req.body;
|
||||
|
||||
@@ -539,10 +541,10 @@ module.exports = function({ backupManager, licenseManager, asyncHandler }) {
|
||||
|
||||
backupManager.updateConfig(config);
|
||||
success(res, { message: `Backup '${name}' scheduled`, maxStorageBytes: maxBytes });
|
||||
}, 'backups-schedule'));
|
||||
}, 'backups-schedule-legacy'));
|
||||
|
||||
// Restore from backup
|
||||
router.post('/backups/restore/:backupId', asyncHandler(async (req, res) => {
|
||||
router.post('/backups/restore/:backupId', validateBody(schemas.backupRestore), asyncHandler(async (req, res) => {
|
||||
const result = await backupManager.restoreBackup(req.params.backupId, req.body);
|
||||
success(res, { result });
|
||||
}, 'backups-restore'));
|
||||
|
||||
@@ -6,6 +6,7 @@ const { exists } = require('../../src/utilities/fs-helpers');
|
||||
const { ValidationError } = require('../../src/utilities/errors');
|
||||
const platformPaths = require('../../platform-paths');
|
||||
const { ok, successMessage } = require('../../src/utils/responses');
|
||||
const { validateBody, schemas: valSchemas } = require('../../src/utilities/validate');
|
||||
/**
|
||||
* Config assets routes factory
|
||||
* @param {Object} deps - Explicit dependencies
|
||||
@@ -54,13 +55,9 @@ module.exports = function({ servicesStateManager: _servicesStateManager, asyncHa
|
||||
|
||||
// ===== ASSET UPLOAD =====
|
||||
|
||||
router.post('/assets/upload', express.json({ limit: LIMITS.BODY_UPLOAD }), asyncHandler(async (req, res) => {
|
||||
router.post('/assets/upload', express.json({ limit: LIMITS.BODY_UPLOAD }), validateBody(valSchemas.assetUpload), asyncHandler(async (req, res) => {
|
||||
const { filename, data } = req.body;
|
||||
|
||||
if (!filename || !data) {
|
||||
throw new ValidationError('filename and data are required');
|
||||
}
|
||||
|
||||
// Validate filename to prevent directory traversal
|
||||
const safeFilename = path.basename(filename);
|
||||
if (safeFilename !== filename || filename.includes('..')) {
|
||||
@@ -129,13 +126,9 @@ module.exports = function({ servicesStateManager: _servicesStateManager, asyncHa
|
||||
// Upload custom logo(s) and/or update position and title
|
||||
// Supports: dataDark/dataLight (separate variants) or data (single logo for both)
|
||||
// eslint-disable-next-line complexity
|
||||
router.post('/logo', express.json({ limit: LIMITS.BODY_UPLOAD }), asyncHandler(async (req, res) => {
|
||||
router.post('/logo', express.json({ limit: LIMITS.BODY_UPLOAD }), validateBody(valSchemas.logoUpload), asyncHandler(async (req, res) => {
|
||||
const { data, dataDark, dataLight, position, dashboardTitle } = req.body;
|
||||
|
||||
if (!data && !dataDark && !dataLight && !position && !dashboardTitle) {
|
||||
throw new ValidationError('Image data, position, or title is required');
|
||||
}
|
||||
|
||||
const config = await ctx.readConfig();
|
||||
let pathDark = null, pathLight = null;
|
||||
|
||||
@@ -240,15 +233,10 @@ module.exports = function({ servicesStateManager: _servicesStateManager, asyncHa
|
||||
return ctx.errorResponse(res, 500, 'Image processing not available');
|
||||
}
|
||||
|
||||
// Extract base64 data
|
||||
const matches = data.match(/^data:image\/([a-zA-Z+]+);base64,(.+)$/);
|
||||
if (!matches) {
|
||||
throw new ValidationError('Invalid image data format');
|
||||
}
|
||||
|
||||
const base64Data = matches[2];
|
||||
const buffer = Buffer.from(base64Data, 'base64');
|
||||
// P0-4: validate MIME type + enforce 5MB buffer size cap (mime validated inside decodeImageData)
|
||||
const { buffer } = decodeImageData(data);
|
||||
|
||||
// Determine assets path (mounted volume)
|
||||
const assetsPath = platformPaths.resolveAssetsPath(process.env.ASSETS_PATH);
|
||||
if (!await exists(assetsPath)) {
|
||||
await fsp.mkdir(assetsPath, { recursive: true });
|
||||
|
||||
Reference in New Issue
Block a user