access-list.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  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 (parseInt(row.proxy_host_count, 10)) {
  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 (parseInt(row.proxy_host_count, 10)) {
  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. .leftJoin('proxy_host', function() {
  238. this.on('proxy_host.access_list_id', '=', 'access_list.id')
  239. .andOn('proxy_host.is_deleted', '=', 0);
  240. })
  241. .where('access_list.is_deleted', 0)
  242. .andWhere('access_list.id', data.id)
  243. .allowGraph('[owner,items,clients,proxy_hosts.[certificate,access_list.[clients,items]]]')
  244. .first();
  245. if (access_data.permission_visibility !== 'all') {
  246. query.andWhere('access_list.owner_user_id', access.token.getUserId(1));
  247. }
  248. if (typeof data.expand !== 'undefined' && data.expand !== null) {
  249. query.withGraphFetched('[' + data.expand.join(', ') + ']');
  250. }
  251. return query.then(utils.omitRow(omissions()));
  252. })
  253. .then((row) => {
  254. if (!row || !row.id) {
  255. throw new error.ItemNotFoundError(data.id);
  256. }
  257. if (!skip_masking && typeof row.items !== 'undefined' && row.items) {
  258. row = internalAccessList.maskItems(row);
  259. }
  260. // Custom omissions
  261. if (typeof data.omit !== 'undefined' && data.omit !== null) {
  262. row = _.omit(row, data.omit);
  263. }
  264. return row;
  265. });
  266. },
  267. /**
  268. * @param {Access} access
  269. * @param {Object} data
  270. * @param {Integer} data.id
  271. * @param {String} [data.reason]
  272. * @returns {Promise}
  273. */
  274. delete: (access, data) => {
  275. return access.can('access_lists:delete', data.id)
  276. .then(() => {
  277. return internalAccessList.get(access, {id: data.id, expand: ['proxy_hosts', 'items', 'clients']});
  278. })
  279. .then((row) => {
  280. if (!row || !row.id) {
  281. throw new error.ItemNotFoundError(data.id);
  282. }
  283. // 1. update row to be deleted
  284. // 2. update any proxy hosts that were using it (ignoring permissions)
  285. // 3. reconfigure those hosts
  286. // 4. audit log
  287. // 1. update row to be deleted
  288. return accessListModel
  289. .query()
  290. .where('id', row.id)
  291. .patch({
  292. is_deleted: 1
  293. })
  294. .then(() => {
  295. // 2. update any proxy hosts that were using it (ignoring permissions)
  296. if (row.proxy_hosts) {
  297. return proxyHostModel
  298. .query()
  299. .where('access_list_id', '=', row.id)
  300. .patch({access_list_id: 0})
  301. .then(() => {
  302. // 3. reconfigure those hosts, then reload nginx
  303. // set the access_list_id to zero for these items
  304. row.proxy_hosts.map(function (val, idx) {
  305. row.proxy_hosts[idx].access_list_id = 0;
  306. });
  307. return internalNginx.bulkGenerateConfigs('proxy_host', row.proxy_hosts);
  308. })
  309. .then(() => {
  310. return internalNginx.reload();
  311. });
  312. }
  313. })
  314. .then(() => {
  315. // delete the htpasswd file
  316. let htpasswd_file = internalAccessList.getFilename(row);
  317. try {
  318. fs.unlinkSync(htpasswd_file);
  319. } catch (err) {
  320. // do nothing
  321. }
  322. })
  323. .then(() => {
  324. // 4. audit log
  325. return internalAuditLog.add(access, {
  326. action: 'deleted',
  327. object_type: 'access-list',
  328. object_id: row.id,
  329. meta: _.omit(internalAccessList.maskItems(row), ['is_deleted', 'proxy_hosts'])
  330. });
  331. });
  332. })
  333. .then(() => {
  334. return true;
  335. });
  336. },
  337. /**
  338. * All Lists
  339. *
  340. * @param {Access} access
  341. * @param {Array} [expand]
  342. * @param {String} [search_query]
  343. * @returns {Promise}
  344. */
  345. getAll: (access, expand, search_query) => {
  346. return access.can('access_lists:list')
  347. .then((access_data) => {
  348. let query = accessListModel
  349. .query()
  350. .select('access_list.*', accessListModel.raw('COUNT(proxy_host.id) as proxy_host_count'))
  351. .leftJoin('proxy_host', function() {
  352. this.on('proxy_host.access_list_id', '=', 'access_list.id')
  353. .andOn('proxy_host.is_deleted', '=', 0);
  354. })
  355. .where('access_list.is_deleted', 0)
  356. .groupBy('access_list.id')
  357. .allowGraph('[owner,items,clients]')
  358. .orderBy('access_list.name', 'ASC');
  359. if (access_data.permission_visibility !== 'all') {
  360. query.andWhere('access_list.owner_user_id', access.token.getUserId(1));
  361. }
  362. // Query is used for searching
  363. if (typeof search_query === 'string') {
  364. query.where(function () {
  365. this.where('name', 'like', '%' + search_query + '%');
  366. });
  367. }
  368. if (typeof expand !== 'undefined' && expand !== null) {
  369. query.withGraphFetched('[' + expand.join(', ') + ']');
  370. }
  371. return query.then(utils.omitRows(omissions()));
  372. })
  373. .then((rows) => {
  374. if (rows) {
  375. rows.map(function (row, idx) {
  376. if (typeof row.items !== 'undefined' && row.items) {
  377. rows[idx] = internalAccessList.maskItems(row);
  378. }
  379. });
  380. }
  381. return rows;
  382. });
  383. },
  384. /**
  385. * Report use
  386. *
  387. * @param {Integer} user_id
  388. * @param {String} visibility
  389. * @returns {Promise}
  390. */
  391. getCount: (user_id, visibility) => {
  392. let query = accessListModel
  393. .query()
  394. .count('id as count')
  395. .where('is_deleted', 0);
  396. if (visibility !== 'all') {
  397. query.andWhere('owner_user_id', user_id);
  398. }
  399. return query.first()
  400. .then((row) => {
  401. return parseInt(row.count, 10);
  402. });
  403. },
  404. /**
  405. * @param {Object} list
  406. * @returns {Object}
  407. */
  408. maskItems: (list) => {
  409. if (list && typeof list.items !== 'undefined') {
  410. list.items.map(function (val, idx) {
  411. let repeat_for = 8;
  412. let first_char = '*';
  413. if (typeof val.password !== 'undefined' && val.password) {
  414. repeat_for = val.password.length - 1;
  415. first_char = val.password.charAt(0);
  416. }
  417. list.items[idx].hint = first_char + ('*').repeat(repeat_for);
  418. list.items[idx].password = '';
  419. });
  420. }
  421. return list;
  422. },
  423. /**
  424. * @param {Object} list
  425. * @param {Integer} list.id
  426. * @returns {String}
  427. */
  428. getFilename: (list) => {
  429. return '/data/access/' + list.id;
  430. },
  431. /**
  432. * @param {Object} list
  433. * @param {Integer} list.id
  434. * @param {String} list.name
  435. * @param {Array} list.items
  436. * @returns {Promise}
  437. */
  438. build: (list) => {
  439. logger.info('Building Access file #' + list.id + ' for: ' + list.name);
  440. return new Promise((resolve, reject) => {
  441. let htpasswd_file = internalAccessList.getFilename(list);
  442. // 1. remove any existing access file
  443. try {
  444. fs.unlinkSync(htpasswd_file);
  445. } catch (err) {
  446. // do nothing
  447. }
  448. // 2. create empty access file
  449. try {
  450. fs.writeFileSync(htpasswd_file, '', {encoding: 'utf8'});
  451. resolve(htpasswd_file);
  452. } catch (err) {
  453. reject(err);
  454. }
  455. })
  456. .then((htpasswd_file) => {
  457. // 3. generate password for each user
  458. if (list.items.length) {
  459. return new Promise((resolve, reject) => {
  460. batchflow(list.items).sequential()
  461. .each((i, item, next) => {
  462. if (typeof item.password !== 'undefined' && item.password.length) {
  463. logger.info('Adding: ' + item.username);
  464. utils.execFile('/usr/bin/htpasswd', ['-b', htpasswd_file, item.username, item.password])
  465. .then((/*result*/) => {
  466. next();
  467. })
  468. .catch((err) => {
  469. logger.error(err);
  470. next(err);
  471. });
  472. }
  473. })
  474. .error((err) => {
  475. logger.error(err);
  476. reject(err);
  477. })
  478. .end((results) => {
  479. logger.success('Built Access file #' + list.id + ' for: ' + list.name);
  480. resolve(results);
  481. });
  482. });
  483. }
  484. });
  485. }
  486. };
  487. module.exports = internalAccessList;