Unverified Commit f72cf664 authored by Nicolas Giard's avatar Nicolas Giard Committed by GitHub

feat: manage / create API keys (#1516)

* fix: admin api UI update * feat: admin api - create dialog UI * feat: admin api - create + list keys * feat: admin api localization (wip) * feat: admin api localization * feat: admin api - toggle state * feat: process API keys + format gql request errors to json
parent f6b048f1
......@@ -83,8 +83,8 @@
template(v-if='hasPermission([`manage:system`, `manage:api`])')
v-divider.my-2
v-subheader.pl-4 {{ $t('admin:nav.system') }}
v-list-item(to='/api', v-if='hasPermission([`manage:system`, `manage:api`])', disabled)
v-list-item-avatar(size='24', tile): v-icon(color='grey lighten-2') mdi-call-split
v-list-item(to='/api', v-if='hasPermission([`manage:system`, `manage:api`])')
v-list-item-avatar(size='24', tile): v-icon mdi-call-split
v-list-item-title {{ $t('admin:api.title') }}
v-list-item(to='/mail', color='primary', v-if='hasPermission(`manage:system`)')
v-list-item-avatar(size='24', tile): v-icon mdi-email-multiple-outline
......
<template lang="pug">
div
v-dialog(v-model='isShown', max-width='650', persistent)
v-card
.dialog-header.is-short
v-icon.mr-3(color='white') mdi-plus
span {{$t('admin:api.newKeyTitle')}}
v-card-text.pt-5
v-text-field(
outlined
prepend-icon='mdi-format-title'
v-model='name'
:label='$t(`admin:api.newKeyName`)'
persistent-hint
ref='keyNameInput'
:hint='$t(`admin:api.newKeyNameHint`)'
counter='255'
)
v-select.mt-3(
:items='expirations'
outlined
prepend-icon='mdi-clock'
v-model='expiration'
:label='$t(`admin:api.newKeyExpiration`)'
:hint='$t(`admin:api.newKeyExpirationHint`)'
persistent-hint
)
v-divider.mt-4
v-subheader.pl-2: strong.indigo--text {{$t('admin:api.newKeyPermissionScopes')}}
v-list.pl-8(nav)
v-list-item-group(v-model='fullAccess')
v-list-item(
:value='true'
active-class='indigo--text'
)
template(v-slot:default='{ active, toggle }')
v-list-item-action
v-checkbox(
:input-value='active'
:true-value='true'
color='indigo'
@click='toggle'
)
v-list-item-content
v-list-item-title {{$t('admin:api.newKeyFullAccess')}}
v-divider.mt-3
v-subheader.caption.indigo--text {{$t('admin:api.newKeyGroupPermissions')}}
v-list-item
v-select(
:disabled='fullAccess'
:items='groups'
item-text='name'
item-value='id'
outlined
color='indigo'
v-model='group'
:label='$t(`admin:api.newKeyGroup`)'
:hint='$t(`admin:api.newKeyGroupHint`)'
persistent-hint
)
v-card-chin
v-spacer
v-btn(text, @click='isShown = false', :disabled='loading') {{$t('common:actions.cancel')}}
v-btn.px-3(depressed, color='primary', @click='generate', :loading='loading')
v-icon(left) mdi-chevron-right
span {{$t('common:actions.generate')}}
v-dialog(
v-model='isCopyKeyDialogShown'
max-width='750'
persistent
overlay-color='blue darken-5'
overlay-opacity='.9'
)
v-card
v-toolbar(dense, flat, color='primary', dark) {{$t('admin:api.newKeyTitle')}}
v-card-text.pt-5
.body-2.text-center
i18next(tag='span', path='admin:api.newKeyCopyWarn')
strong(place='bold') {{$t('admin:api.newKeyCopyWarnBold')}}
v-textarea.mt-3(
ref='keyContentsIpt'
filled
no-resize
readonly
v-model='key'
:rows='10'
hide-details
)
v-card-chin
v-spacer
v-btn.px-3(depressed, dark, color='primary', @click='isCopyKeyDialogShown = false') {{$t('common:actions.close')}}
</template>
<script>
import _ from 'lodash'
import gql from 'graphql-tag'
import groupsQuery from 'gql/admin/users/users-query-groups.gql'
export default {
props: {
value: {
type: Boolean,
default: false
}
},
data() {
return {
loading: false,
name: '',
expiration: '1y',
fullAccess: true,
groups: [],
group: null,
isCopyKeyDialogShown: false,
key: ''
}
},
computed: {
isShown: {
get() { return this.value },
set(val) { this.$emit('input', val) }
},
expirations() {
return [
{ value: '30d', text: this.$t('admin:api.expiration30d') },
{ value: '90d', text: this.$t('admin:api.expiration90d') },
{ value: '180d', text: this.$t('admin:api.expiration180d') },
{ value: '1y', text: this.$t('admin:api.expiration1y') },
{ value: '3y', text: this.$t('admin:api.expiration3y') }
]
}
},
watch: {
value (newValue, oldValue) {
if (newValue) {
setTimeout(() => {
this.$refs.keyNameInput.focus()
}, 400)
}
}
},
methods: {
async generate () {
try {
if (_.trim(this.name).length < 2 || this.name.length > 255) {
throw new Error(this.$t('admin:api.newKeyNameError'))
} else if (!this.fullAccess && !this.group) {
throw new Error(this.$t('admin:api.newKeyGroupError'))
} else if (!this.fullAccess && this.group === 2) {
throw new Error(this.$t('admin:api.newKeyGuestGroupError'))
}
} catch (err) {
return this.$store.commit('showNotification', {
style: 'red',
message: err,
icon: 'alert'
})
}
this.loading = true
try {
const resp = await this.$apollo.mutate({
mutation: gql`
mutation ($name: String!, $expiration: String!, $fullAccess: Boolean!, $group: Int) {
authentication {
createApiKey (name: $name, expiration: $expiration, fullAccess: $fullAccess, group: $group) {
key
responseResult {
succeeded
errorCode
slug
message
}
}
}
}
`,
variables: {
name: this.name,
expiration: this.expiration,
fullAccess: (this.fullAccess === true),
group: this.group
},
watchLoading (isLoading) {
this.$store.commit(`loading${isLoading ? 'Start' : 'Stop'}`, 'admin-api-create')
}
})
if (_.get(resp, 'data.authentication.createApiKey.responseResult.succeeded', false)) {
this.$store.commit('showNotification', {
style: 'success',
message: this.$t('admin:api.newKeySuccess'),
icon: 'check'
})
this.name = ''
this.expiration = '1y'
this.fullAccess = true
this.group = null
this.isShown = false
this.$emit('refresh')
this.key = _.get(resp, 'data.authentication.createApiKey.key', '???')
this.isCopyKeyDialogShown = true
setTimeout(() => {
this.$refs.keyContentsIpt.$refs.input.select()
}, 400)
} else {
this.$store.commit('showNotification', {
style: 'red',
message: _.get(resp, 'data.authentication.createApiKey.responseResult.message', 'An unexpected error occured.'),
icon: 'alert'
})
}
} catch (err) {
this.$store.commit('pushGraphError', err)
}
this.loading = false
}
},
apollo: {
groups: {
query: groupsQuery,
fetchPolicy: 'network-only',
update: (data) => data.groups.list,
watchLoading (isLoading) {
this.$store.commit(`loading${isLoading ? 'Start' : 'Stop'}`, 'admin-api-groups-refresh')
}
}
}
}
</script>
......@@ -114,6 +114,7 @@
"moment": "2.24.0",
"moment-timezone": "0.5.27",
"mongodb": "3.5.2",
"ms": "2.1.2",
"mssql": "6.0.1",
"multer": "1.4.2",
"mysql2": "2.1.0",
......
......@@ -29,6 +29,8 @@ defaults:
maxFiles: 10
offline: false
# DB defaults
api:
isEnabled: false
graphEndpoint: 'https://graph.requarks.io'
lang:
code: en
......
......@@ -17,6 +17,7 @@ module.exports = {
cacheExpiration: moment.utc().subtract(1, 'd')
},
groups: {},
validApiKeys: [],
/**
* Initialize the authentication module
......@@ -44,6 +45,7 @@ module.exports = {
})
this.reloadGroups()
this.reloadApiKeys()
return this
},
......@@ -64,7 +66,8 @@ module.exports = {
jwtFromRequest: securityHelper.extractJWT,
secretOrKey: WIKI.config.certs.public,
audience: WIKI.config.auth.audience,
issuer: 'urn:wiki.js'
issuer: 'urn:wiki.js',
algorithms: ['RS256']
}, (jwtPayload, cb) => {
cb(null, jwtPayload)
}))
......@@ -135,6 +138,31 @@ module.exports = {
return next()
}
// Process API tokens
if (_.has(user, 'api')) {
if (_.includes(WIKI.auth.validApiKeys, user.api)) {
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.'))
}
}
// JWT is valid
req.logIn(user, { session: false }, (errc) => {
if (errc) { return next(errc) }
......@@ -248,15 +276,23 @@ module.exports = {
/**
* Reload Groups from DB
*/
async reloadGroups() {
async reloadGroups () {
const groupsArray = await WIKI.models.groups.query()
this.groups = _.keyBy(groupsArray, 'id')
},
/**
* Reload valid API Keys from DB
*/
async reloadApiKeys () {
const keys = await WIKI.models.apiKeys.query().select('id').where('isRevoked', false).andWhere('expiration', '>', moment.utc().toISOString())
this.validApiKeys = _.map(keys, 'id')
},
/**
* Generate New Authentication Public / Private Key Certificates
*/
async regenerateCertificates() {
async regenerateCertificates () {
WIKI.logger.info('Regenerating certificates...')
_.set(WIKI.config, 'sessionSecret', (await crypto.randomBytesAsync(32)).toString('hex'))
......
exports.up = knex => {
return knex.schema
.createTable('apiKeys', table => {
table.increments('id').primary()
table.string('name').notNullable()
table.text('key').notNullable()
table.string('expiration').notNullable()
table.boolean('isRevoked').notNullable().defaultTo(false)
table.string('createdAt').notNullable()
table.string('updatedAt').notNullable()
})
}
exports.down = knex => { }
/* global WIKI */
exports.up = knex => {
const dbCompat = {
charset: (WIKI.config.db.type === `mysql` || WIKI.config.db.type === `mariadb`)
}
return knex.schema
.createTable('apiKeys', table => {
if (dbCompat.charset) { table.charset('utf8mb4') }
table.increments('id').primary()
table.string('name').notNullable()
table.text('key').notNullable()
table.string('expiration').notNullable()
table.boolean('isRevoked').notNullable().defaultTo(false)
table.string('createdAt').notNullable()
table.string('updatedAt').notNullable()
})
}
exports.down = knex => { }
......@@ -14,6 +14,27 @@ module.exports = {
},
AuthenticationQuery: {
/**
* List of API Keys
*/
async apiKeys (obj, args, context) {
const keys = await WIKI.models.apiKeys.query().orderBy(['isRevoked', 'name'])
return keys.map(k => ({
id: k.id,
name: k.name,
keyShort: '...' + k.key.substring(k.key.length - 20),
isRevoked: k.isRevoked,
expiration: k.expiration,
createdAt: k.createdAt,
updatedAt: k.updatedAt
}))
},
/**
* Current API State
*/
apiState () {
return WIKI.config.api.isEnabled
},
/**
* Fetch active authentication strategies
*/
async strategies (obj, args, context, info) {
......@@ -42,6 +63,19 @@ module.exports = {
},
AuthenticationMutation: {
/**
* Create New API Key
*/
async createApiKey (obj, args, context) {
try {
return {
key: await WIKI.models.apiKeys.createNewKey(args),
responseResult: graphHelper.generateSuccess('API Key created successfully')
}
} catch (err) {
return graphHelper.generateError(err)
}
},
/**
* Perform Login
*/
async login (obj, args, context) {
......@@ -102,6 +136,36 @@ module.exports = {
}
},
/**
* Set API state
*/
async setApiState (obj, args, context) {
try {
WIKI.config.api.isEnabled = args.enabled
await WIKI.configSvc.saveToDb(['api'])
return {
responseResult: graphHelper.generateSuccess('API State changed successfully')
}
} catch (err) {
return graphHelper.generateError(err)
}
},
/**
* Revoke an API key
*/
async revokeApiKey (obj, args, context) {
try {
await WIKI.models.apiKeys.query().findById(args.id).patch({
isRevoked: true
})
await WIKI.auth.reloadApiKeys()
return {
responseResult: graphHelper.generateSuccess('API Key revoked successfully')
}
} catch (err) {
return graphHelper.generateError(err)
}
},
/**
* Update Authentication Strategies
*/
async updateStrategies (obj, args, context) {
......
......@@ -15,6 +15,10 @@ extend type Mutation {
# -----------------------------------------------
type AuthenticationQuery {
apiKeys: [AuthenticationApiKey] @auth(requires: ["manage:system", "manage:api"])
apiState: Boolean! @auth(requires: ["manage:system", "manage:api"])
strategies(
isEnabled: Boolean
): [AuthenticationStrategy]
......@@ -25,6 +29,13 @@ type AuthenticationQuery {
# -----------------------------------------------
type AuthenticationMutation {
createApiKey(
name: String!
expiration: String!
fullAccess: Boolean!
group: Int
): AuthenticationCreateApiKeyResponse @auth(requires: ["manage:system", "manage:api"])
login(
username: String!
password: String!
......@@ -47,12 +58,21 @@ type AuthenticationMutation {
name: String!
): AuthenticationRegisterResponse
revokeApiKey(
id: Int!
): DefaultResponse @auth(requires: ["manage:system", "manage:api"])
setApiState(
enabled: Boolean!
): DefaultResponse @auth(requires: ["manage:system", "manage:api"])
updateStrategies(
strategies: [AuthenticationStrategyInput]!
config: AuthenticationConfigInput
): DefaultResponse @auth(requires: ["manage:system"])
regenerateCertificates: DefaultResponse @auth(requires: ["manage:system"])
resetGuestUser: DefaultResponse @auth(requires: ["manage:system"])
}
......@@ -105,3 +125,18 @@ input AuthenticationConfigInput {
tokenExpiration: String!
tokenRenewal: String!
}
type AuthenticationApiKey {
id: Int!
name: String!
keyShort: String!
expiration: Date!
createdAt: Date!
updatedAt: Date!
isRevoked: Boolean!
}
type AuthenticationCreateApiKeyResponse {
responseResult: ResponseStatus
key: String
}
......@@ -167,12 +167,22 @@ module.exports = async () => {
})
app.use((err, req, res, next) => {
res.status(err.status || 500)
_.set(res.locals, 'pageMeta.title', 'Error')
res.render('error', {
message: err.message,
error: WIKI.IS_DEBUG ? err : {}
})
if (req.path === '/graphql') {
res.status(err.status || 500).json({
data: {},
errors: [{
message: err.message,
path: []
}]
})
} else {
res.status(err.status || 500)
_.set(res.locals, 'pageMeta.title', 'Error')
res.render('error', {
message: err.message,
error: WIKI.IS_DEBUG ? err : {}
})
}
})
// ----------------------------------------
......
/* global WIKI */
const Model = require('objection').Model
const moment = require('moment')
const ms = require('ms')
const jwt = require('jsonwebtoken')
/**
* Users model
*/
module.exports = class ApiKey extends Model {
static get tableName() { return 'apiKeys' }
static get jsonSchema () {
return {
type: 'object',
required: ['name', 'key'],
properties: {
id: {type: 'integer'},
name: {type: 'string'},
key: {type: 'string'},
expiration: {type: 'string'},
isRevoked: {type: 'boolean'},
createdAt: {type: 'string'},
validUntil: {type: 'string'}
}
}
}
async $beforeUpdate(opt, context) {
await super.$beforeUpdate(opt, context)
this.updatedAt = moment.utc().toISOString()
}
async $beforeInsert(context) {
await super.$beforeInsert(context)
this.createdAt = moment.utc().toISOString()
this.updatedAt = moment.utc().toISOString()
}
static async createNewKey ({ name, expiration, fullAccess, group }) {
const entry = await WIKI.models.apiKeys.query().insert({
name,
key: 'pending',
expiration: moment.utc().add(ms(expiration), 'ms').toISOString(),
isRevoked: true
})
const key = jwt.sign({
api: entry.id,
grp: fullAccess ? 1 : group
}, {
key: WIKI.config.certs.private,
passphrase: WIKI.config.sessionSecret
}, {
algorithm: 'RS256',
expiresIn: expiration,
audience: WIKI.config.auth.audience,
issuer: 'urn:wiki.js'
})
await WIKI.models.apiKeys.query().findById(entry.id).patch({
key,
isRevoked: false
})
return key
}
}
......@@ -26,7 +26,6 @@ module.exports = class User extends Model {
name: {type: 'string', minLength: 1, maxLength: 255},
providerId: {type: 'string'},
password: {type: 'string'},
role: {type: 'string', enum: ['admin', 'guest', 'user']},
tfaIsActive: {type: 'boolean', default: false},
tfaSecret: {type: 'string'},
jobTitle: {type: 'string'},
......
This diff was suppressed by a .gitattributes entry.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment