passport.ts 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062
  1. import urljoin from 'url-join';
  2. import luceneQueryParser from 'lucene-query-parser';
  3. import passport from 'passport';
  4. import LdapStrategy from 'passport-ldapauth';
  5. import { Strategy as LocalStrategy } from 'passport-local';
  6. import { Strategy as GoogleStrategy } from 'passport-google-oauth20';
  7. import { Strategy as GitHubStrategy } from 'passport-github';
  8. import { Strategy as TwitterStrategy } from 'passport-twitter';
  9. import { Strategy as OidcStrategy, Issuer as OIDCIssuer } from 'openid-client';
  10. import { Profile, Strategy as SamlStrategy, VerifiedCallback } from 'passport-saml';
  11. import { BasicStrategy } from 'passport-http';
  12. import { IncomingMessage } from 'http';
  13. import axiosRetry from 'axios-retry';
  14. import pRetry from 'p-retry';
  15. import loggerFactory from '~/utils/logger';
  16. import S2sMessage from '../models/vo/s2s-message';
  17. import { S2sMessageHandlable } from './s2s-messaging/handlable';
  18. const logger = loggerFactory('growi:service:PassportService');
  19. interface IncomingMessageWithLdapAccountInfo extends IncomingMessage {
  20. ldapAccountInfo: any;
  21. }
  22. /**
  23. * the service class of Passport
  24. */
  25. class PassportService implements S2sMessageHandlable {
  26. // see '/lib/form/login.js'
  27. static get USERNAME_FIELD() { return 'loginForm[username]' }
  28. static get PASSWORD_FIELD() { return 'loginForm[password]' }
  29. crowi!: any;
  30. lastLoadedAt?: Date;
  31. /**
  32. * the flag whether LocalStrategy is set up successfully
  33. */
  34. isLocalStrategySetup = false;
  35. /**
  36. * the flag whether LdapStrategy is set up successfully
  37. */
  38. isLdapStrategySetup = false;
  39. /**
  40. * the flag whether GoogleStrategy is set up successfully
  41. */
  42. isGoogleStrategySetup = false;
  43. /**
  44. * the flag whether GitHubStrategy is set up successfully
  45. */
  46. isGitHubStrategySetup = false;
  47. /**
  48. * the flag whether TwitterStrategy is set up successfully
  49. */
  50. isTwitterStrategySetup = false;
  51. /**
  52. * the flag whether OidcStrategy is set up successfully
  53. */
  54. isOidcStrategySetup = false;
  55. /**
  56. * the flag whether SamlStrategy is set up successfully
  57. */
  58. isSamlStrategySetup = false;
  59. /**
  60. * the flag whether BasicStrategy is set up successfully
  61. */
  62. isBasicStrategySetup = false;
  63. /**
  64. * the flag whether serializer/deserializer are set up successfully
  65. */
  66. isSerializerSetup = false;
  67. /**
  68. * the keys of mandatory configs for SAML
  69. */
  70. mandatoryConfigKeysForSaml = [
  71. 'security:passport-saml:entryPoint',
  72. 'security:passport-saml:issuer',
  73. 'security:passport-saml:cert',
  74. 'security:passport-saml:attrMapId',
  75. 'security:passport-saml:attrMapUsername',
  76. 'security:passport-saml:attrMapMail',
  77. ];
  78. setupFunction = {
  79. local: {
  80. setup: 'setupLocalStrategy',
  81. reset: 'resetLocalStrategy',
  82. },
  83. ldap: {
  84. setup: 'setupLdapStrategy',
  85. reset: 'resetLdapStrategy',
  86. },
  87. saml: {
  88. setup: 'setupSamlStrategy',
  89. reset: 'resetSamlStrategy',
  90. },
  91. oidc: {
  92. setup: 'setupOidcStrategy',
  93. reset: 'resetOidcStrategy',
  94. },
  95. basic: {
  96. setup: 'setupBasicStrategy',
  97. reset: 'resetBasicStrategy',
  98. },
  99. google: {
  100. setup: 'setupGoogleStrategy',
  101. reset: 'resetGoogleStrategy',
  102. },
  103. github: {
  104. setup: 'setupGitHubStrategy',
  105. reset: 'resetGitHubStrategy',
  106. },
  107. twitter: {
  108. setup: 'setupTwitterStrategy',
  109. reset: 'resetTwitterStrategy',
  110. },
  111. };
  112. constructor(crowi: any) {
  113. this.crowi = crowi;
  114. }
  115. /**
  116. * @inheritdoc
  117. */
  118. shouldHandleS2sMessage(s2sMessage) {
  119. const { eventName, updatedAt, strategyId } = s2sMessage;
  120. if (eventName !== 'passportServiceUpdated' || updatedAt == null || strategyId == null) {
  121. return false;
  122. }
  123. return this.lastLoadedAt == null || this.lastLoadedAt < new Date(s2sMessage.updatedAt);
  124. }
  125. /**
  126. * @inheritdoc
  127. */
  128. async handleS2sMessage(s2sMessage) {
  129. const { configManager } = this.crowi;
  130. const { strategyId } = s2sMessage;
  131. logger.info('Reset strategy by pubsub notification');
  132. await configManager.loadConfigs();
  133. return this.setupStrategyById(strategyId);
  134. }
  135. async publishUpdatedMessage(strategyId) {
  136. const { s2sMessagingService } = this.crowi;
  137. if (s2sMessagingService != null) {
  138. const s2sMessage = new S2sMessage('passportStrategyReloaded', {
  139. updatedAt: new Date(),
  140. strategyId,
  141. });
  142. try {
  143. await s2sMessagingService.publish(s2sMessage);
  144. }
  145. catch (e) {
  146. logger.error('Failed to publish update message with S2sMessagingService: ', e.message);
  147. }
  148. }
  149. }
  150. /**
  151. * get SetupStrategies
  152. *
  153. * @return {Array}
  154. * @memberof PassportService
  155. */
  156. getSetupStrategies() {
  157. const setupStrategies: string[] = [];
  158. if (this.isLocalStrategySetup) { setupStrategies.push('local') }
  159. if (this.isLdapStrategySetup) { setupStrategies.push('ldap') }
  160. if (this.isSamlStrategySetup) { setupStrategies.push('saml') }
  161. if (this.isOidcStrategySetup) { setupStrategies.push('oidc') }
  162. if (this.isBasicStrategySetup) { setupStrategies.push('basic') }
  163. if (this.isGoogleStrategySetup) { setupStrategies.push('google') }
  164. if (this.isGitHubStrategySetup) { setupStrategies.push('github') }
  165. if (this.isTwitterStrategySetup) { setupStrategies.push('twitter') }
  166. return setupStrategies;
  167. }
  168. /**
  169. * get SetupFunction
  170. *
  171. * @return {Object}
  172. * @param {string} authId
  173. */
  174. getSetupFunction(authId) {
  175. return this.setupFunction[authId];
  176. }
  177. /**
  178. * setup strategy by target name
  179. */
  180. async setupStrategyById(authId) {
  181. const func = this.getSetupFunction(authId);
  182. try {
  183. this[func.setup]();
  184. }
  185. catch (err) {
  186. logger.debug(err);
  187. this[func.reset]();
  188. }
  189. this.lastLoadedAt = new Date();
  190. }
  191. /**
  192. * reset LocalStrategy
  193. *
  194. * @memberof PassportService
  195. */
  196. resetLocalStrategy() {
  197. logger.debug('LocalStrategy: reset');
  198. passport.unuse('local');
  199. this.isLocalStrategySetup = false;
  200. }
  201. /**
  202. * setup LocalStrategy
  203. *
  204. * @memberof PassportService
  205. */
  206. setupLocalStrategy() {
  207. this.resetLocalStrategy();
  208. const { configManager } = this.crowi;
  209. const isEnabled = configManager.getConfig('crowi', 'security:passport-local:isEnabled');
  210. // when disabled
  211. if (!isEnabled) {
  212. return;
  213. }
  214. logger.debug('LocalStrategy: setting up..');
  215. const User = this.crowi.model('User');
  216. passport.use(new LocalStrategy(
  217. {
  218. usernameField: PassportService.USERNAME_FIELD,
  219. passwordField: PassportService.PASSWORD_FIELD,
  220. },
  221. (username, password, done) => {
  222. // find user
  223. User.findUserByUsernameOrEmail(username, password, (err, user) => {
  224. if (err) { return done(err) }
  225. // check existence and password
  226. if (!user || !user.isPasswordValid(password)) {
  227. return done(null, false, { message: 'Incorrect credentials.' });
  228. }
  229. return done(null, user);
  230. });
  231. },
  232. ));
  233. this.isLocalStrategySetup = true;
  234. logger.debug('LocalStrategy: setup is done');
  235. }
  236. /**
  237. * reset LdapStrategy
  238. *
  239. * @memberof PassportService
  240. */
  241. resetLdapStrategy() {
  242. logger.debug('LdapStrategy: reset');
  243. passport.unuse('ldapauth');
  244. this.isLdapStrategySetup = false;
  245. }
  246. /**
  247. * Asynchronous configuration retrieval
  248. *
  249. * @memberof PassportService
  250. */
  251. setupLdapStrategy() {
  252. this.resetLdapStrategy();
  253. const config = this.crowi.config;
  254. const { configManager } = this.crowi;
  255. const isLdapEnabled = configManager.getConfig('crowi', 'security:passport-ldap:isEnabled');
  256. // when disabled
  257. if (!isLdapEnabled) {
  258. return;
  259. }
  260. logger.debug('LdapStrategy: setting up..');
  261. passport.use(new LdapStrategy(this.getLdapConfigurationFunc(config, { passReqToCallback: true }),
  262. (req, ldapAccountInfo, done) => {
  263. logger.debug('LDAP authentication has succeeded', ldapAccountInfo);
  264. // store ldapAccountInfo to req
  265. (req as IncomingMessageWithLdapAccountInfo).ldapAccountInfo = ldapAccountInfo;
  266. done(null, ldapAccountInfo);
  267. }));
  268. this.isLdapStrategySetup = true;
  269. logger.debug('LdapStrategy: setup is done');
  270. }
  271. /**
  272. * return attribute name for mapping to username of Crowi DB
  273. *
  274. * @returns
  275. * @memberof PassportService
  276. */
  277. getLdapAttrNameMappedToUsername() {
  278. return this.crowi.configManager.getConfig('crowi', 'security:passport-ldap:attrMapUsername') || 'uid';
  279. }
  280. /**
  281. * return attribute name for mapping to name of Crowi DB
  282. *
  283. * @returns
  284. * @memberof PassportService
  285. */
  286. getLdapAttrNameMappedToName() {
  287. return this.crowi.configManager.getConfig('crowi', 'security:passport-ldap:attrMapName') || '';
  288. }
  289. /**
  290. * return attribute name for mapping to name of Crowi DB
  291. *
  292. * @returns
  293. * @memberof PassportService
  294. */
  295. getLdapAttrNameMappedToMail() {
  296. return this.crowi.configManager.getConfig('crowi', 'security:passport-ldap:attrMapMail') || 'mail';
  297. }
  298. /**
  299. * CAUTION: this method is capable to use only when `req.body.loginForm` is not null
  300. *
  301. * @param {any} req
  302. * @returns
  303. * @memberof PassportService
  304. */
  305. getLdapAccountIdFromReq(req) {
  306. return req.body.loginForm.username;
  307. }
  308. /**
  309. * Asynchronous configuration retrieval
  310. * @see https://github.com/vesse/passport-ldapauth#asynchronous-configuration-retrieval
  311. *
  312. * @param {object} config
  313. * @param {object} opts
  314. * @returns
  315. * @memberof PassportService
  316. */
  317. getLdapConfigurationFunc(config, opts) {
  318. /* eslint-disable no-multi-spaces */
  319. const { configManager } = this.crowi;
  320. // get configurations
  321. const isUserBind = configManager.getConfig('crowi', 'security:passport-ldap:isUserBind');
  322. const serverUrl = configManager.getConfig('crowi', 'security:passport-ldap:serverUrl');
  323. const bindDN = configManager.getConfig('crowi', 'security:passport-ldap:bindDN');
  324. const bindCredentials = configManager.getConfig('crowi', 'security:passport-ldap:bindDNPassword');
  325. const searchFilter = configManager.getConfig('crowi', 'security:passport-ldap:searchFilter') || '(uid={{username}})';
  326. const groupSearchBase = configManager.getConfig('crowi', 'security:passport-ldap:groupSearchBase');
  327. const groupSearchFilter = configManager.getConfig('crowi', 'security:passport-ldap:groupSearchFilter');
  328. const groupDnProperty = configManager.getConfig('crowi', 'security:passport-ldap:groupDnProperty') || 'uid';
  329. /* eslint-enable no-multi-spaces */
  330. // parse serverUrl
  331. // see: https://regex101.com/r/0tuYBB/1
  332. const match = serverUrl.match(/(ldaps?:\/\/[^/]+)\/(.*)?/);
  333. if (match == null || match.length < 1) {
  334. logger.debug('LdapStrategy: serverUrl is invalid');
  335. return (req, callback) => { callback({ message: 'serverUrl is invalid' }) };
  336. }
  337. const url = match[1];
  338. const searchBase = match[2] || '';
  339. logger.debug(`LdapStrategy: url=${url}`);
  340. logger.debug(`LdapStrategy: searchBase=${searchBase}`);
  341. logger.debug(`LdapStrategy: isUserBind=${isUserBind}`);
  342. if (!isUserBind) {
  343. logger.debug(`LdapStrategy: bindDN=${bindDN}`);
  344. logger.debug(`LdapStrategy: bindCredentials=${bindCredentials}`);
  345. }
  346. logger.debug(`LdapStrategy: searchFilter=${searchFilter}`);
  347. logger.debug(`LdapStrategy: groupSearchBase=${groupSearchBase}`);
  348. logger.debug(`LdapStrategy: groupSearchFilter=${groupSearchFilter}`);
  349. logger.debug(`LdapStrategy: groupDnProperty=${groupDnProperty}`);
  350. return (req, callback) => {
  351. // get credentials from form data
  352. const loginForm = req.body.loginForm;
  353. if (!req.form.isValid) {
  354. return callback({ message: 'Incorrect credentials.' });
  355. }
  356. // user bind
  357. const fixedBindDN = (isUserBind)
  358. ? bindDN.replace(/{{username}}/, loginForm.username)
  359. : bindDN;
  360. const fixedBindCredentials = (isUserBind) ? loginForm.password : bindCredentials;
  361. let serverOpt = {
  362. url,
  363. bindDN: fixedBindDN,
  364. bindCredentials: fixedBindCredentials,
  365. searchBase,
  366. searchFilter,
  367. attrMapUsername: this.getLdapAttrNameMappedToUsername(),
  368. attrMapName: this.getLdapAttrNameMappedToName(),
  369. };
  370. if (groupSearchBase && groupSearchFilter) {
  371. serverOpt = Object.assign(serverOpt, { groupSearchBase, groupSearchFilter, groupDnProperty });
  372. }
  373. process.nextTick(() => {
  374. const mergedOpts = Object.assign({
  375. usernameField: PassportService.USERNAME_FIELD,
  376. passwordField: PassportService.PASSWORD_FIELD,
  377. server: serverOpt,
  378. }, opts);
  379. logger.debug('ldap configuration: ', mergedOpts);
  380. // store configuration to req
  381. req.ldapConfiguration = mergedOpts;
  382. callback(null, mergedOpts);
  383. });
  384. };
  385. }
  386. /**
  387. * Asynchronous configuration retrieval
  388. *
  389. * @memberof PassportService
  390. */
  391. setupGoogleStrategy() {
  392. this.resetGoogleStrategy();
  393. const { configManager } = this.crowi;
  394. const isGoogleEnabled = configManager.getConfig('crowi', 'security:passport-google:isEnabled');
  395. // when disabled
  396. if (!isGoogleEnabled) {
  397. return;
  398. }
  399. logger.debug('GoogleStrategy: setting up..');
  400. passport.use(
  401. new GoogleStrategy(
  402. {
  403. clientID: configManager.getConfig('crowi', 'security:passport-google:clientId'),
  404. clientSecret: configManager.getConfig('crowi', 'security:passport-google:clientSecret'),
  405. callbackURL: (this.crowi.appService.getSiteUrl() != null)
  406. ? urljoin(this.crowi.appService.getSiteUrl(), '/passport/google/callback') // auto-generated with v3.2.4 and above
  407. : configManager.getConfig('crowi', 'security:passport-google:callbackUrl'), // DEPRECATED: backward compatible with v3.2.3 and below
  408. skipUserProfile: false,
  409. },
  410. (accessToken, refreshToken, profile, done) => {
  411. if (profile) {
  412. return done(null, profile);
  413. }
  414. return done(null, false);
  415. },
  416. ),
  417. );
  418. this.isGoogleStrategySetup = true;
  419. logger.debug('GoogleStrategy: setup is done');
  420. }
  421. /**
  422. * reset GoogleStrategy
  423. *
  424. * @memberof PassportService
  425. */
  426. resetGoogleStrategy() {
  427. logger.debug('GoogleStrategy: reset');
  428. passport.unuse('google');
  429. this.isGoogleStrategySetup = false;
  430. }
  431. setupGitHubStrategy() {
  432. this.resetGitHubStrategy();
  433. const { configManager } = this.crowi;
  434. const isGitHubEnabled = configManager.getConfig('crowi', 'security:passport-github:isEnabled');
  435. // when disabled
  436. if (!isGitHubEnabled) {
  437. return;
  438. }
  439. logger.debug('GitHubStrategy: setting up..');
  440. passport.use(
  441. new GitHubStrategy(
  442. {
  443. clientID: configManager.getConfig('crowi', 'security:passport-github:clientId'),
  444. clientSecret: configManager.getConfig('crowi', 'security:passport-github:clientSecret'),
  445. callbackURL: (this.crowi.appService.getSiteUrl() != null)
  446. ? urljoin(this.crowi.appService.getSiteUrl(), '/passport/github/callback') // auto-generated with v3.2.4 and above
  447. : configManager.getConfig('crowi', 'security:passport-github:callbackUrl'), // DEPRECATED: backward compatible with v3.2.3 and below
  448. skipUserProfile: false,
  449. },
  450. (accessToken, refreshToken, profile, done) => {
  451. if (profile) {
  452. return done(null, profile);
  453. }
  454. return done(null, false);
  455. },
  456. ),
  457. );
  458. this.isGitHubStrategySetup = true;
  459. logger.debug('GitHubStrategy: setup is done');
  460. }
  461. /**
  462. * reset GitHubStrategy
  463. *
  464. * @memberof PassportService
  465. */
  466. resetGitHubStrategy() {
  467. logger.debug('GitHubStrategy: reset');
  468. passport.unuse('github');
  469. this.isGitHubStrategySetup = false;
  470. }
  471. setupTwitterStrategy() {
  472. this.resetTwitterStrategy();
  473. const { configManager } = this.crowi;
  474. const isTwitterEnabled = configManager.getConfig('crowi', 'security:passport-twitter:isEnabled');
  475. // when disabled
  476. if (!isTwitterEnabled) {
  477. return;
  478. }
  479. logger.debug('TwitterStrategy: setting up..');
  480. passport.use(
  481. new TwitterStrategy(
  482. {
  483. consumerKey: configManager.getConfig('crowi', 'security:passport-twitter:consumerKey'),
  484. consumerSecret: configManager.getConfig('crowi', 'security:passport-twitter:consumerSecret'),
  485. callbackURL: (this.crowi.appService.getSiteUrl() != null)
  486. ? urljoin(this.crowi.appService.getSiteUrl(), '/passport/twitter/callback') // auto-generated with v3.2.4 and above
  487. : configManager.getConfig('crowi', 'security:passport-twitter:callbackUrl'), // DEPRECATED: backward compatible with v3.2.3 and below
  488. skipUserProfile: false,
  489. },
  490. (accessToken, refreshToken, profile, done) => {
  491. if (profile) {
  492. return done(null, profile);
  493. }
  494. return done(null, false);
  495. },
  496. ),
  497. );
  498. this.isTwitterStrategySetup = true;
  499. logger.debug('TwitterStrategy: setup is done');
  500. }
  501. /**
  502. * reset TwitterStrategy
  503. *
  504. * @memberof PassportService
  505. */
  506. resetTwitterStrategy() {
  507. logger.debug('TwitterStrategy: reset');
  508. passport.unuse('twitter');
  509. this.isTwitterStrategySetup = false;
  510. }
  511. async setupOidcStrategy() {
  512. this.resetOidcStrategy();
  513. const { configManager } = this.crowi;
  514. const isOidcEnabled = configManager.getConfig('crowi', 'security:passport-oidc:isEnabled');
  515. // when disabled
  516. if (!isOidcEnabled) {
  517. return;
  518. }
  519. logger.debug('OidcStrategy: setting up..');
  520. // setup client
  521. // extend oidc request timeouts
  522. const OIDC_ISSUER_TIMEOUT_OPTION = await this.crowi.configManager.getConfig('crowi', 'security:passport-oidc:oidcIssuerTimeoutOption');
  523. OIDCIssuer.defaultHttpOptions = { timeout: OIDC_ISSUER_TIMEOUT_OPTION };
  524. const issuerHost = configManager.getConfig('crowi', 'security:passport-oidc:issuerHost');
  525. const clientId = configManager.getConfig('crowi', 'security:passport-oidc:clientId');
  526. const clientSecret = configManager.getConfig('crowi', 'security:passport-oidc:clientSecret');
  527. const redirectUri = (configManager.getConfig('crowi', 'app:siteUrl') != null)
  528. ? urljoin(this.crowi.appService.getSiteUrl(), '/passport/oidc/callback')
  529. : configManager.getConfig('crowi', 'security:passport-oidc:callbackUrl'); // DEPRECATED: backward compatible with v3.2.3 and below
  530. // Prevent request timeout error on app init
  531. const oidcIssuer = await this.getOIDCIssuerInstace(issuerHost);
  532. if (oidcIssuer != null) {
  533. logger.debug('Discovered issuer %s %O', oidcIssuer.issuer, oidcIssuer.metadata);
  534. const authorizationEndpoint = configManager.getConfig('crowi', 'security:passport-oidc:authorizationEndpoint');
  535. if (authorizationEndpoint) {
  536. oidcIssuer.metadata.authorization_endpoint = authorizationEndpoint;
  537. }
  538. const tokenEndpoint = configManager.getConfig('crowi', 'security:passport-oidc:tokenEndpoint');
  539. if (tokenEndpoint) {
  540. oidcIssuer.metadata.token_endpoint = tokenEndpoint;
  541. }
  542. const revocationEndpoint = configManager.getConfig('crowi', 'security:passport-oidc:revocationEndpoint');
  543. if (revocationEndpoint) {
  544. oidcIssuer.metadata.revocation_endpoint = revocationEndpoint;
  545. }
  546. const introspectionEndpoint = configManager.getConfig('crowi', 'security:passport-oidc:introspectionEndpoint');
  547. if (introspectionEndpoint) {
  548. oidcIssuer.metadata.introspection_endpoint = introspectionEndpoint;
  549. }
  550. const userInfoEndpoint = configManager.getConfig('crowi', 'security:passport-oidc:userInfoEndpoint');
  551. if (userInfoEndpoint) {
  552. oidcIssuer.metadata.userinfo_endpoint = userInfoEndpoint;
  553. }
  554. const endSessionEndpoint = configManager.getConfig('crowi', 'security:passport-oidc:endSessionEndpoint');
  555. if (endSessionEndpoint) {
  556. oidcIssuer.metadata.end_session_endpoint = endSessionEndpoint;
  557. }
  558. const registrationEndpoint = configManager.getConfig('crowi', 'security:passport-oidc:registrationEndpoint');
  559. if (registrationEndpoint) {
  560. oidcIssuer.metadata.registration_endpoint = registrationEndpoint;
  561. }
  562. const jwksUri = configManager.getConfig('crowi', 'security:passport-oidc:jwksUri');
  563. if (jwksUri) {
  564. oidcIssuer.metadata.jwks_uri = jwksUri;
  565. }
  566. logger.debug('Configured issuer %s %O', oidcIssuer.issuer, oidcIssuer.metadata);
  567. const client = new oidcIssuer.Client({
  568. client_id: clientId,
  569. client_secret: clientSecret,
  570. redirect_uris: [redirectUri],
  571. response_types: ['code'],
  572. });
  573. // prevent error AssertionError [ERR_ASSERTION]: id_token issued in the future
  574. // Doc: https://github.com/panva/node-openid-client/tree/v2.x#allow-for-system-clock-skew
  575. const OIDC_CLIENT_CLOCK_TOLERANCE = await this.crowi.configManager.getConfig('crowi', 'security:passport-oidc:oidcClientClockTolerance');
  576. client.CLOCK_TOLERANCE = OIDC_CLIENT_CLOCK_TOLERANCE;
  577. passport.use('oidc', new OidcStrategy(
  578. {
  579. client,
  580. params: { scope: 'openid email profile' },
  581. },
  582. (tokenset, userinfo, done) => {
  583. if (userinfo) {
  584. return done(null, userinfo);
  585. }
  586. return done(null, false);
  587. },
  588. ));
  589. this.isOidcStrategySetup = true;
  590. logger.debug('OidcStrategy: setup is done');
  591. }
  592. }
  593. /**
  594. * reset OidcStrategy
  595. *
  596. * @memberof PassportService
  597. */
  598. resetOidcStrategy() {
  599. logger.debug('OidcStrategy: reset');
  600. passport.unuse('oidc');
  601. this.isOidcStrategySetup = false;
  602. }
  603. /**
  604. *
  605. * Check and initialize connection to OIDC issuer host
  606. * Prevent request timeout error on app init
  607. *
  608. * @param issuerHost
  609. * @returns boolean
  610. */
  611. async isOidcHostReachable(issuerHost) {
  612. try {
  613. const client = require('axios').default;
  614. axiosRetry(client, {
  615. retries: 3,
  616. });
  617. const response = await client.get(`${issuerHost}/.well-known/openid-configuration`);
  618. // Check for valid OIDC Issuer configuration
  619. if (!response.data.issuer) {
  620. logger.debug('OidcStrategy: Invalid OIDC Issuer configurations');
  621. return false;
  622. }
  623. return true;
  624. }
  625. catch (err) {
  626. logger.error('OidcStrategy: issuer host unreachable:', err.code);
  627. }
  628. }
  629. /**
  630. * Get oidcIssuer object
  631. * Utilize p-retry package to retry oidcIssuer initialization 3 times
  632. *
  633. * @param issuerHost
  634. * @returns instance of OIDCIssuer
  635. */
  636. async getOIDCIssuerInstace(issuerHost) {
  637. const OIDC_TIMEOUT_MULTIPLIER = await this.crowi.configManager.getConfig('crowi', 'security:passport-oidc:timeoutMultiplier');
  638. const OIDC_DISCOVERY_RETRIES = await this.crowi.configManager.getConfig('crowi', 'security:passport-oidc:discoveryRetries');
  639. const oidcIssuerHostReady = await this.isOidcHostReachable(issuerHost);
  640. if (!oidcIssuerHostReady) {
  641. logger.error('OidcStrategy: setup failed');
  642. return;
  643. }
  644. const oidcIssuer = await pRetry(async() => {
  645. return OIDCIssuer.discover(issuerHost);
  646. }, {
  647. onFailedAttempt: (error) => {
  648. // get current OIDCIssuer.defaultHttpOptions.timeout
  649. const oidcOptionTimeout = OIDCIssuer.defaultHttpOptions.timeout;
  650. // Increases OIDCIssuer.defaultHttpOptions.timeout by multiply with 1.5
  651. OIDCIssuer.defaultHttpOptions = { timeout: oidcOptionTimeout * OIDC_TIMEOUT_MULTIPLIER };
  652. logger.debug(`OidcStrategy: setup attempt ${error.attemptNumber} failed with error: ${error}. Retrying ...`);
  653. },
  654. retries: OIDC_DISCOVERY_RETRIES,
  655. }).catch((error) => {
  656. logger.error(`OidcStrategy: setup failed with error: ${error} `);
  657. });
  658. return oidcIssuer;
  659. }
  660. setupSamlStrategy() {
  661. this.resetSamlStrategy();
  662. const { configManager } = this.crowi;
  663. const isSamlEnabled = configManager.getConfig('crowi', 'security:passport-saml:isEnabled');
  664. // when disabled
  665. if (!isSamlEnabled) {
  666. return;
  667. }
  668. logger.debug('SamlStrategy: setting up..');
  669. passport.use(
  670. new SamlStrategy(
  671. {
  672. entryPoint: configManager.getConfig('crowi', 'security:passport-saml:entryPoint'),
  673. callbackUrl: (this.crowi.appService.getSiteUrl() != null)
  674. ? urljoin(this.crowi.appService.getSiteUrl(), '/passport/saml/callback') // auto-generated with v3.2.4 and above
  675. : configManager.getConfig('crowi', 'security:passport-saml:callbackUrl'), // DEPRECATED: backward compatible with v3.2.3 and below
  676. issuer: configManager.getConfig('crowi', 'security:passport-saml:issuer'),
  677. cert: configManager.getConfig('crowi', 'security:passport-saml:cert'),
  678. },
  679. (profile: Profile, done: VerifiedCallback) => {
  680. if (profile) {
  681. return done(null, profile);
  682. }
  683. return done(null);
  684. },
  685. ),
  686. );
  687. this.isSamlStrategySetup = true;
  688. logger.debug('SamlStrategy: setup is done');
  689. }
  690. /**
  691. * reset SamlStrategy
  692. *
  693. * @memberof PassportService
  694. */
  695. resetSamlStrategy() {
  696. logger.debug('SamlStrategy: reset');
  697. passport.unuse('saml');
  698. this.isSamlStrategySetup = false;
  699. }
  700. /**
  701. * return the keys of the configs mandatory for SAML whose value are empty.
  702. */
  703. getSamlMissingMandatoryConfigKeys() {
  704. const missingRequireds: string[] = [];
  705. for (const key of this.mandatoryConfigKeysForSaml) {
  706. if (this.crowi.configManager.getConfig('crowi', key) === null) {
  707. missingRequireds.push(key);
  708. }
  709. }
  710. return missingRequireds;
  711. }
  712. /**
  713. * Parse Attribute-Based Login Control Rule as Lucene Query
  714. * @param {string} rule Lucene syntax string
  715. * @returns {object} Expression Tree Structure generated by lucene-query-parser
  716. * @see https://github.com/thoward/lucene-query-parser.js/wiki
  717. */
  718. parseABLCRule(rule) {
  719. // parse with lucene-query-parser
  720. // see https://github.com/thoward/lucene-query-parser.js/wiki
  721. return luceneQueryParser.parse(rule);
  722. }
  723. /**
  724. * Verify that a SAML response meets the attribute-base login control rule
  725. */
  726. verifySAMLResponseByABLCRule(response) {
  727. const rule = this.crowi.configManager.getConfig('crowi', 'security:passport-saml:ABLCRule');
  728. if (rule == null) {
  729. logger.debug('There is no ABLCRule.');
  730. return true;
  731. }
  732. const luceneRule = this.parseABLCRule(rule);
  733. logger.debug({ 'Parsed Rule': JSON.stringify(luceneRule, null, 2) });
  734. const attributes = this.extractAttributesFromSAMLResponse(response);
  735. logger.debug({ 'Extracted Attributes': JSON.stringify(attributes, null, 2) });
  736. return this.evaluateRuleForSamlAttributes(attributes, luceneRule);
  737. }
  738. /**
  739. * Evaluate whether the specified rule is satisfied under the specified attributes
  740. *
  741. * @param {object} attributes results by extractAttributesFromSAMLResponse
  742. * @param {object} luceneRule Expression Tree Structure generated by lucene-query-parser
  743. * @see https://github.com/thoward/lucene-query-parser.js/wiki
  744. */
  745. evaluateRuleForSamlAttributes(attributes, luceneRule) {
  746. const { left, right, operator } = luceneRule;
  747. // when combined rules
  748. if (right != null) {
  749. return this.evaluateCombinedRulesForSamlAttributes(attributes, left, right, operator);
  750. }
  751. if (left != null) {
  752. return this.evaluateRuleForSamlAttributes(attributes, left);
  753. }
  754. const { field, term } = luceneRule;
  755. const unescapedField = this.literalUnescape(field);
  756. if (unescapedField === '<implicit>') {
  757. return attributes[term] != null;
  758. }
  759. if (attributes[unescapedField] == null) {
  760. return false;
  761. }
  762. return attributes[unescapedField].includes(term);
  763. }
  764. /**
  765. * Evaluate whether the specified two rules are satisfied under the specified attributes
  766. *
  767. * @param {object} attributes results by extractAttributesFromSAMLResponse
  768. * @param {object} luceneRuleLeft Expression Tree Structure generated by lucene-query-parser
  769. * @param {object} luceneRuleRight Expression Tree Structure generated by lucene-query-parser
  770. * @param {string} luceneOperator operator string expression
  771. * @see https://github.com/thoward/lucene-query-parser.js/wiki
  772. */
  773. evaluateCombinedRulesForSamlAttributes(attributes, luceneRuleLeft, luceneRuleRight, luceneOperator) {
  774. if (luceneOperator === 'OR') {
  775. return this.evaluateRuleForSamlAttributes(attributes, luceneRuleLeft) || this.evaluateRuleForSamlAttributes(attributes, luceneRuleRight);
  776. }
  777. if (luceneOperator === 'AND') {
  778. return this.evaluateRuleForSamlAttributes(attributes, luceneRuleLeft) && this.evaluateRuleForSamlAttributes(attributes, luceneRuleRight);
  779. }
  780. if (luceneOperator === 'NOT') {
  781. return this.evaluateRuleForSamlAttributes(attributes, luceneRuleLeft) && !this.evaluateRuleForSamlAttributes(attributes, luceneRuleRight);
  782. }
  783. throw new Error(`Unsupported operator: ${luceneOperator}`);
  784. }
  785. /**
  786. * Extract attributes from a SAML response
  787. *
  788. * The format of extracted attributes is the following.
  789. *
  790. * {
  791. * "attribute_name1": ["value1", "value2", ...],
  792. * "attribute_name2": ["value1", "value2", ...],
  793. * ...
  794. * }
  795. */
  796. extractAttributesFromSAMLResponse(response) {
  797. const attributeStatement = response.getAssertion().Assertion.AttributeStatement;
  798. if (attributeStatement == null || attributeStatement[0] == null) {
  799. return {};
  800. }
  801. const attributes = attributeStatement[0].Attribute;
  802. if (attributes == null) {
  803. return {};
  804. }
  805. const result = {};
  806. for (const attribute of attributes) {
  807. const name = attribute.$.Name;
  808. const attributeValues = attribute.AttributeValue.map(v => v._);
  809. if (result[name] == null) {
  810. result[name] = attributeValues;
  811. }
  812. else {
  813. result[name] = result[name].concat(attributeValues);
  814. }
  815. }
  816. return result;
  817. }
  818. /**
  819. * reset BasicStrategy
  820. *
  821. * @memberof PassportService
  822. */
  823. resetBasicStrategy() {
  824. logger.debug('BasicStrategy: reset');
  825. passport.unuse('basic');
  826. this.isBasicStrategySetup = false;
  827. }
  828. /**
  829. * setup BasicStrategy
  830. *
  831. * @memberof PassportService
  832. */
  833. setupBasicStrategy() {
  834. this.resetBasicStrategy();
  835. const configManager = this.crowi.configManager;
  836. const isBasicEnabled = configManager.getConfig('crowi', 'security:passport-basic:isEnabled');
  837. // when disabled
  838. if (!isBasicEnabled) {
  839. return;
  840. }
  841. logger.debug('BasicStrategy: setting up..');
  842. passport.use(new BasicStrategy(
  843. (userId, password, done) => {
  844. if (userId != null) {
  845. return done(null, userId);
  846. }
  847. return done(null, false, { message: 'Incorrect credentials.' });
  848. },
  849. ));
  850. this.isBasicStrategySetup = true;
  851. logger.debug('BasicStrategy: setup is done');
  852. }
  853. /**
  854. * setup serializer and deserializer
  855. *
  856. * @memberof PassportService
  857. */
  858. setupSerializer() {
  859. // check whether the serializer/deserializer have already been set up
  860. if (this.isSerializerSetup) {
  861. throw new Error('serializer/deserializer have already been set up');
  862. }
  863. logger.debug('setting up serializer and deserializer');
  864. const User = this.crowi.model('User');
  865. passport.serializeUser((user, done) => {
  866. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  867. done(null, (user as any).id);
  868. });
  869. passport.deserializeUser(async(id, done) => {
  870. try {
  871. const user = await User.findById(id);
  872. if (user == null) {
  873. throw new Error('user not found');
  874. }
  875. if (user.imageUrlCached == null) {
  876. await user.updateImageUrlCached();
  877. await user.save();
  878. }
  879. done(null, user);
  880. }
  881. catch (err) {
  882. done(err);
  883. }
  884. });
  885. this.isSerializerSetup = true;
  886. }
  887. isSameUsernameTreatedAsIdenticalUser(providerType) {
  888. const key = `security:passport-${providerType}:isSameUsernameTreatedAsIdenticalUser`;
  889. return this.crowi.configManager.getConfig('crowi', key);
  890. }
  891. isSameEmailTreatedAsIdenticalUser(providerType) {
  892. const key = `security:passport-${providerType}:isSameEmailTreatedAsIdenticalUser`;
  893. return this.crowi.configManager.getConfig('crowi', key);
  894. }
  895. literalUnescape(string: string) {
  896. return string
  897. .replace(/\\\\/g, '\\')
  898. .replace(/\\\//g, '/')
  899. .replace(/\\:/g, ':')
  900. .replace(/\\"/g, '"')
  901. .replace(/\\0/g, '\0')
  902. .replace(/\\t/g, '\t')
  903. .replace(/\\n/g, '\n')
  904. .replace(/\\r/g, '\r');
  905. }
  906. }
  907. module.exports = PassportService;