You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

482 lines
15 KiB

5 years ago
  1. const passport = require('passport')
  2. const passportJWT = require('passport-jwt')
  3. const _ = require('lodash')
  4. const jwt = require('jsonwebtoken')
  5. const ms = require('ms')
  6. const { DateTime } = require('luxon')
  7. const Promise = require('bluebird')
  8. const crypto = Promise.promisifyAll(require('crypto'))
  9. const pem2jwk = require('pem-jwk').pem2jwk
  10. const securityHelper = require('../helpers/security')
  11. /* global WIKI */
  12. module.exports = {
  13. strategies: {},
  14. guest: {
  15. cacheExpiration: DateTime.utc().minus({ days: 1 })
  16. },
  17. groups: {},
  18. validApiKeys: [],
  19. revocationList: require('./cache').init(),
  20. /**
  21. * Initialize the authentication module
  22. */
  23. init() {
  24. this.passport = passport
  25. passport.serializeUser((user, done) => {
  26. done(null, user.id)
  27. })
  28. passport.deserializeUser(async (id, done) => {
  29. try {
  30. const user = await WIKI.models.users.query().findById(id).withGraphFetched('groups').modifyGraph('groups', builder => {
  31. builder.select('groups.id', 'permissions')
  32. })
  33. if (user) {
  34. done(null, user)
  35. } else {
  36. done(new Error(WIKI.lang.t('auth:errors:usernotfound')), null)
  37. }
  38. } catch (err) {
  39. done(err, null)
  40. }
  41. })
  42. this.reloadGroups()
  43. this.reloadApiKeys()
  44. return this
  45. },
  46. /**
  47. * Load authentication strategies
  48. */
  49. async activateStrategies () {
  50. try {
  51. // Unload any active strategies
  52. WIKI.auth.strategies = {}
  53. const currentStrategies = _.keys(passport._strategies)
  54. _.pull(currentStrategies, 'session')
  55. _.forEach(currentStrategies, stg => { passport.unuse(stg) })
  56. // Load JWT
  57. passport.use('jwt', new passportJWT.Strategy({
  58. jwtFromRequest: securityHelper.extractJWT,
  59. secretOrKey: WIKI.config.certs.public,
  60. audience: WIKI.config.auth.audience,
  61. issuer: 'urn:wiki.js',
  62. algorithms: ['RS256']
  63. }, (jwtPayload, cb) => {
  64. cb(null, jwtPayload)
  65. }))
  66. // Load enabled strategies
  67. const enabledStrategies = await WIKI.models.authentication.getStrategies()
  68. for (let idx in enabledStrategies) {
  69. const stg = enabledStrategies[idx]
  70. try {
  71. const strategy = require(`../modules/authentication/${stg.strategyKey}/authentication.js`)
  72. stg.config.callbackURL = `${WIKI.config.host}/login/${stg.key}/callback`
  73. stg.config.key = stg.key;
  74. strategy.init(passport, stg.config)
  75. strategy.config = stg.config
  76. WIKI.auth.strategies[stg.key] = {
  77. ...strategy,
  78. ...stg
  79. }
  80. WIKI.logger.info(`Authentication Strategy ${stg.displayName}: [ OK ]`)
  81. } catch (err) {
  82. WIKI.logger.error(`Authentication Strategy ${stg.displayName} (${stg.key}): [ FAILED ]`)
  83. WIKI.logger.error(err)
  84. }
  85. }
  86. } catch (err) {
  87. WIKI.logger.error(`Failed to initialize Authentication Strategies: [ ERROR ]`)
  88. WIKI.logger.error(err)
  89. }
  90. },
  91. /**
  92. * Authenticate current request
  93. *
  94. * @param {Express Request} req
  95. * @param {Express Response} res
  96. * @param {Express Next Callback} next
  97. */
  98. authenticate (req, res, next) {
  99. WIKI.auth.passport.authenticate('jwt', {session: false}, async (err, user, info) => {
  100. if (err) { return next() }
  101. let mustRevalidate = false
  102. // Expired but still valid within N days, just renew
  103. if (info instanceof Error && info.name === 'TokenExpiredError') {
  104. const expiredDate = (info.expiredAt instanceof Date) ? info.expiredAt.toISOString() : info.expiredAt
  105. if (DateTime.utc().minus(ms(WIKI.config.auth.tokenRenewal)) < DateTime.fromISO(expiredDate)) {
  106. mustRevalidate = true
  107. }
  108. }
  109. // Check if user / group is in revocation list
  110. if (user && !user.api && !mustRevalidate) {
  111. const uRevalidate = WIKI.auth.revocationList.get(`u${_.toString(user.id)}`)
  112. if (uRevalidate && user.iat < uRevalidate) {
  113. mustRevalidate = true
  114. } else if (DateTime.fromSeconds(user.iat) <= WIKI.startedAt) { // Prevent new / restarted instance from allowing revoked tokens
  115. mustRevalidate = true
  116. } else {
  117. for (const gid of user.groups) {
  118. const gRevalidate = WIKI.auth.revocationList.get(`g${_.toString(gid)}`)
  119. if (gRevalidate && user.iat < gRevalidate) {
  120. mustRevalidate = true
  121. break
  122. }
  123. }
  124. }
  125. }
  126. // Revalidate and renew token
  127. if (mustRevalidate) {
  128. const jwtPayload = jwt.decode(securityHelper.extractJWT(req))
  129. try {
  130. const newToken = await WIKI.models.users.refreshToken(jwtPayload.id)
  131. user = newToken.user
  132. user.permissions = user.getGlobalPermissions()
  133. user.groups = user.getGroups()
  134. req.user = user
  135. // Try headers, otherwise cookies for response
  136. if (req.get('content-type') === 'application/json') {
  137. res.set('new-jwt', newToken.token)
  138. } else {
  139. res.cookie('jwt', newToken.token, { expires: DateTime.utc().plus({ days: 365 }).toJSDate() })
  140. }
  141. } catch (errc) {
  142. WIKI.logger.warn(errc)
  143. return next()
  144. }
  145. }
  146. // JWT is NOT valid, set as guest
  147. if (!user) {
  148. if (WIKI.auth.guest.cacheExpiration <= DateTime.utc()) {
  149. WIKI.auth.guest = await WIKI.models.users.getGuestUser()
  150. WIKI.auth.guest.cacheExpiration = DateTime.utc().plus({ minutes: 1 })
  151. }
  152. req.user = WIKI.auth.guest
  153. return next()
  154. }
  155. // Process API tokens
  156. if (_.has(user, 'api')) {
  157. if (!WIKI.config.api.isEnabled) {
  158. return next(new Error('API is disabled. You must enable it from the Administration Area first.'))
  159. } else if (_.includes(WIKI.auth.validApiKeys, user.api)) {
  160. req.user = {
  161. id: 1,
  162. email: 'api@localhost',
  163. name: 'API',
  164. pictureUrl: null,
  165. timezone: 'America/New_York',
  166. localeCode: 'en',
  167. permissions: _.get(WIKI.auth.groups, `${user.grp}.permissions`, []),
  168. groups: [user.grp],
  169. getGlobalPermissions () {
  170. return req.user.permissions
  171. },
  172. getGroups () {
  173. return req.user.groups
  174. }
  175. }
  176. return next()
  177. } else {
  178. return next(new Error('API Key is invalid or was revoked.'))
  179. }
  180. }
  181. // JWT is valid
  182. req.logIn(user, { session: false }, (errc) => {
  183. if (errc) { return next(errc) }
  184. next()
  185. })
  186. })(req, res, next)
  187. },
  188. /**
  189. * Check if user has access to resource
  190. *
  191. * @param {User} user
  192. * @param {Array<String>} permissions
  193. * @param {String|Boolean} path
  194. */
  195. checkAccess(user, permissions = [], page = false) {
  196. const userPermissions = user.permissions ? user.permissions : user.getGlobalPermissions()
  197. // System Admin
  198. if (_.includes(userPermissions, 'manage:system')) {
  199. return true
  200. }
  201. // Check Global Permissions
  202. if (_.intersection(userPermissions, permissions).length < 1) {
  203. return false
  204. }
  205. // Skip if no page rule to check
  206. if (!page) {
  207. return true
  208. }
  209. // Check Page Rules
  210. if (user.groups) {
  211. let checkState = {
  212. deny: false,
  213. match: false,
  214. specificity: ''
  215. }
  216. user.groups.forEach(grp => {
  217. const grpId = _.isObject(grp) ? _.get(grp, 'id', 0) : grp
  218. _.get(WIKI.auth.groups, `${grpId}.pageRules`, []).forEach(rule => {
  219. if (rule.locales && rule.locales.length > 0) {
  220. if (!rule.locales.includes(page.locale)) { return }
  221. }
  222. if (_.intersection(rule.roles, permissions).length > 0) {
  223. switch (rule.match) {
  224. case 'START':
  225. if (_.startsWith(`/${page.path}`, `/${rule.path}`)) {
  226. checkState = this._applyPageRuleSpecificity({ rule, checkState, higherPriority: ['END', 'REGEX', 'EXACT', 'TAG'] })
  227. }
  228. break
  229. case 'END':
  230. if (_.endsWith(page.path, rule.path)) {
  231. checkState = this._applyPageRuleSpecificity({ rule, checkState, higherPriority: ['REGEX', 'EXACT', 'TAG'] })
  232. }
  233. break
  234. case 'REGEX':
  235. const reg = new RegExp(rule.path)
  236. if (reg.test(page.path)) {
  237. checkState = this._applyPageRuleSpecificity({ rule, checkState, higherPriority: ['EXACT', 'TAG'] })
  238. }
  239. break
  240. case 'TAG':
  241. _.get(page, 'tags', []).forEach(tag => {
  242. if (tag.tag === rule.path) {
  243. checkState = this._applyPageRuleSpecificity({
  244. rule,
  245. checkState,
  246. higherPriority: ['EXACT']
  247. })
  248. }
  249. })
  250. break
  251. case 'EXACT':
  252. if (`/${page.path}` === `/${rule.path}`) {
  253. checkState = this._applyPageRuleSpecificity({ rule, checkState, higherPriority: [] })
  254. }
  255. break
  256. }
  257. }
  258. })
  259. })
  260. return (checkState.match && !checkState.deny)
  261. }
  262. return false
  263. },
  264. /**
  265. * Check for exclusive permissions (contain any X permission(s) but not any Y permission(s))
  266. *
  267. * @param {User} user
  268. * @param {Array<String>} includePermissions
  269. * @param {Array<String>} excludePermissions
  270. */
  271. checkExclusiveAccess(user, includePermissions = [], excludePermissions = []) {
  272. const userPermissions = user.permissions ? user.permissions : user.getGlobalPermissions()
  273. // Check Inclusion Permissions
  274. if (_.intersection(userPermissions, includePermissions).length < 1) {
  275. return false
  276. }
  277. // Check Exclusion Permissions
  278. if (_.intersection(userPermissions, excludePermissions).length > 0) {
  279. return false
  280. }
  281. return true
  282. },
  283. /**
  284. * Check and apply Page Rule specificity
  285. *
  286. * @access private
  287. */
  288. _applyPageRuleSpecificity ({ rule, checkState, higherPriority = [] }) {
  289. if (rule.path.length === checkState.specificity.length) {
  290. // Do not override higher priority rules
  291. if (_.includes(higherPriority, checkState.match)) {
  292. return checkState
  293. }
  294. // Do not override a previous DENY rule with same match
  295. if (rule.match === checkState.match && checkState.deny && !rule.deny) {
  296. return checkState
  297. }
  298. } else if (rule.path.length < checkState.specificity.length) {
  299. // Do not override higher specificity rules
  300. return checkState
  301. }
  302. return {
  303. deny: rule.deny,
  304. match: rule.match,
  305. specificity: rule.path
  306. }
  307. },
  308. /**
  309. * Reload Groups from DB
  310. */
  311. async reloadGroups () {
  312. const groupsArray = await WIKI.models.groups.query()
  313. this.groups = _.keyBy(groupsArray, 'id')
  314. WIKI.auth.guest.cacheExpiration = DateTime.utc().minus({ days: 1 })
  315. },
  316. /**
  317. * Reload valid API Keys from DB
  318. */
  319. async reloadApiKeys () {
  320. const keys = await WIKI.models.apiKeys.query().select('id').where('isRevoked', false).andWhere('expiration', '>', DateTime.utc().toISO())
  321. this.validApiKeys = _.map(keys, 'id')
  322. },
  323. /**
  324. * Generate New Authentication Public / Private Key Certificates
  325. */
  326. async regenerateCertificates () {
  327. WIKI.logger.info('Regenerating certificates...')
  328. _.set(WIKI.config, 'sessionSecret', (await crypto.randomBytesAsync(32)).toString('hex'))
  329. const certs = crypto.generateKeyPairSync('rsa', {
  330. modulusLength: 2048,
  331. publicKeyEncoding: {
  332. type: 'pkcs1',
  333. format: 'pem'
  334. },
  335. privateKeyEncoding: {
  336. type: 'pkcs1',
  337. format: 'pem',
  338. cipher: 'aes-256-cbc',
  339. passphrase: WIKI.config.sessionSecret
  340. }
  341. })
  342. _.set(WIKI.config, 'certs', {
  343. jwk: pem2jwk(certs.publicKey),
  344. public: certs.publicKey,
  345. private: certs.privateKey
  346. })
  347. await WIKI.configSvc.saveToDb([
  348. 'certs',
  349. 'sessionSecret'
  350. ])
  351. await WIKI.auth.activateStrategies()
  352. WIKI.events.outbound.emit('reloadAuthStrategies')
  353. WIKI.logger.info('Regenerated certificates: [ COMPLETED ]')
  354. },
  355. /**
  356. * Reset Guest User
  357. */
  358. async resetGuestUser() {
  359. WIKI.logger.info('Resetting guest account...')
  360. const guestGroup = await WIKI.models.groups.query().where('id', 2).first()
  361. await WIKI.models.users.query().delete().where({
  362. providerKey: 'local',
  363. email: 'guest@example.com'
  364. }).orWhere('id', 2)
  365. const guestUser = await WIKI.models.users.query().insert({
  366. id: 2,
  367. provider: 'local',
  368. email: 'guest@example.com',
  369. name: 'Guest',
  370. password: '',
  371. locale: 'en',
  372. defaultEditor: 'markdown',
  373. tfaIsActive: false,
  374. isSystem: true,
  375. isActive: true,
  376. isVerified: true
  377. })
  378. await guestUser.$relatedQuery('groups').relate(guestGroup.id)
  379. WIKI.logger.info('Guest user has been reset: [ COMPLETED ]')
  380. },
  381. /**
  382. * Subscribe to HA propagation events
  383. */
  384. subscribeToEvents() {
  385. WIKI.events.inbound.on('reloadGroups', () => {
  386. WIKI.auth.reloadGroups()
  387. })
  388. WIKI.events.inbound.on('reloadApiKeys', () => {
  389. WIKI.auth.reloadApiKeys()
  390. })
  391. WIKI.events.inbound.on('reloadAuthStrategies', () => {
  392. WIKI.auth.activateStrategies()
  393. })
  394. WIKI.events.inbound.on('addAuthRevoke', (args) => {
  395. WIKI.auth.revokeUserTokens(args)
  396. })
  397. },
  398. /**
  399. * Get all user permissions for a specific page
  400. */
  401. getEffectivePermissions (req, page) {
  402. return {
  403. comments: {
  404. read: WIKI.config.features.featurePageComments ? WIKI.auth.checkAccess(req.user, ['read:comments'], page) : false,
  405. write: WIKI.config.features.featurePageComments ? WIKI.auth.checkAccess(req.user, ['write:comments'], page) : false,
  406. manage: WIKI.config.features.featurePageComments ? WIKI.auth.checkAccess(req.user, ['manage:comments'], page) : false
  407. },
  408. history: {
  409. read: WIKI.auth.checkAccess(req.user, ['read:history'], page)
  410. },
  411. source: {
  412. read: WIKI.auth.checkAccess(req.user, ['read:source'], page)
  413. },
  414. pages: {
  415. read: WIKI.auth.checkAccess(req.user, ['read:pages'], page),
  416. write: WIKI.auth.checkAccess(req.user, ['write:pages'], page),
  417. manage: WIKI.auth.checkAccess(req.user, ['manage:pages'], page),
  418. delete: WIKI.auth.checkAccess(req.user, ['delete:pages'], page),
  419. script: WIKI.auth.checkAccess(req.user, ['write:scripts'], page),
  420. style: WIKI.auth.checkAccess(req.user, ['write:styles'], page)
  421. },
  422. system: {
  423. manage: WIKI.auth.checkAccess(req.user, ['manage:system'], page)
  424. }
  425. }
  426. },
  427. /**
  428. * Add user / group ID to JWT revocation list, forcing all requests to be validated against the latest permissions
  429. */
  430. revokeUserTokens ({ id, kind = 'u' }) {
  431. WIKI.auth.revocationList.set(`${kind}${_.toString(id)}`, Math.round(DateTime.utc().minus({ seconds: 5 }).toSeconds()), Math.ceil(ms(WIKI.config.auth.tokenExpiration) / 1000))
  432. }
  433. }