passport.js 27 KB

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