auth.mjs 15 KB

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