All files / api-keys create.js

100% Statements 60/60
93.93% Branches 31/33
100% Functions 4/4
100% Lines 59/59

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252                    1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x   1x 1x 1x 1x             12x 12x                 10x 4x 4x                               4x               4x   1x       1x 21x   21x 21x   21x 1x                     20x 20x     20x 2x                   18x 3x                   15x 1x                     14x 14x 1x                       13x 16x   13x 13x     12x 12x 12x     12x                           12x 2x 1x                 1x       11x               10x             10x                                             2x     2x 1x                   1x                          
/**
 * Create API Key Lambda
 * POST /v1/admin/api-keys
 *
 * Creates a new API key assigned to one or more roles
 * Requires JWT authentication with admin permissions
 *
 * @implements UC-APIKEY-005.1
 */
 
const { getActiveFlowId } = require('../shared/activeFlow')
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, PutCommand, GetCommand } = require('@aws-sdk/lib-dynamodb')
const crypto = require('crypto')
const { hashApiKey } = require('../shared/auth-helper')
const { permissionChecker } = require('../utils/PermissionChecker')
const { validateRolePermissions } = require('../utils/validateRolePermissions')
const { sendEmail, pickEmailLanguage } = require('../utils/email')
const { renderApiKeyCreatedEmail } = require('../utils/emailTemplates/apiKeyCreated')
 
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
 
const API_KEYS_TABLE = process.env.API_KEYS_TABLE
const USERS_TABLE_NAME = process.env.USERS_TABLE_NAME
const FLOWS_TABLE_NAME = process.env.FLOWS_TABLE_NAME
const APP_URL = process.env.APP_URL
 
/**
 * Generate a secure API key
 * Format: apikey_{id}_{secret}
 */
function generateApiKey(id) {
  const secret = crypto.randomBytes(32).toString('hex')
  return `apikey_${id}_${secret}`
}
 
/**
 * Tells the creator a key was created on their account, so a key created from
 * a hijacked session does not go unnoticed. Best-effort: the key exists either
 * way, so a failed email is logged and never fails the request.
 */
async function notifyCreator({ userId, email, apiKeyRecord }) {
  if (!email) return
  try {
    const [user, flow] = await Promise.all([
      docClient.send(
        new GetCommand({
          TableName: USERS_TABLE_NAME,
          Key: { id: userId },
          ProjectionExpression: 'languagePreferences'
        })
      ),
      docClient.send(
        new GetCommand({
          TableName: FLOWS_TABLE_NAME,
          Key: { id: apiKeyRecord.flowId },
          ProjectionExpression: 'slug'
        })
      )
    ])
    const { subject, html, text } = renderApiKeyCreatedEmail({
      lang: pickEmailLanguage(user.Item?.languagePreferences),
      keyName: apiKeyRecord.name,
      createdAt: apiKeyRecord.createdAt,
      expiresAt: apiKeyRecord.expiresAt,
      appUrl: APP_URL,
      flowSlug: flow.Item?.slug
    })
    await sendEmail({ to: email, subject, html, text })
  } catch (error) {
    console.error('Failed to send API key creation email:', error)
  }
}
 
exports.handler = async (event) => {
  try {
    // Only JWT authentication allowed for admin operations
    const userId = event.requestContext?.authorizer?.claims?.sub
    const flowId = await getActiveFlowId(event)
 
    if (!userId) {
      return {
        statusCode: 401,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'Authentication required' })
      }
    }
 
    // Parse request body
    const body = JSON.parse(event.body || '{}')
    const { name, roleIds, expiresAt, description } = body
 
    // Validation
    if (!name) {
      return {
        statusCode: 400,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'Name is required' })
      }
    }
 
    if (!roleIds || !Array.isArray(roleIds) || roleIds.length === 0) {
      return {
        statusCode: 400,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'At least one role is required' })
      }
    }
 
    if (!flowId) {
      return {
        statusCode: 400,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'Flow context required' })
      }
    }
 
    // Verify every requested role actually exists in this flow
    const roles = await permissionChecker.batchGetRoles(roleIds, flowId)
    if (roles.length !== new Set(roleIds).size) {
      return {
        statusCode: 400,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'One or more roles do not exist in this flow' })
      }
    }
 
    // Prevent privilege escalation: the creator must already hold every
    // permission granted by the roles they're assigning to the key
    const grantedPermissions = Array.from(
      new Set(roles.flatMap((role) => (Array.isArray(role.permissions) ? role.permissions : [])))
    )
    const creatorResult = await permissionChecker.getUserPermissions(userId, flowId)
    await validateRolePermissions(grantedPermissions, creatorResult.permissions || [])
 
    // Generate API key
    const keyId = crypto.randomUUID()
    const apiKey = generateApiKey(keyId)
    const keyHash = hashApiKey(apiKey)
 
    // Create API key record
    const apiKeyRecord = {
      id: keyId,
      keyHash,
      name,
      description: description || '',
      roleIds,
      flowId, // Associate with current flow
      status: 'active',
      createdBy: userId,
      createdAt: new Date().toISOString(),
      lastUsedAt: null
    }
 
    // Add expiration if provided
    if (expiresAt) {
      if (new Date(expiresAt) <= new Date()) {
        return {
          statusCode: 400,
          headers: {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
          },
          body: JSON.stringify({ error: 'Expiration date must be in the future' })
        }
      }
      apiKeyRecord.expiresAt = expiresAt
    }
 
    // Store in database
    await docClient.send(
      new PutCommand({
        TableName: API_KEYS_TABLE,
        Item: apiKeyRecord,
        ConditionExpression: 'attribute_not_exists(id)'
      })
    )
 
    await notifyCreator({
      userId,
      email: event.requestContext.authorizer.claims.email,
      apiKeyRecord
    })
 
    // Return response with the plain API key (only shown once!)
    return {
      statusCode: 201,
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
      },
      body: JSON.stringify({
        message: 'API key created successfully',
        apiKey: {
          id: keyId,
          name,
          roleIds,
          expiresAt: apiKeyRecord.expiresAt || null,
          status: apiKeyRecord.status,
          createdBy: apiKeyRecord.createdBy,
          createdAt: apiKeyRecord.createdAt
        },
        // ⚠️ IMPORTANT: This is the only time the key is shown
        key: apiKey,
        warning: 'Save this API key securely. It will not be shown again.'
      })
    }
  } catch (error) {
    console.error('Error creating API key:', error)
 
    // Privilege escalation guard rejection
    if (error.message && error.message.includes('permission to grant')) {
      return {
        statusCode: 403,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: error.message })
      }
    }
 
    return {
      statusCode: 500,
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
      },
      body: JSON.stringify({
        error: 'Failed to create API key',
        message: error.message
      })
    }
  }
}