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.

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