Files
cloudron-box/src/backups.js

364 lines
14 KiB
JavaScript
Raw Normal View History

'use strict';
exports = module.exports = {
get,
2021-07-14 11:07:19 -07:00
getByIdentifierAndStatePaged,
getByTypePaged,
add,
update,
setState,
2021-07-14 11:07:19 -07:00
list,
del,
2015-09-21 14:14:21 -07:00
startBackupTask,
startCleanupTask,
cleanupCacheFilesSync,
injectPrivateFields,
removePrivateFields,
generateEncryptionKeysSync,
2021-07-14 11:07:19 -07:00
getSnapshotInfo,
setSnapshotInfo,
testConfig,
testProviderConfig,
remount,
BACKUP_IDENTIFIER_BOX: 'box',
BACKUP_IDENTIFIER_MAIL: 'mail',
BACKUP_TYPE_APP: 'app',
BACKUP_TYPE_BOX: 'box',
BACKUP_TYPE_MAIL: 'mail',
BACKUP_STATE_NORMAL: 'normal', // should rename to created to avoid listing in UI?
BACKUP_STATE_CREATING: 'creating',
BACKUP_STATE_ERROR: 'error',
};
2021-07-14 11:07:19 -07:00
const assert = require('assert'),
2019-10-22 20:36:20 -07:00
BoxError = require('./boxerror.js'),
constants = require('./constants.js'),
CronJob = require('cron').CronJob,
crypto = require('crypto'),
database = require('./database.js'),
2021-09-10 12:10:10 -07:00
debug = require('debug')('box:backups'),
eventlog = require('./eventlog.js'),
hat = require('./hat.js'),
locker = require('./locker.js'),
path = require('path'),
paths = require('./paths.js'),
safe = require('safetydance'),
2015-11-07 22:06:09 -08:00
settings = require('./settings.js'),
2021-07-14 11:07:19 -07:00
storage = require('./storage.js'),
2022-04-14 07:59:50 -05:00
tasks = require('./tasks.js');
2021-07-14 11:07:19 -07:00
const BACKUPS_FIELDS = [ 'id', 'remotePath', 'label', 'identifier', 'creationTime', 'packageVersion', 'type', 'dependsOnJson', 'state', 'manifestJson', 'format', 'preserveSecs', 'encryptionVersion' ];
2021-07-14 11:07:19 -07:00
function postProcess(result) {
assert.strictEqual(typeof result, 'object');
result.dependsOn = result.dependsOnJson ? safe.JSON.parse(result.dependsOnJson) : [];
delete result.dependsOnJson;
2021-07-14 11:07:19 -07:00
result.manifest = result.manifestJson ? safe.JSON.parse(result.manifestJson) : null;
delete result.manifestJson;
2015-11-06 18:14:59 -08:00
2021-07-14 11:07:19 -07:00
return result;
}
function injectPrivateFields(newConfig, currentConfig) {
2020-05-14 11:18:41 -07:00
if ('password' in newConfig) {
if (newConfig.password === constants.SECRET_PLACEHOLDER) {
2020-05-14 11:18:41 -07:00
delete newConfig.password;
}
2020-05-14 23:35:03 +02:00
newConfig.encryption = currentConfig.encryption || null;
} else {
newConfig.encryption = null;
}
2021-07-14 11:07:19 -07:00
if (newConfig.provider === currentConfig.provider) storage.api(newConfig.provider).injectPrivateFields(newConfig, currentConfig);
}
function removePrivateFields(backupConfig) {
assert.strictEqual(typeof backupConfig, 'object');
if (backupConfig.encryption) {
delete backupConfig.encryption;
backupConfig.password = constants.SECRET_PLACEHOLDER;
}
2021-07-14 11:07:19 -07:00
return storage.api(backupConfig.provider).removePrivateFields(backupConfig);
}
// this function is used in migrations - 20200512172301-settings-backup-encryption.js
function generateEncryptionKeysSync(password) {
assert.strictEqual(typeof password, 'string');
const aesKeys = crypto.scryptSync(password, Buffer.from('CLOUDRONSCRYPTSALT', 'utf8'), 128);
return {
dataKey: aesKeys.slice(0, 32).toString('hex'),
dataHmacKey: aesKeys.slice(32, 64).toString('hex'),
filenameKey: aesKeys.slice(64, 96).toString('hex'),
filenameHmacKey: aesKeys.slice(96).toString('hex')
};
}
async function add(data) {
2021-07-14 11:07:19 -07:00
assert(data && typeof data === 'object');
assert.strictEqual(typeof data.remotePath, 'string');
2021-07-14 11:07:19 -07:00
assert(data.encryptionVersion === null || typeof data.encryptionVersion === 'number');
assert.strictEqual(typeof data.packageVersion, 'string');
assert.strictEqual(typeof data.type, 'string');
assert.strictEqual(typeof data.identifier, 'string');
assert.strictEqual(typeof data.state, 'string');
assert(Array.isArray(data.dependsOn));
assert.strictEqual(typeof data.manifest, 'object');
assert.strictEqual(typeof data.format, 'string');
assert.strictEqual(typeof data.preserveSecs, 'number');
2021-07-14 11:07:19 -07:00
const creationTime = data.creationTime || new Date(); // allow tests to set the time
const manifestJson = JSON.stringify(data.manifest);
const prefixId = data.type === exports.BACKUP_TYPE_APP ? `${data.type}_${data.identifier}` : data.type; // type and identifier are same for other types
const id = `${prefixId}_v${data.packageVersion}_${hat(256)}`; // id is used by the UI to derive dependent packages. making this a UUID will require a lot of db querying
2021-07-14 11:07:19 -07:00
const [error] = await safe(database.query('INSERT INTO backups (id, remotePath, identifier, encryptionVersion, packageVersion, type, creationTime, state, dependsOnJson, manifestJson, format, preserveSecs) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
[ id, data.remotePath, data.identifier, data.encryptionVersion, data.packageVersion, data.type, creationTime, data.state, JSON.stringify(data.dependsOn), manifestJson, data.format, data.preserveSecs ]));
2021-07-14 11:07:19 -07:00
if (error && error.code === 'ER_DUP_ENTRY') throw new BoxError(BoxError.ALREADY_EXISTS, 'Backup already exists');
if (error) throw error;
return id;
2021-07-14 11:07:19 -07:00
}
async function getByIdentifierAndStatePaged(identifier, state, page, perPage) {
assert.strictEqual(typeof identifier, 'string');
assert.strictEqual(typeof state, 'string');
2016-03-08 08:52:20 -08:00
assert(typeof page === 'number' && page > 0);
assert(typeof perPage === 'number' && perPage > 0);
2021-07-14 11:07:19 -07:00
const results = await database.query(`SELECT ${BACKUPS_FIELDS} FROM backups WHERE identifier = ? AND state = ? ORDER BY creationTime DESC LIMIT ?,?`, [ identifier, state, (page-1)*perPage, perPage ]);
2021-07-14 11:07:19 -07:00
results.forEach(function (result) { postProcess(result); });
2021-07-14 11:07:19 -07:00
return results;
}
2021-07-14 11:07:19 -07:00
async function get(id) {
assert.strictEqual(typeof id, 'string');
2017-09-19 20:40:38 -07:00
2021-07-14 11:07:19 -07:00
const result = await database.query('SELECT ' + BACKUPS_FIELDS + ' FROM backups WHERE id = ? ORDER BY creationTime DESC', [ id ]);
if (result.length === 0) return null;
2021-07-14 11:07:19 -07:00
return postProcess(result[0]);
2017-09-19 20:40:38 -07:00
}
2021-07-14 11:07:19 -07:00
async function getByTypePaged(type, page, perPage) {
assert.strictEqual(typeof type, 'string');
assert(typeof page === 'number' && page > 0);
assert(typeof perPage === 'number' && perPage > 0);
2021-07-14 11:07:19 -07:00
const results = await database.query(`SELECT ${BACKUPS_FIELDS} FROM backups WHERE type = ? ORDER BY creationTime DESC LIMIT ?,?`, [ type, (page-1)*perPage, perPage ]);
2021-07-14 11:07:19 -07:00
results.forEach(function (result) { postProcess(result); });
2021-07-14 11:07:19 -07:00
return results;
}
function validateLabel(label) {
assert.strictEqual(typeof label, 'string');
if (label.length >= 200) return new BoxError(BoxError.BAD_FIELD, 'label too long');
2022-06-24 09:18:51 -07:00
if (/[^a-zA-Z0-9._() -]/.test(label)) return new BoxError(BoxError.BAD_FIELD, 'label can only contain alphanumerals, space, dot, hyphen, brackets or underscore');
return null;
}
// this is called by REST API
async function update(id, data) {
2021-07-14 11:07:19 -07:00
assert.strictEqual(typeof id, 'string');
assert.strictEqual(typeof data, 'object');
2020-05-15 16:05:12 -07:00
let error;
if ('label' in data) {
error = validateLabel(data.label);
if (error) throw error;
}
const fields = [], values = [];
for (const p in data) {
if (p === 'label' || p === 'preserveSecs') {
fields.push(p + ' = ?');
values.push(data[p]);
}
}
2021-07-14 11:07:19 -07:00
values.push(id);
const backup = await get(id);
if (backup === null) throw new BoxError(BoxError.NOT_FOUND, 'Backup not found');
2021-07-14 11:07:19 -07:00
const result = await database.query('UPDATE backups SET ' + fields.join(', ') + ' WHERE id = ?', values);
if (result.affectedRows !== 1) throw new BoxError(BoxError.NOT_FOUND, 'Backup not found');
if ('preserveSecs' in data) {
// update the dependancies
for (const depId of backup.dependsOn) {
await database.query('UPDATE backups SET preserveSecs=? WHERE id = ?', [ data.preserveSecs, depId]);
}
}
}
async function setState(id, state) {
assert.strictEqual(typeof id, 'string');
assert.strictEqual(typeof state, 'string');
const result = await database.query('UPDATE backups SET state = ? WHERE id = ?', [state, id]);
if (result.affectedRows !== 1) throw new BoxError(BoxError.NOT_FOUND, 'Backup not found');
}
2021-09-10 12:10:10 -07:00
async function startBackupTask(auditSource) {
2021-07-14 11:07:19 -07:00
let error = locker.lock(locker.OP_FULL_BACKUP);
2021-09-10 12:10:10 -07:00
if (error) throw new BoxError(BoxError.BAD_STATE, `Cannot backup now: ${error.message}`);
2021-09-10 12:10:10 -07:00
const backupConfig = await settings.getBackupConfig();
const memoryLimit = 'memoryLimit' in backupConfig ? Math.max(backupConfig.memoryLimit/1024/1024, 800) : 800;
2021-09-10 12:10:10 -07:00
const taskId = await tasks.add(tasks.TASK_BACKUP, [ { /* options */ } ]);
2021-09-10 12:10:10 -07:00
await eventlog.add(eventlog.ACTION_BACKUP_START, auditSource, { taskId });
2021-09-10 12:10:10 -07:00
tasks.startTask(taskId, { timeout: 24 * 60 * 60 * 1000 /* 24 hours */, nice: 15, memoryLimit }, async function (error, backupId) {
locker.unlock(locker.OP_FULL_BACKUP);
2021-09-10 12:10:10 -07:00
const errorMessage = error ? error.message : '';
const timedOut = error ? error.code === tasks.ETIMEOUT : false;
const backup = backupId ? await get(backupId) : null;
await safe(eventlog.add(eventlog.ACTION_BACKUP_FINISH, auditSource, { taskId, errorMessage, timedOut, backupId, remotePath: backup?.remotePath }), { debug });
});
2021-09-10 12:10:10 -07:00
return taskId;
2021-07-14 11:07:19 -07:00
}
2021-07-14 11:07:19 -07:00
async function list(page, perPage) {
assert(typeof page === 'number' && page > 0);
assert(typeof perPage === 'number' && perPage > 0);
2021-07-14 11:07:19 -07:00
const results = await database.query('SELECT ' + BACKUPS_FIELDS + ' FROM backups ORDER BY creationTime DESC LIMIT ?,?', [ (page-1)*perPage, perPage ]);
2021-07-14 11:07:19 -07:00
results.forEach(function (result) { postProcess(result); });
2021-07-14 11:07:19 -07:00
return results;
}
2021-07-14 11:07:19 -07:00
async function del(id) {
assert.strictEqual(typeof id, 'string');
2021-07-14 11:07:19 -07:00
const result = await database.query('DELETE FROM backups WHERE id=?', [ id ]);
if (result.affectedRows !== 1) throw new BoxError(BoxError.NOT_FOUND, 'Backup not found');
}
// this function is used in migrations - 20200512172301-settings-backup-encryption.js
2021-07-14 11:07:19 -07:00
function cleanupCacheFilesSync() {
2021-09-10 12:10:10 -07:00
const files = safe.fs.readdirSync(path.join(paths.BACKUP_INFO_DIR));
2021-07-14 11:07:19 -07:00
if (!files) return;
2021-09-10 12:10:10 -07:00
files
.filter(function (f) { return f.endsWith('.sync.cache'); })
.forEach(function (f) {
safe.fs.unlinkSync(path.join(paths.BACKUP_INFO_DIR, f));
});
}
2021-07-14 11:07:19 -07:00
function getSnapshotInfo(id) {
assert.strictEqual(typeof id, 'string');
2021-07-14 11:07:19 -07:00
const contents = safe.fs.readFileSync(paths.SNAPSHOT_INFO_FILE, 'utf8');
const info = safe.JSON.parse(contents);
if (!info) return { };
return info[id] || { };
2017-09-22 14:40:37 -07:00
}
// keeps track of contents of the snapshot directory. this provides a way to clean up backups of uninstalled apps
2021-09-16 13:59:03 -07:00
async function setSnapshotInfo(id, info) {
2021-07-14 11:07:19 -07:00
assert.strictEqual(typeof id, 'string');
assert.strictEqual(typeof info, 'object');
2017-09-22 14:40:37 -07:00
2021-07-14 11:07:19 -07:00
const contents = safe.fs.readFileSync(paths.SNAPSHOT_INFO_FILE, 'utf8');
const data = safe.JSON.parse(contents) || { };
if (info) data[id] = info; else delete data[id];
if (!safe.fs.writeFileSync(paths.SNAPSHOT_INFO_FILE, JSON.stringify(data, null, 4), 'utf8')) {
2021-09-16 13:59:03 -07:00
throw new BoxError(BoxError.FS_ERROR, safe.error.message);
}
2017-09-22 14:40:37 -07:00
}
2021-07-14 11:07:19 -07:00
async function startCleanupTask(auditSource) {
assert.strictEqual(typeof auditSource, 'object');
2021-07-14 11:07:19 -07:00
const taskId = await tasks.add(tasks.TASK_CLEAN_BACKUPS, []);
tasks.startTask(taskId, {}, async (error, result) => { // result is { removedBoxBackupPaths, removedAppBackupPaths, removedMailBackupPaths, missingBackupPaths }
2022-02-24 20:04:46 -08:00
await safe(eventlog.add(eventlog.ACTION_BACKUP_CLEANUP_FINISH, auditSource, {
2021-07-14 11:07:19 -07:00
taskId,
errorMessage: error ? error.message : null,
removedBoxBackupPaths: result ? result.removedBoxBackupPaths : [],
removedMailBackupPaths: result ? result.removedMailBackupPaths : [],
removedAppBackupPaths: result ? result.removedAppBackupPaths : [],
missingBackupPaths: result ? result.missingBackupPaths : []
2022-02-24 20:04:46 -08:00
}), { debug });
});
2021-07-14 11:07:19 -07:00
return taskId;
}
async function testConfig(backupConfig) {
assert.strictEqual(typeof backupConfig, 'object');
2021-07-14 11:07:19 -07:00
const func = storage.api(backupConfig.provider);
if (!func) return new BoxError(BoxError.BAD_FIELD, 'unknown storage provider');
if (backupConfig.format !== 'tgz' && backupConfig.format !== 'rsync') return new BoxError(BoxError.BAD_FIELD, 'unknown format');
2021-07-14 11:07:19 -07:00
const job = safe.safeCall(function () { return new CronJob(backupConfig.schedulePattern); });
if (!job) return new BoxError(BoxError.BAD_FIELD, 'Invalid schedule pattern');
2021-07-14 11:07:19 -07:00
if ('password' in backupConfig) {
if (typeof backupConfig.password !== 'string') return new BoxError(BoxError.BAD_FIELD, 'password must be a string');
if (backupConfig.password.length < 8) return new BoxError(BoxError.BAD_FIELD, 'password must be atleast 8 characters');
2021-07-14 11:07:19 -07:00
}
2021-07-14 11:07:19 -07:00
const policy = backupConfig.retentionPolicy;
if (!policy) return new BoxError(BoxError.BAD_FIELD, 'retentionPolicy is required');
if (!['keepWithinSecs','keepDaily','keepWeekly','keepMonthly','keepYearly'].find(k => !!policy[k])) return new BoxError(BoxError.BAD_FIELD, 'properties missing');
if ('keepWithinSecs' in policy && typeof policy.keepWithinSecs !== 'number') return new BoxError(BoxError.BAD_FIELD, 'keepWithinSecs must be a number');
if ('keepDaily' in policy && typeof policy.keepDaily !== 'number') return new BoxError(BoxError.BAD_FIELD, 'keepDaily must be a number');
if ('keepWeekly' in policy && typeof policy.keepWeekly !== 'number') return new BoxError(BoxError.BAD_FIELD, 'keepWeekly must be a number');
if ('keepMonthly' in policy && typeof policy.keepMonthly !== 'number') return new BoxError(BoxError.BAD_FIELD, 'keepMonthly must be a number');
if ('keepYearly' in policy && typeof policy.keepYearly !== 'number') return new BoxError(BoxError.BAD_FIELD, 'keepYearly must be a number');
2022-04-14 07:59:50 -05:00
await storage.api(backupConfig.provider).testConfig(backupConfig);
}
2017-10-10 20:23:04 -07:00
2021-07-14 11:07:19 -07:00
// this skips password check since that policy is only at creation time
async function testProviderConfig(backupConfig) {
assert.strictEqual(typeof backupConfig, 'object');
2021-07-14 11:07:19 -07:00
const func = storage.api(backupConfig.provider);
if (!func) return new BoxError(BoxError.BAD_FIELD, 'unknown storage provider');
2018-09-26 12:39:33 -07:00
2022-04-14 07:59:50 -05:00
await storage.api(backupConfig.provider).testConfig(backupConfig);
2020-02-26 09:08:30 -08:00
}
async function remount(auditSource) {
assert.strictEqual(typeof auditSource, 'object');
const backupConfig = await settings.getBackupConfig();
const func = storage.api(backupConfig.provider);
if (!func) throw new BoxError(BoxError.BAD_FIELD, 'unknown storage provider');
2022-04-14 07:43:43 -05:00
await storage.api(backupConfig.provider).remount(backupConfig);
}