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