auth.js 14 KB

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