auth.js 14 KB

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