config-manager.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. const logger = require('@alias/logger')('growi:service:ConfigManager');
  2. const parseISO = require('date-fns/parseISO');
  3. const S2sMessage = require('../models/vo/s2s-message');
  4. const S2sMessageHandlable = require('./s2s-messaging/handlable');
  5. const ConfigLoader = require('./config-loader');
  6. const KEYS_FOR_LOCAL_STRATEGY_USE_ONLY_ENV_OPTION = [
  7. 'security:passport-local:isEnabled',
  8. ];
  9. const KEYS_FOR_SAML_USE_ONLY_ENV_OPTION = [
  10. 'security:passport-saml:isEnabled',
  11. 'security:passport-saml:entryPoint',
  12. 'security:passport-saml:issuer',
  13. 'security:passport-saml:attrMapId',
  14. 'security:passport-saml:attrMapUsername',
  15. 'security:passport-saml:attrMapMail',
  16. 'security:passport-saml:attrMapFirstName',
  17. 'security:passport-saml:attrMapLastName',
  18. 'security:passport-saml:cert',
  19. 'security:passport-saml:ABLCRule',
  20. ];
  21. const KEYS_FOR_FIEL_UPLOAD_USE_ONLY_ENV_OPTION = [
  22. 'app:fileUploadType',
  23. ];
  24. const KEYS_FOR_GCS_USE_ONLY_ENV_OPTION = [
  25. 'gcs:apiKeyJsonPath',
  26. 'gcs:bucket',
  27. 'gcs:uploadNamespace',
  28. ];
  29. class ConfigManager extends S2sMessageHandlable {
  30. constructor(configModel) {
  31. super();
  32. this.configModel = configModel;
  33. this.configLoader = new ConfigLoader(this.configModel);
  34. this.configObject = null;
  35. this.configKeys = [];
  36. this.lastLoadedAt = null;
  37. this.getConfig = this.getConfig.bind(this);
  38. }
  39. /**
  40. * load configs from the database and the environment variables
  41. */
  42. async loadConfigs() {
  43. this.configObject = await this.configLoader.load();
  44. logger.debug('ConfigManager#loadConfigs', this.configObject);
  45. // cache all config keys
  46. this.reloadConfigKeys();
  47. this.lastLoadedAt = new Date();
  48. }
  49. /**
  50. * Set S2sMessagingServiceDelegator instance
  51. * @param {S2sMessagingServiceDelegator} s2sMessagingService
  52. */
  53. async setS2sMessagingService(s2sMessagingService) {
  54. this.s2sMessagingService = s2sMessagingService;
  55. }
  56. /**
  57. * get a config specified by namespace & key
  58. *
  59. * Basically, this searches a specified config from configs loaded from the database at first
  60. * and then from configs loaded from the environment variables.
  61. *
  62. * In some case, this search method changes.
  63. *
  64. * the followings are the meanings of each special return value.
  65. * - null: a specified config is not set.
  66. * - undefined: a specified config does not exist.
  67. */
  68. getConfig(namespace, key) {
  69. let value;
  70. if (this.shouldSearchedFromEnvVarsOnly(namespace, key)) {
  71. value = this.searchOnlyFromEnvVarConfigs(namespace, key);
  72. }
  73. else {
  74. value = this.defaultSearch(namespace, key);
  75. }
  76. logger.debug(key, value);
  77. return value;
  78. }
  79. /**
  80. * get a config specified by namespace and regular expression
  81. */
  82. getConfigByRegExp(namespace, regexp) {
  83. const result = {};
  84. for (const key of this.configKeys) {
  85. if (regexp.test(key)) {
  86. result[key] = this.getConfig(namespace, key);
  87. }
  88. }
  89. return result;
  90. }
  91. /**
  92. * get a config specified by namespace and prefix
  93. */
  94. getConfigByPrefix(namespace, prefix) {
  95. const regexp = new RegExp(`^${prefix}`);
  96. return this.getConfigByRegExp(namespace, regexp);
  97. }
  98. /**
  99. * generate an array of config keys from this.configObject
  100. */
  101. getConfigKeys() {
  102. // type: fromDB, fromEnvVars
  103. const types = Object.keys(this.configObject);
  104. let namespaces = [];
  105. let keys = [];
  106. for (const type of types) {
  107. if (this.configObject[type] != null) {
  108. // ns: crowi, markdown, notification
  109. namespaces = [...namespaces, ...Object.keys(this.configObject[type])];
  110. }
  111. }
  112. // remove duplicates
  113. namespaces = [...new Set(namespaces)];
  114. for (const type of types) {
  115. for (const ns of namespaces) {
  116. if (this.configObject[type][ns] != null) {
  117. keys = [...keys, ...Object.keys(this.configObject[type][ns])];
  118. }
  119. }
  120. }
  121. // remove duplicates
  122. keys = [...new Set(keys)];
  123. return keys;
  124. }
  125. reloadConfigKeys() {
  126. this.configKeys = this.getConfigKeys();
  127. }
  128. /**
  129. * get a config specified by namespace & key from configs loaded from the database
  130. *
  131. * **Do not use this unless absolutely necessary. Use getConfig instead.**
  132. */
  133. getConfigFromDB(namespace, key) {
  134. return this.searchOnlyFromDBConfigs(namespace, key);
  135. }
  136. /**
  137. * get a config specified by namespace & key from configs loaded from the environment variables
  138. *
  139. * **Do not use this unless absolutely necessary. Use getConfig instead.**
  140. */
  141. getConfigFromEnvVars(namespace, key) {
  142. return this.searchOnlyFromEnvVarConfigs(namespace, key);
  143. }
  144. /**
  145. * update configs in the same namespace
  146. *
  147. * Specified values are encoded by convertInsertValue.
  148. * In it, an empty string is converted to null that indicates a config is not set.
  149. *
  150. * For example:
  151. * ```
  152. * updateConfigsInTheSameNamespace(
  153. * 'some namespace',
  154. * {
  155. * 'some key 1': 'value 1',
  156. * 'some key 2': 'value 2',
  157. * ...
  158. * }
  159. * );
  160. * ```
  161. */
  162. async updateConfigsInTheSameNamespace(namespace, configs, withoutPublishingS2sMessage) {
  163. const queries = [];
  164. for (const key of Object.keys(configs)) {
  165. queries.push({
  166. updateOne: {
  167. filter: { ns: namespace, key },
  168. update: { ns: namespace, key, value: this.convertInsertValue(configs[key]) },
  169. upsert: true,
  170. },
  171. });
  172. }
  173. await this.configModel.bulkWrite(queries);
  174. await this.loadConfigs();
  175. // publish updated date after reloading
  176. if (this.s2sMessagingService != null && !withoutPublishingS2sMessage) {
  177. this.publishUpdateMessage();
  178. }
  179. }
  180. /**
  181. * return whether the specified namespace/key should be retrieved only from env vars
  182. */
  183. shouldSearchedFromEnvVarsOnly(namespace, key) {
  184. return (namespace === 'crowi' && (
  185. // local strategy
  186. (
  187. KEYS_FOR_LOCAL_STRATEGY_USE_ONLY_ENV_OPTION.includes(key)
  188. && this.defaultSearch('crowi', 'security:passport-local:useOnlyEnvVarsForSomeOptions')
  189. )
  190. // saml strategy
  191. || (
  192. KEYS_FOR_SAML_USE_ONLY_ENV_OPTION.includes(key)
  193. && this.defaultSearch('crowi', 'security:passport-saml:useOnlyEnvVarsForSomeOptions')
  194. )
  195. // file upload option
  196. || (
  197. KEYS_FOR_FIEL_UPLOAD_USE_ONLY_ENV_OPTION.includes(key)
  198. && this.searchOnlyFromEnvVarConfigs('crowi', 'app:useOnlyEnvVarForFileUploadType')
  199. )
  200. // gcs option
  201. || (
  202. KEYS_FOR_GCS_USE_ONLY_ENV_OPTION.includes(key)
  203. && this.searchOnlyFromEnvVarConfigs('crowi', 'gcs:useOnlyEnvVarsForSomeOptions')
  204. )
  205. ));
  206. }
  207. /*
  208. * All of the methods below are private APIs.
  209. */
  210. /**
  211. * search a specified config from configs loaded from the database at first
  212. * and then from configs loaded from the environment variables
  213. */
  214. defaultSearch(namespace, key) {
  215. // does not exist neither in db nor in env vars
  216. if (!this.configExistsInDB(namespace, key) && !this.configExistsInEnvVars(namespace, key)) {
  217. logger.debug(`${namespace}.${key} does not exist neither in db nor in env vars`);
  218. return undefined;
  219. }
  220. // only exists in db
  221. if (this.configExistsInDB(namespace, key) && !this.configExistsInEnvVars(namespace, key)) {
  222. logger.debug(`${namespace}.${key} only exists in db`);
  223. return this.configObject.fromDB[namespace][key];
  224. }
  225. // only exists env vars
  226. if (!this.configExistsInDB(namespace, key) && this.configExistsInEnvVars(namespace, key)) {
  227. logger.debug(`${namespace}.${key} only exists in env vars`);
  228. return this.configObject.fromEnvVars[namespace][key];
  229. }
  230. // exists both in db and in env vars [db > env var]
  231. if (this.configExistsInDB(namespace, key) && this.configExistsInEnvVars(namespace, key)) {
  232. if (this.configObject.fromDB[namespace][key] !== null) {
  233. logger.debug(`${namespace}.${key} exists both in db and in env vars. loaded from db`);
  234. return this.configObject.fromDB[namespace][key];
  235. }
  236. /* eslint-disable-next-line no-else-return */
  237. else {
  238. logger.debug(`${namespace}.${key} exists both in db and in env vars. loaded from env vars`);
  239. return this.configObject.fromEnvVars[namespace][key];
  240. }
  241. }
  242. }
  243. /**
  244. * search a specified config from configs loaded from the database
  245. */
  246. searchOnlyFromDBConfigs(namespace, key) {
  247. if (!this.configExistsInDB(namespace, key)) {
  248. return undefined;
  249. }
  250. return this.configObject.fromDB[namespace][key];
  251. }
  252. /**
  253. * search a specified config from configs loaded from the environment variables
  254. */
  255. searchOnlyFromEnvVarConfigs(namespace, key) {
  256. if (!this.configExistsInEnvVars(namespace, key)) {
  257. return undefined;
  258. }
  259. return this.configObject.fromEnvVars[namespace][key];
  260. }
  261. /**
  262. * check whether a specified config exists in configs loaded from the database
  263. */
  264. configExistsInDB(namespace, key) {
  265. if (this.configObject.fromDB[namespace] === undefined) {
  266. return false;
  267. }
  268. return this.configObject.fromDB[namespace][key] !== undefined;
  269. }
  270. /**
  271. * check whether a specified config exists in configs loaded from the environment variables
  272. */
  273. configExistsInEnvVars(namespace, key) {
  274. if (this.configObject.fromEnvVars[namespace] === undefined) {
  275. return false;
  276. }
  277. return this.configObject.fromEnvVars[namespace][key] !== undefined;
  278. }
  279. convertInsertValue(value) {
  280. return JSON.stringify(value === '' ? null : value);
  281. }
  282. async publishUpdateMessage() {
  283. const s2sMessage = new S2sMessage('configUpdated', { updatedAt: new Date() });
  284. try {
  285. await this.s2sMessagingService.publish(s2sMessage);
  286. }
  287. catch (e) {
  288. logger.error('Failed to publish update message with S2sMessagingService: ', e.message);
  289. }
  290. }
  291. /**
  292. * @inheritdoc
  293. */
  294. shouldHandleS2sMessage(s2sMessage) {
  295. const { eventName, updatedAt } = s2sMessage;
  296. if (eventName !== 'configUpdated' || updatedAt == null) {
  297. return false;
  298. }
  299. return this.lastLoadedAt == null || this.lastLoadedAt < parseISO(s2sMessage.updatedAt);
  300. }
  301. /**
  302. * @inheritdoc
  303. */
  304. async handleS2sMessage(s2sMessage) {
  305. logger.info('Reload configs by pubsub notification');
  306. return this.loadConfigs();
  307. }
  308. }
  309. module.exports = ConfigManager;