userdirectory: move the validation and apply logic

This commit is contained in:
Girish Ramakrishnan
2022-02-16 12:57:38 -08:00
parent 2ed770affd
commit 426ed435a4
3 changed files with 48 additions and 31 deletions

View File

@@ -2,7 +2,10 @@
exports = module.exports = {
start,
stop
stop,
validateConfig,
applyConfig
};
const assert = require('assert'),
@@ -15,11 +18,15 @@ const assert = require('assert'),
fs = require('fs'),
groups = require('./groups.js'),
ldap = require('ldapjs'),
path = require('path'),
paths = require('./paths.js'),
reverseproxy = require('./reverseproxy.js'),
safe = require('safetydance'),
settings = require('./settings.js'),
shell = require('./shell.js'),
users = require('./users.js'),
util = require('util');
util = require('util'),
validator = require('validator');
var gServer = null;
@@ -27,6 +34,41 @@ const NOOP = function () {};
const GROUP_USERS_DN = 'cn=users,ou=groups,dc=cloudron';
const GROUP_ADMINS_DN = 'cn=admins,ou=groups,dc=cloudron';
const SET_LDAP_ALLOWLIST_CMD = path.join(__dirname, 'scripts/setldapallowlist.sh');
async function validateConfig(config) {
const { enabled, secret, allowlist } = config;
if (!enabled) return;
if (!secret) throw new BoxError(BoxError.BAD_FIELD, 'secret cannot be empty');
let gotOne = false;
for (const line of allowlist.split('\n')) {
if (!line || line.startsWith('#')) continue;
const rangeOrIP = line.trim();
// this checks for IPv4 and IPv6
if (!validator.isIP(rangeOrIP) && !validator.isIPRange(rangeOrIP)) throw new BoxError(BoxError.BAD_FIELD, `${rangeOrIP} is not a valid IP or range`);
gotOne = true;
}
// only allow if we at least have one allowed IP/range
if (!gotOne) throw new BoxError(BoxError.BAD_FIELD, 'allowlist must at least contain one IP or range');
}
async function applyConfig(config) {
assert.strictEqual(typeof config, 'object');
// this is done only because it's easier for the shell script and the firewall service to get the value
if (config.enabled) {
if (!safe.fs.writeFileSync(paths.LDAP_ALLOWLIST_FILE, config.allowlist + '\n', 'utf8')) throw new BoxError(BoxError.FS_ERROR, safe.error.message);
} else {
safe.fs.unlinkSync(paths.LDAP_ALLOWLIST_FILE);
}
const [error] = await safe(shell.promises.sudo('setLdapAllowlist', [ SET_LDAP_ALLOWLIST_CMD ], {}));
if (error) throw new BoxError(BoxError.IPTABLES_ERROR, `Error setting ldap allowlist: ${error.message}`);
}
// helper function to deal with pagination
function finalSend(results, req, res, next) {