passport.js 29 KB

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