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 accessListModel = require('../models/access_list');
  7. const accessListAuthModel = require('../models/access_list_auth');
  8. const accessListClientModel = require('../models/access_list_client');
  9. const proxyHostModel = require('../models/proxy_host');
  10. const internalAuditLog = require('./audit-log');
  11. const internalNginx = require('./nginx');
  12. const utils = require('../lib/utils');
  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. .omit(omissions())
  28. .insertAndFetch({
  29. name: data.name,
  30. satisfy_any: data.satisfy_any,
  31. pass_auth: data.pass_auth,
  32. owner_user_id: access.token.getUserId(1)
  33. });
  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(internalNginx.reload)
  192. .then(() => {
  193. // Add to audit log
  194. return internalAuditLog.add(access, {
  195. action: 'updated',
  196. object_type: 'access-list',
  197. object_id: data.id,
  198. meta: internalAccessList.maskItems(data)
  199. });
  200. })
  201. .then(() => {
  202. // re-fetch with expansions
  203. return internalAccessList.get(access, {
  204. id: data.id,
  205. expand: ['owner', 'items', 'clients', 'proxy_hosts.access_list.[clients,items]']
  206. }, true /* <- skip masking */);
  207. })
  208. .then((row) => {
  209. return internalAccessList.build(row)
  210. .then(() => {
  211. if (row.proxy_host_count) {
  212. return internalNginx.bulkGenerateConfigs('proxy_host', row.proxy_hosts);
  213. }
  214. })
  215. .then(() => {
  216. return internalAccessList.maskItems(row);
  217. });
  218. });
  219. },
  220. /**
  221. * @param {Access} access
  222. * @param {Object} data
  223. * @param {Integer} data.id
  224. * @param {Array} [data.expand]
  225. * @param {Array} [data.omit]
  226. * @param {Boolean} [skip_masking]
  227. * @return {Promise}
  228. */
  229. get: (access, data, skip_masking) => {
  230. if (typeof data === 'undefined') {
  231. data = {};
  232. }
  233. return access.can('access_lists:get', data.id)
  234. .then((access_data) => {
  235. let query = accessListModel
  236. .query()
  237. .select('access_list.*', accessListModel.raw('COUNT(proxy_host.id) as proxy_host_count'))
  238. .joinRaw('LEFT JOIN `proxy_host` ON `proxy_host`.`access_list_id` = `access_list`.`id` AND `proxy_host`.`is_deleted` = 0')
  239. .where('access_list.is_deleted', 0)
  240. .andWhere('access_list.id', data.id)
  241. .allowEager('[owner,items,clients,proxy_hosts.[*, access_list.[clients,items]]]')
  242. .omit(['access_list.is_deleted'])
  243. .first();
  244. if (access_data.permission_visibility !== 'all') {
  245. query.andWhere('access_list.owner_user_id', access.token.getUserId(1));
  246. }
  247. // Custom omissions
  248. if (typeof data.omit !== 'undefined' && data.omit !== null) {
  249. query.omit(data.omit);
  250. }
  251. if (typeof data.expand !== 'undefined' && data.expand !== null) {
  252. query.eager('[' + data.expand.join(', ') + ']');
  253. }
  254. return query;
  255. })
  256. .then((row) => {
  257. if (row) {
  258. if (!skip_masking && typeof row.items !== 'undefined' && row.items) {
  259. row = internalAccessList.maskItems(row);
  260. }
  261. return _.omit(row, omissions());
  262. } else {
  263. throw new error.ItemNotFoundError(data.id);
  264. }
  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) {
  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. .joinRaw('LEFT JOIN `proxy_host` ON `proxy_host`.`access_list_id` = `access_list`.`id` AND `proxy_host`.`is_deleted` = 0')
  352. .where('access_list.is_deleted', 0)
  353. .groupBy('access_list.id')
  354. .omit(['access_list.is_deleted'])
  355. .allowEager('[owner,items,clients]')
  356. .orderBy('access_list.name', 'ASC');
  357. if (access_data.permission_visibility !== 'all') {
  358. query.andWhere('access_list.owner_user_id', access.token.getUserId(1));
  359. }
  360. // Query is used for searching
  361. if (typeof search_query === 'string') {
  362. query.where(function () {
  363. this.where('name', 'like', '%' + search_query + '%');
  364. });
  365. }
  366. if (typeof expand !== 'undefined' && expand !== null) {
  367. query.eager('[' + expand.join(', ') + ']');
  368. }
  369. return query;
  370. })
  371. .then((rows) => {
  372. if (rows) {
  373. rows.map(function (row, idx) {
  374. if (typeof row.items !== 'undefined' && row.items) {
  375. rows[idx] = internalAccessList.maskItems(row);
  376. }
  377. });
  378. }
  379. return rows;
  380. });
  381. },
  382. /**
  383. * Report use
  384. *
  385. * @param {Integer} user_id
  386. * @param {String} visibility
  387. * @returns {Promise}
  388. */
  389. getCount: (user_id, visibility) => {
  390. let query = accessListModel
  391. .query()
  392. .count('id as count')
  393. .where('is_deleted', 0);
  394. if (visibility !== 'all') {
  395. query.andWhere('owner_user_id', user_id);
  396. }
  397. return query.first()
  398. .then((row) => {
  399. return parseInt(row.count, 10);
  400. });
  401. },
  402. /**
  403. * @param {Object} list
  404. * @returns {Object}
  405. */
  406. maskItems: (list) => {
  407. if (list && typeof list.items !== 'undefined') {
  408. list.items.map(function (val, idx) {
  409. let repeat_for = 8;
  410. let first_char = '*';
  411. if (typeof val.password !== 'undefined' && val.password) {
  412. repeat_for = val.password.length - 1;
  413. first_char = val.password.charAt(0);
  414. }
  415. list.items[idx].hint = first_char + ('*').repeat(repeat_for);
  416. list.items[idx].password = '';
  417. });
  418. }
  419. return list;
  420. },
  421. /**
  422. * @param {Object} list
  423. * @param {Integer} list.id
  424. * @returns {String}
  425. */
  426. getFilename: (list) => {
  427. return '/data/access/' + list.id;
  428. },
  429. /**
  430. * @param {Object} list
  431. * @param {Integer} list.id
  432. * @param {String} list.name
  433. * @param {Array} list.items
  434. * @returns {Promise}
  435. */
  436. build: (list) => {
  437. logger.info('Building Access file #' + list.id + ' for: ' + list.name);
  438. return new Promise((resolve, reject) => {
  439. let htpasswd_file = internalAccessList.getFilename(list);
  440. // 1. remove any existing access file
  441. try {
  442. fs.unlinkSync(htpasswd_file);
  443. } catch (err) {
  444. // do nothing
  445. }
  446. // 2. create empty access file
  447. try {
  448. fs.writeFileSync(htpasswd_file, '', {encoding: 'utf8'});
  449. resolve(htpasswd_file);
  450. } catch (err) {
  451. reject(err);
  452. }
  453. })
  454. .then((htpasswd_file) => {
  455. // 3. generate password for each user
  456. if (list.items.length) {
  457. return new Promise((resolve, reject) => {
  458. batchflow(list.items).sequential()
  459. .each((i, item, next) => {
  460. if (typeof item.password !== 'undefined' && item.password.length) {
  461. logger.info('Adding: ' + item.username);
  462. utils.execFile('/usr/bin/htpasswd', ['-b', htpasswd_file, item.username, item.password])
  463. .then((/*result*/) => {
  464. next();
  465. })
  466. .catch((err) => {
  467. logger.error(err);
  468. next(err);
  469. });
  470. }
  471. })
  472. .error((err) => {
  473. logger.error(err);
  474. reject(err);
  475. })
  476. .end((results) => {
  477. logger.success('Built Access file #' + list.id + ' for: ' + list.name);
  478. resolve(results);
  479. });
  480. });
  481. }
  482. });
  483. }
  484. };
  485. module.exports = internalAccessList;