Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
const apmSpan = apm.startSpan('Get access info for API key')
accessInfo = await computeAccessInfo({
roles: apiKey.roles,
permissions: apiKey.permissions,
readNamespaces: apiKey.readNamespaces,
editNamespaces: apiKey.editNamespaces,
...computeAccessParams
})
apmSpan && apmSpan.end()
} else if (token && typeof token === 'object') {
sources.push('token')
const apmSpan = apm.startSpan('Get access info for token')
// the header x-stelace-organization-id is only useful for authentication by token
organizationId = req.headers['x-stelace-organization-id']
const tokenPermissions = token.permissions || []
let scopePermissions = []
if (token.scope && typeof token.scope === 'string') {
scopePermissions = token.scope.split(' ')
}
// routes/services can override the `organizationId` (like in user.joinOrganizationOrUpdateRights)
if (typeof getOrganizationIdFn === 'function') {
organizationId = getOrganizationIdFn(req)
}
async applyChanges ({ target, fromVersion, toVersion, params = {} }) {
const apmSpan = apm.startSpan(`${this.label} version transformation`)
let transformedParams = params
// apply the change for ANY version and ANY target
// and before all other changes
const beforeAllChange = this.getChange({ version: 'always', target: 'beforeAll' })
if (_.isPlainObject(beforeAllChange)) {
transformedParams = await beforeAllChange[this.direction](transformedParams)
}
const index = this.apiVersions.indexOf(fromVersion)
const foundVersion = index !== -1
if (foundVersion) {
for (let i = index; i < this.apiVersions.length; i++) {
const version = this.apiVersions[i]
async send (...args) {
const sendParams = args[0] || {}
const name = `Requester send: ${this.advertisement.name} | type: ${sendParams.type}`
const apmSpan = apm.startSpan(name)
// used to link to the source APM transaction across network (see custom responder)
if (apm.currentTransaction) {
sendParams._apmTraceparent = apm.currentTransaction.traceparent
}
try {
const result = await super.send(...args)
return result
} finally {
if (isApmActive && !apmSpan) {
if (!apm.currentTransaction) {
logError(new Error(`No APM transaction available in requester "${name}"`))
} else {
logError(new Error(`Empty apm span in requester "${name}"`))
}
const middleware = async (req, res, next) => {
const apmSpan = apm.startSpan('Check permissions')
const permissionsToCheck = permissions.slice(0)
// Always check, in case platformData is edited via current endpoint
if (!permissionsToCheck.includes('platformData:edit:all')) {
permissionsToCheck.push('platformData:edit:all')
}
optionalPermissions.forEach(p => permissionsToCheck.push(p))
try {
const token = req[requestProperty]
const rawApiKey = _.get(req.authorization, 'apiKey') ||
req.headers['x-api-key'] // legacy x-api-key, convenient during development
const stelaceWorkflowKey = req.headers['x-stelace-workflow-key']
const targetUserId = req.headers['x-stelace-user-id']
server.use((req, res, next) => {
req.apmSpans.restifyPlugin && req.apmSpans.restifyPlugins.end()
req.apmSpans.restifyPlugins = null
req.apmSpans.requestInit = apm.startSpan('Request initialization')
req._requestId = Uuid.v4()
req._ip = getIp(req)
// set this header for CORS
res.header('access-control-allow-credentials', true)
next()
})
server.use(async (req, res, next) => {
const apmSpan = apm.startSpan('Parse Authorization and get platform info')
try {
parseAuthorizationHeader(req)
} catch (err) { // still trying to parse authorization header for convenience when not required
if (!req._manualAuthRoute) {
apmSpan && apmSpan.end()
return next(err)
}
}
try {
const setPlanAndVersion = async ({ errParams } = {}) => {
try {
const info = await getPlatformEnvData(req.platformId, req.env, [
'plan', // can be set by some plugin
'version'
private apmStartSpan(name: string): any {
if (process.env.ELASTIC_APM_ENABLED) {
return require('elastic-apm-node').startSpan('ApiCache.' + name, 'cache');
}
}
async function checkAuthToken ({
authToken,
platformId,
env,
apmLabel = 'Authentication token'
}) {
const apmSpan = apm.startSpan(apmLabel)
let decodedToken
let isStelaceAuthToken
try {
const secret = await authenticationRequester.send({
type: '_getAuthSecret',
platformId,
env
})
const options = { algorithms: ['HS256'] }
isStelaceAuthToken = true
try {
jwt.decode(authToken, { complete: true })