auth.js 14.8 KB
Newer Older
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 8 9
const Promise = require('bluebird')
const crypto = Promise.promisifyAll(require('crypto'))
const pem2jwk = require('pem-jwk').pem2jwk
10

11
const securityHelper = require('../helpers/security')
12 13

/* global WIKI */
14

NGPixel's avatar
NGPixel committed
15
module.exports = {
16
  strategies: {},
17
  guest: {
18
    cacheExpiration: DateTime.utc().minus({ days: 1 })
19
  },
20
  groups: {},
21
  validApiKeys: [],
NGPixel's avatar
NGPixel committed
22
  revocationList: require('./cache').init(),
23 24 25 26

  /**
   * Initialize the authentication module
   */
27 28 29
  init() {
    this.passport = passport

30
    passport.serializeUser((user, done) => {
31
      done(null, user.id)
NGPixel's avatar
NGPixel committed
32
    })
33

34 35
    passport.deserializeUser(async (id, done) => {
      try {
NGPixel's avatar
NGPixel committed
36
        const user = await WIKI.models.users.query().findById(id).withGraphFetched('groups').modifyGraph('groups', builder => {
37 38
          builder.select('groups.id', 'permissions')
        })
39 40 41 42 43
        if (user) {
          done(null, user)
        } else {
          done(new Error(WIKI.lang.t('auth:errors:usernotfound')), null)
        }
44
      } catch (err) {
45
        done(err, null)
46
      }
47 48
    })

49
    this.reloadGroups()
50
    this.reloadApiKeys()
51

52
    return this
53
  },
54 55 56 57

  /**
   * Load authentication strategies
   */
58
  async activateStrategies () {
59 60
    try {
      // Unload any active strategies
61
      WIKI.auth.strategies = {}
62 63 64 65
      const currentStrategies = _.keys(passport._strategies)
      _.pull(currentStrategies, 'session')
      _.forEach(currentStrategies, stg => { passport.unuse(stg) })

66 67 68
      // Load JWT
      passport.use('jwt', new passportJWT.Strategy({
        jwtFromRequest: securityHelper.extractJWT,
69
        secretOrKey: WIKI.config.certs.public,
70
        audience: WIKI.config.auth.audience,
71 72
        issuer: 'urn:wiki.js',
        algorithms: ['RS256']
73 74 75 76
      }, (jwtPayload, cb) => {
        cb(null, jwtPayload)
      }))

77
      // Load enabled strategies
78
      const enabledStrategies = await WIKI.models.authentication.getStrategies()
79 80
      for (let idx in enabledStrategies) {
        const stg = enabledStrategies[idx]
81
        try {
82
          const strategy = require(`../modules/authentication/${stg.strategyKey}/authentication.js`)
83 84 85 86 87 88 89 90 91

          stg.config.callbackURL = `${WIKI.config.host}/login/${stg.key}/callback`
          strategy.init(passport, stg.config)
          strategy.config = stg.config

          WIKI.auth.strategies[stg.key] = {
            ...strategy,
            ...stg
          }
92
          WIKI.logger.info(`Authentication Strategy ${stg.displayName}: [ OK ]`)
93
        } catch (err) {
94
          WIKI.logger.error(`Authentication Strategy ${stg.displayName} (${stg.key}): [ FAILED ]`)
95
          WIKI.logger.error(err)
Nick's avatar
Nick committed
96
        }
97 98
      }
    } catch (err) {
99
      WIKI.logger.error(`Failed to initialize Authentication Strategies: [ ERROR ]`)
100 101
      WIKI.logger.error(err)
    }
102 103 104 105 106 107 108 109 110
  },

  /**
   * Authenticate current request
   *
   * @param {Express Request} req
   * @param {Express Response} res
   * @param {Express Next Callback} next
   */
111
  authenticate (req, res, next) {
112 113
    WIKI.auth.passport.authenticate('jwt', {session: false}, async (err, user, info) => {
      if (err) { return next() }
114
      let mustRevalidate = false
115 116

      // Expired but still valid within N days, just renew
NGPixel's avatar
NGPixel committed
117 118 119 120 121
      if (info instanceof Error && info.name === 'TokenExpiredError') {
        const expiredDate = (info.expiredAt instanceof Date) ? info.expiredAt.toISOString() : info.expiredAt
        if (DateTime.utc().minus(ms(WIKI.config.auth.tokenRenewal)) < DateTime.fromISO(expiredDate)) {
          mustRevalidate = true
        }
122 123
      }

NGPixel's avatar
NGPixel committed
124
      // Check if user / group is in revocation list
125
      if (user && !user.api && !mustRevalidate) {
NGPixel's avatar
NGPixel committed
126
        const uRevalidate = WIKI.auth.revocationList.get(`u${_.toString(user.id)}`)
127
        if (uRevalidate && user.iat < uRevalidate) {
128
          mustRevalidate = true
129 130 131 132
        } else if (DateTime.fromSeconds(user.iat) <= WIKI.startedAt) { // Prevent new / restarted instance from allowing revoked tokens
          mustRevalidate = true
        } else {
          for (const gid of user.groups) {
NGPixel's avatar
NGPixel committed
133
            const gRevalidate = WIKI.auth.revocationList.get(`g${_.toString(gid)}`)
134 135 136 137
            if (gRevalidate && user.iat < gRevalidate) {
              mustRevalidate = true
              break
            }
138 139 140 141 142 143
          }
        }
      }

      // Revalidate and renew token
      if (mustRevalidate) {
144 145 146 147
        const jwtPayload = jwt.decode(securityHelper.extractJWT(req))
        try {
          const newToken = await WIKI.models.users.refreshToken(jwtPayload.id)
          user = newToken.user
148
          user.permissions = user.getGlobalPermissions()
149
          user.groups = user.getGroups()
150
          req.user = user
151 152 153 154 155

          // Try headers, otherwise cookies for response
          if (req.get('content-type') === 'application/json') {
            res.set('new-jwt', newToken.token)
          } else {
156
            res.cookie('jwt', newToken.token, { expires: DateTime.utc().plus({ days: 365 }).toJSDate() })
157
          }
Nick's avatar
Nick committed
158 159
        } catch (errc) {
          WIKI.logger.warn(errc)
160 161 162 163 164 165
          return next()
        }
      }

      // JWT is NOT valid, set as guest
      if (!user) {
166
        if (WIKI.auth.guest.cacheExpiration <= DateTime.utc()) {
167
          WIKI.auth.guest = await WIKI.models.users.getGuestUser()
168
          WIKI.auth.guest.cacheExpiration = DateTime.utc().plus({ minutes: 1 })
169 170 171 172 173
        }
        req.user = WIKI.auth.guest
        return next()
      }

174 175
      // Process API tokens
      if (_.has(user, 'api')) {
176 177 178
        if (!WIKI.config.api.isEnabled) {
          return next(new Error('API is disabled. You must enable it from the Administration Area first.'))
        } else if (_.includes(WIKI.auth.validApiKeys, user.api)) {
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
          req.user = {
            id: 1,
            email: 'api@localhost',
            name: 'API',
            pictureUrl: null,
            timezone: 'America/New_York',
            localeCode: 'en',
            permissions: _.get(WIKI.auth.groups, `${user.grp}.permissions`, []),
            groups: [user.grp],
            getGlobalPermissions () {
              return req.user.permissions
            },
            getGroups () {
              return req.user.groups
            }
          }
          return next()
        } else {
          return next(new Error('API Key is invalid or was revoked.'))
        }
      }

201
      // JWT is valid
Nick's avatar
Nick committed
202 203
      req.logIn(user, { session: false }, (errc) => {
        if (errc) { return next(errc) }
204 205 206 207 208 209 210 211 212 213 214 215
        next()
      })
    })(req, res, next)
  },

  /**
   * Check if user has access to resource
   *
   * @param {User} user
   * @param {Array<String>} permissions
   * @param {String|Boolean} path
   */
216
  checkAccess(user, permissions = [], page = false) {
217 218
    const userPermissions = user.permissions ? user.permissions : user.getGlobalPermissions()

219
    // System Admin
220
    if (_.includes(userPermissions, 'manage:system')) {
221 222 223 224
      return true
    }

    // Check Global Permissions
225
    if (_.intersection(userPermissions, permissions).length < 1) {
226 227 228
      return false
    }

229 230 231 232 233
    // Skip if no page rule to check
    if (!page) {
      return true
    }

234
    // Check Page Rules
235
    if (user.groups) {
236 237 238 239 240 241 242 243
      let checkState = {
        deny: false,
        match: false,
        specificity: ''
      }
      user.groups.forEach(grp => {
        const grpId = _.isObject(grp) ? _.get(grp, 'id', 0) : grp
        _.get(WIKI.auth.groups, `${grpId}.pageRules`, []).forEach(rule => {
NGPixel's avatar
NGPixel committed
244
          if (_.intersection(rule.roles, permissions).length > 0) {
245 246 247 248
            switch (rule.match) {
              case 'START':
                if (_.startsWith(`/${page.path}`, `/${rule.path}`)) {
                  checkState = this._applyPageRuleSpecificity({ rule, checkState, higherPriority: ['END', 'REGEX', 'EXACT', 'TAG'] })
249
                }
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
                break
              case 'END':
                if (_.endsWith(page.path, rule.path)) {
                  checkState = this._applyPageRuleSpecificity({ rule, checkState, higherPriority: ['REGEX', 'EXACT', 'TAG'] })
                }
                break
              case 'REGEX':
                const reg = new RegExp(rule.path)
                if (reg.test(page.path)) {
                  checkState = this._applyPageRuleSpecificity({ rule, checkState, higherPriority: ['EXACT', 'TAG'] })
                }
                break
              case 'TAG':
                _.get(page, 'tags', []).forEach(tag => {
                  if (tag.tag === rule.path) {
                    checkState = this._applyPageRuleSpecificity({
                      rule,
                      checkState,
                      higherPriority: ['EXACT']
                    })
                  }
                })
                break
              case 'EXACT':
                if (`/${page.path}` === `/${rule.path}`) {
                  checkState = this._applyPageRuleSpecificity({ rule, checkState, higherPriority: [] })
                }
                break
            }
279 280 281 282 283 284 285
          }
        })
      })

      return (checkState.match && !checkState.deny)
    }

286
    return false
287 288
  },

289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
  /**
   * Check for exclusive permissions (contain any X permission(s) but not any Y permission(s))
   *
   * @param {User} user
   * @param {Array<String>} includePermissions
   * @param {Array<String>} excludePermissions
   */
  checkExclusiveAccess(user, includePermissions = [], excludePermissions = []) {
    const userPermissions = user.permissions ? user.permissions : user.getGlobalPermissions()

    // Check Inclusion Permissions
    if (_.intersection(userPermissions, includePermissions).length < 1) {
      return false
    }

    // Check Exclusion Permissions
    if (_.intersection(userPermissions, excludePermissions).length > 0) {
      return false
    }

    return true
  },

312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
  /**
   * Check and apply Page Rule specificity
   *
   * @access private
   */
  _applyPageRuleSpecificity ({ rule, checkState, higherPriority = [] }) {
    if (rule.path.length === checkState.specificity.length) {
      // Do not override higher priority rules
      if (_.includes(higherPriority, checkState.match)) {
        return checkState
      }
      // Do not override a previous DENY rule with same match
      if (rule.match === checkState.match && checkState.deny && !rule.deny) {
        return checkState
      }
    } else if (rule.path.length < checkState.specificity.length) {
      // Do not override higher specificity rules
      return checkState
    }

    return {
      deny: rule.deny,
      match: rule.match,
      specificity: rule.path
    }
  },

  /**
   * Reload Groups from DB
   */
342
  async reloadGroups () {
343 344
    const groupsArray = await WIKI.models.groups.query()
    this.groups = _.keyBy(groupsArray, 'id')
345
    WIKI.auth.guest.cacheExpiration = DateTime.utc().minus({ days: 1 })
346 347
  },

348 349 350 351
  /**
   * Reload valid API Keys from DB
   */
  async reloadApiKeys () {
352
    const keys = await WIKI.models.apiKeys.query().select('id').where('isRevoked', false).andWhere('expiration', '>', DateTime.utc().toISO())
353 354 355
    this.validApiKeys = _.map(keys, 'id')
  },

356 357 358
  /**
   * Generate New Authentication Public / Private Key Certificates
   */
359
  async regenerateCertificates () {
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
    WIKI.logger.info('Regenerating certificates...')

    _.set(WIKI.config, 'sessionSecret', (await crypto.randomBytesAsync(32)).toString('hex'))
    const certs = crypto.generateKeyPairSync('rsa', {
      modulusLength: 2048,
      publicKeyEncoding: {
        type: 'pkcs1',
        format: 'pem'
      },
      privateKeyEncoding: {
        type: 'pkcs1',
        format: 'pem',
        cipher: 'aes-256-cbc',
        passphrase: WIKI.config.sessionSecret
      }
    })

    _.set(WIKI.config, 'certs', {
      jwk: pem2jwk(certs.publicKey),
      public: certs.publicKey,
      private: certs.privateKey
    })

    await WIKI.configSvc.saveToDb([
      'certs',
      'sessionSecret'
    ])

    await WIKI.auth.activateStrategies()
389
    WIKI.events.outbound.emit('reloadAuthStrategies')
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421

    WIKI.logger.info('Regenerated certificates: [ COMPLETED ]')
  },

  /**
   * Reset Guest User
   */
  async resetGuestUser() {
    WIKI.logger.info('Resetting guest account...')
    const guestGroup = await WIKI.models.groups.query().where('id', 2).first()

    await WIKI.models.users.query().delete().where({
      providerKey: 'local',
      email: 'guest@example.com'
    }).orWhere('id', 2)

    const guestUser = await WIKI.models.users.query().insert({
      id: 2,
      provider: 'local',
      email: 'guest@example.com',
      name: 'Guest',
      password: '',
      locale: 'en',
      defaultEditor: 'markdown',
      tfaIsActive: false,
      isSystem: true,
      isActive: true,
      isVerified: true
    })
    await guestUser.$relatedQuery('groups').relate(guestGroup.id)

    WIKI.logger.info('Guest user has been reset: [ COMPLETED ]')
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
  },

  /**
   * Subscribe to HA propagation events
   */
  subscribeToEvents() {
    WIKI.events.inbound.on('reloadGroups', () => {
      WIKI.auth.reloadGroups()
    })
    WIKI.events.inbound.on('reloadApiKeys', () => {
      WIKI.auth.reloadApiKeys()
    })
    WIKI.events.inbound.on('reloadAuthStrategies', () => {
      WIKI.auth.activateStrategies()
    })
437 438 439
    WIKI.events.inbound.on('addAuthRevoke', (args) => {
      WIKI.auth.revokeUserTokens(args)
    })
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
  },

  /**
   * Get all user permissions for a specific page
   */
  getEffectivePermissions (req, page) {
    return {
      comments: {
        read: WIKI.config.features.featurePageComments ? WIKI.auth.checkAccess(req.user, ['read:comments'], page) : false,
        write: WIKI.config.features.featurePageComments ? WIKI.auth.checkAccess(req.user, ['write:comments'], page) : false,
        manage: WIKI.config.features.featurePageComments ? WIKI.auth.checkAccess(req.user, ['manage:comments'], page) : false
      },
      history: {
        read: WIKI.auth.checkAccess(req.user, ['read:history'], page)
      },
      source: {
        read: WIKI.auth.checkAccess(req.user, ['read:source'], page)
      },
      pages: {
        read: WIKI.auth.checkAccess(req.user, ['read:pages'], page),
        write: WIKI.auth.checkAccess(req.user, ['write:pages'], page),
        manage: WIKI.auth.checkAccess(req.user, ['manage:pages'], page),
        delete: WIKI.auth.checkAccess(req.user, ['delete:pages'], page),
        script: WIKI.auth.checkAccess(req.user, ['write:scripts'], page),
        style: WIKI.auth.checkAccess(req.user, ['write:styles'], page)
      },
      system: {
        manage: WIKI.auth.checkAccess(req.user, ['manage:system'], page)
      }
    }
470 471 472
  },

  /**
NGPixel's avatar
NGPixel committed
473
   * Add user / group ID to JWT revocation list, forcing all requests to be validated against the latest permissions
474 475
   */
  revokeUserTokens ({ id, kind = 'u' }) {
NGPixel's avatar
NGPixel committed
476
    WIKI.auth.revocationList.set(`${kind}${_.toString(id)}`, Math.round(DateTime.utc().minus({ seconds: 5 }).toSeconds()), Math.ceil(ms(WIKI.config.auth.tokenExpiration) / 1000))
NGPixel's avatar
NGPixel committed
477
  }
478
}