access-list.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. const _ = require('lodash');
  2. const fs = require('fs');
  3. const batchflow = require('batchflow');
  4. const logger = require('../logger').access;
  5. const error = require('../lib/error');
  6. const utils = require('../lib/utils');
  7. const accessListModel = require('../models/access_list');
  8. const accessListAuthModel = require('../models/access_list_auth');
  9. const accessListClientModel = require('../models/access_list_client');
  10. const proxyHostModel = require('../models/proxy_host');
  11. const internalAuditLog = require('./audit-log');
  12. const internalNginx = require('./nginx');
  13. function omissions () {
  14. return ['is_deleted'];
  15. }
  16. const internalAccessList = {
  17. /**
  18. * @param {Access} access
  19. * @param {Object} data
  20. * @returns {Promise}
  21. */
  22. create: (access, data) => {
  23. return access.can('access_lists:create', data)
  24. .then((/*access_data*/) => {
  25. return accessListModel
  26. .query()
  27. .insertAndFetch({
  28. name: data.name,
  29. satisfy_any: data.satisfy_any,
  30. pass_auth: data.pass_auth,
  31. owner_user_id: access.token.getUserId(1)
  32. })
  33. .then(utils.omitRow(omissions()));
  34. })
  35. .then((row) => {
  36. data.id = row.id;
  37. let promises = [];
  38. // Now add the items
  39. data.items.map((item) => {
  40. promises.push(accessListAuthModel
  41. .query()
  42. .insert({
  43. access_list_id: row.id,
  44. username: item.username,
  45. password: item.password
  46. })
  47. );
  48. });
  49. // Now add the clients
  50. if (typeof data.clients !== 'undefined' && data.clients) {
  51. data.clients.map((client) => {
  52. promises.push(accessListClientModel
  53. .query()
  54. .insert({
  55. access_list_id: row.id,
  56. address: client.address,
  57. directive: client.directive
  58. })
  59. );
  60. });
  61. }
  62. return Promise.all(promises);
  63. })
  64. .then(() => {
  65. // re-fetch with expansions
  66. return internalAccessList.get(access, {
  67. id: data.id,
  68. expand: ['owner', 'items', 'clients', 'proxy_hosts.access_list.[clients,items]']
  69. }, true /* <- skip masking */);
  70. })
  71. .then((row) => {
  72. // Audit log
  73. data.meta = _.assign({}, data.meta || {}, row.meta);
  74. return internalAccessList.build(row)
  75. .then(() => {
  76. if (row.proxy_host_count) {
  77. return internalNginx.bulkGenerateConfigs('proxy_host', row.proxy_hosts);
  78. }
  79. })
  80. .then(() => {
  81. // Add to audit log
  82. return internalAuditLog.add(access, {
  83. action: 'created',
  84. object_type: 'access-list',
  85. object_id: row.id,
  86. meta: internalAccessList.maskItems(data)
  87. });
  88. })
  89. .then(() => {
  90. return internalAccessList.maskItems(row);
  91. });
  92. });
  93. },
  94. /**
  95. * @param {Access} access
  96. * @param {Object} data
  97. * @param {Integer} data.id
  98. * @param {String} [data.name]
  99. * @param {String} [data.items]
  100. * @return {Promise}
  101. */
  102. update: (access, data) => {
  103. return access.can('access_lists:update', data.id)
  104. .then((/*access_data*/) => {
  105. return internalAccessList.get(access, {id: data.id});
  106. })
  107. .then((row) => {
  108. if (row.id !== data.id) {
  109. // Sanity check that something crazy hasn't happened
  110. throw new error.InternalValidationError('Access List could not be updated, IDs do not match: ' + row.id + ' !== ' + data.id);
  111. }
  112. })
  113. .then(() => {
  114. // patch name if specified
  115. if (typeof data.name !== 'undefined' && data.name) {
  116. return accessListModel
  117. .query()
  118. .where({id: data.id})
  119. .patch({
  120. name: data.name,
  121. satisfy_any: data.satisfy_any,
  122. pass_auth: data.pass_auth,
  123. });
  124. }
  125. })
  126. .then(() => {
  127. // Check for items and add/update/remove them
  128. if (typeof data.items !== 'undefined' && data.items) {
  129. let promises = [];
  130. let items_to_keep = [];
  131. data.items.map(function (item) {
  132. if (item.password) {
  133. promises.push(accessListAuthModel
  134. .query()
  135. .insert({
  136. access_list_id: data.id,
  137. username: item.username,
  138. password: item.password
  139. })
  140. );
  141. } else {
  142. // This was supplied with an empty password, which means keep it but don't change the password
  143. items_to_keep.push(item.username);
  144. }
  145. });
  146. let query = accessListAuthModel
  147. .query()
  148. .delete()
  149. .where('access_list_id', data.id);
  150. if (items_to_keep.length) {
  151. query.andWhere('username', 'NOT IN', items_to_keep);
  152. }
  153. return query
  154. .then(() => {
  155. // Add new items
  156. if (promises.length) {
  157. return Promise.all(promises);
  158. }
  159. });
  160. }
  161. })
  162. .then(() => {
  163. // Check for clients and add/update/remove them
  164. if (typeof data.clients !== 'undefined' && data.clients) {
  165. let promises = [];
  166. data.clients.map(function (client) {
  167. if (client.address) {
  168. promises.push(accessListClientModel
  169. .query()
  170. .insert({
  171. access_list_id: data.id,
  172. address: client.address,
  173. directive: client.directive
  174. })
  175. );
  176. }
  177. });
  178. let query = accessListClientModel
  179. .query()
  180. .delete()
  181. .where('access_list_id', data.id);
  182. return query
  183. .then(() => {
  184. // Add new items
  185. if (promises.length) {
  186. return Promise.all(promises);
  187. }
  188. });
  189. }
  190. })
  191. .then(() => {
  192. // Add to audit log
  193. return internalAuditLog.add(access, {
  194. action: 'updated',
  195. object_type: 'access-list',
  196. object_id: data.id,
  197. meta: internalAccessList.maskItems(data)
  198. });
  199. })
  200. .then(() => {
  201. // re-fetch with expansions
  202. return internalAccessList.get(access, {
  203. id: data.id,
  204. expand: ['owner', 'items', 'clients', 'proxy_hosts.[certificate,access_list.[clients,items]]']
  205. }, true /* <- skip masking */);
  206. })
  207. .then((row) => {
  208. return internalAccessList.build(row)
  209. .then(() => {
  210. if (row.proxy_host_count) {
  211. return internalNginx.bulkGenerateConfigs('proxy_host', row.proxy_hosts);
  212. }
  213. }).then(internalNginx.reload)
  214. .then(() => {
  215. return internalAccessList.maskItems(row);
  216. });
  217. });
  218. },
  219. /**
  220. * @param {Access} access
  221. * @param {Object} data
  222. * @param {Integer} data.id
  223. * @param {Array} [data.expand]
  224. * @param {Array} [data.omit]
  225. * @param {Boolean} [skip_masking]
  226. * @return {Promise}
  227. */
  228. get: (access, data, skip_masking) => {
  229. if (typeof data === 'undefined') {
  230. data = {};
  231. }
  232. return access.can('access_lists:get', data.id)
  233. .then((access_data) => {
  234. let query = accessListModel
  235. .query()
  236. .select('access_list.*', accessListModel.raw('COUNT(proxy_host.id) as proxy_host_count'))
  237. .joinRaw('LEFT JOIN `proxy_host` ON `proxy_host`.`access_list_id` = `access_list`.`id` AND `proxy_host`.`is_deleted` = 0')
  238. .where('access_list.is_deleted', 0)
  239. .andWhere('access_list.id', data.id)
  240. .allowGraph('[owner,items,clients,proxy_hosts.[certificate,access_list.[clients,items]]]')
  241. .first();
  242. if (access_data.permission_visibility !== 'all') {
  243. query.andWhere('access_list.owner_user_id', access.token.getUserId(1));
  244. }
  245. if (typeof data.expand !== 'undefined' && data.expand !== null) {
  246. query.withGraphFetched('[' + data.expand.join(', ') + ']');
  247. }
  248. return query.then(utils.omitRow(omissions()));
  249. })
  250. .then((row) => {
  251. if (!row || !row.id) {
  252. throw new error.ItemNotFoundError(data.id);
  253. }
  254. if (!skip_masking && typeof row.items !== 'undefined' && row.items) {
  255. row = internalAccessList.maskItems(row);
  256. }
  257. // Custom omissions
  258. if (typeof data.omit !== 'undefined' && data.omit !== null) {
  259. row = _.omit(row, data.omit);
  260. }
  261. return row;
  262. });
  263. },
  264. /**
  265. * @param {Access} access
  266. * @param {Object} data
  267. * @param {Integer} data.id
  268. * @param {String} [data.reason]
  269. * @returns {Promise}
  270. */
  271. delete: (access, data) => {
  272. return access.can('access_lists:delete', data.id)
  273. .then(() => {
  274. return internalAccessList.get(access, {id: data.id, expand: ['proxy_hosts', 'items', 'clients']});
  275. })
  276. .then((row) => {
  277. if (!row || !row.id) {
  278. throw new error.ItemNotFoundError(data.id);
  279. }
  280. // 1. update row to be deleted
  281. // 2. update any proxy hosts that were using it (ignoring permissions)
  282. // 3. reconfigure those hosts
  283. // 4. audit log
  284. // 1. update row to be deleted
  285. return accessListModel
  286. .query()
  287. .where('id', row.id)
  288. .patch({
  289. is_deleted: 1
  290. })
  291. .then(() => {
  292. // 2. update any proxy hosts that were using it (ignoring permissions)
  293. if (row.proxy_hosts) {
  294. return proxyHostModel
  295. .query()
  296. .where('access_list_id', '=', row.id)
  297. .patch({access_list_id: 0})
  298. .then(() => {
  299. // 3. reconfigure those hosts, then reload nginx
  300. // set the access_list_id to zero for these items
  301. row.proxy_hosts.map(function (val, idx) {
  302. row.proxy_hosts[idx].access_list_id = 0;
  303. });
  304. return internalNginx.bulkGenerateConfigs('proxy_host', row.proxy_hosts);
  305. })
  306. .then(() => {
  307. return internalNginx.reload();
  308. });
  309. }
  310. })
  311. .then(() => {
  312. // delete the htpasswd file
  313. let htpasswd_file = internalAccessList.getFilename(row);
  314. try {
  315. fs.unlinkSync(htpasswd_file);
  316. } catch (err) {
  317. // do nothing
  318. }
  319. })
  320. .then(() => {
  321. // 4. audit log
  322. return internalAuditLog.add(access, {
  323. action: 'deleted',
  324. object_type: 'access-list',
  325. object_id: row.id,
  326. meta: _.omit(internalAccessList.maskItems(row), ['is_deleted', 'proxy_hosts'])
  327. });
  328. });
  329. })
  330. .then(() => {
  331. return true;
  332. });
  333. },
  334. /**
  335. * All Lists
  336. *
  337. * @param {Access} access
  338. * @param {Array} [expand]
  339. * @param {String} [search_query]
  340. * @returns {Promise}
  341. */
  342. getAll: (access, expand, search_query) => {
  343. return access.can('access_lists:list')
  344. .then((access_data) => {
  345. let query = accessListModel
  346. .query()
  347. .select('access_list.*', accessListModel.raw('COUNT(proxy_host.id) as proxy_host_count'))
  348. .joinRaw('LEFT JOIN `proxy_host` ON `proxy_host`.`access_list_id` = `access_list`.`id` AND `proxy_host`.`is_deleted` = 0')
  349. .where('access_list.is_deleted', 0)
  350. .groupBy('access_list.id')
  351. .allowGraph('[owner,items,clients]')
  352. .orderBy('access_list.name', 'ASC');
  353. if (access_data.permission_visibility !== 'all') {
  354. query.andWhere('access_list.owner_user_id', access.token.getUserId(1));
  355. }
  356. // Query is used for searching
  357. if (typeof search_query === 'string') {
  358. query.where(function () {
  359. this.where('name', 'like', '%' + search_query + '%');
  360. });
  361. }
  362. if (typeof expand !== 'undefined' && expand !== null) {
  363. query.withGraphFetched('[' + expand.join(', ') + ']');
  364. }
  365. return query.then(utils.omitRows(omissions()));
  366. })
  367. .then((rows) => {
  368. if (rows) {
  369. rows.map(function (row, idx) {
  370. if (typeof row.items !== 'undefined' && row.items) {
  371. rows[idx] = internalAccessList.maskItems(row);
  372. }
  373. });
  374. }
  375. return rows;
  376. });
  377. },
  378. /**
  379. * Report use
  380. *
  381. * @param {Integer} user_id
  382. * @param {String} visibility
  383. * @returns {Promise}
  384. */
  385. getCount: (user_id, visibility) => {
  386. let query = accessListModel
  387. .query()
  388. .count('id as count')
  389. .where('is_deleted', 0);
  390. if (visibility !== 'all') {
  391. query.andWhere('owner_user_id', user_id);
  392. }
  393. return query.first()
  394. .then((row) => {
  395. return parseInt(row.count, 10);
  396. });
  397. },
  398. /**
  399. * @param {Object} list
  400. * @returns {Object}
  401. */
  402. maskItems: (list) => {
  403. if (list && typeof list.items !== 'undefined') {
  404. list.items.map(function (val, idx) {
  405. let repeat_for = 8;
  406. let first_char = '*';
  407. if (typeof val.password !== 'undefined' && val.password) {
  408. repeat_for = val.password.length - 1;
  409. first_char = val.password.charAt(0);
  410. }
  411. list.items[idx].hint = first_char + ('*').repeat(repeat_for);
  412. list.items[idx].password = '';
  413. });
  414. }
  415. return list;
  416. },
  417. /**
  418. * @param {Object} list
  419. * @param {Integer} list.id
  420. * @returns {String}
  421. */
  422. getFilename: (list) => {
  423. return '/data/access/' + list.id;
  424. },
  425. /**
  426. * @param {Object} list
  427. * @param {Integer} list.id
  428. * @param {String} list.name
  429. * @param {Array} list.items
  430. * @returns {Promise}
  431. */
  432. build: (list) => {
  433. logger.info('Building Access file #' + list.id + ' for: ' + list.name);
  434. return new Promise((resolve, reject) => {
  435. let htpasswd_file = internalAccessList.getFilename(list);
  436. // 1. remove any existing access file
  437. try {
  438. fs.unlinkSync(htpasswd_file);
  439. } catch (err) {
  440. // do nothing
  441. }
  442. // 2. create empty access file
  443. try {
  444. fs.writeFileSync(htpasswd_file, '', {encoding: 'utf8'});
  445. resolve(htpasswd_file);
  446. } catch (err) {
  447. reject(err);
  448. }
  449. })
  450. .then((htpasswd_file) => {
  451. // 3. generate password for each user
  452. if (list.items.length) {
  453. return new Promise((resolve, reject) => {
  454. batchflow(list.items).sequential()
  455. .each((i, item, next) => {
  456. if (typeof item.password !== 'undefined' && item.password.length) {
  457. logger.info('Adding: ' + item.username);
  458. utils.execFile('/usr/bin/htpasswd', ['-b', htpasswd_file, item.username, item.password])
  459. .then((/*result*/) => {
  460. next();
  461. })
  462. .catch((err) => {
  463. logger.error(err);
  464. next(err);
  465. });
  466. }
  467. })
  468. .error((err) => {
  469. logger.error(err);
  470. reject(err);
  471. })
  472. .end((results) => {
  473. logger.success('Built Access file #' + list.id + ' for: ' + list.name);
  474. resolve(results);
  475. });
  476. });
  477. }
  478. });
  479. }
  480. };
  481. module.exports = internalAccessList;