All files / api-keys create.js

100% Statements 34/34
100% Branches 23/23
100% Functions 2/2
100% Lines 34/34

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                1x 1x 1x 1x   1x 1x   1x             7x 7x     1x 13x   13x 13x   13x 1x                     12x 12x     12x 2x                   10x 3x                     7x 7x 7x         7x   7x                             7x 2x 1x                 1x       6x                 5x                                           1x   1x                          
/**
 * Create API Key Lambda
 * POST /v1/admin/api-keys
 *
 * Creates a new API key with specified permissions
 * Requires JWT authentication with admin permissions
 */
 
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, PutCommand } = require('@aws-sdk/lib-dynamodb')
const crypto = require('crypto')
const { hashApiKey } = require('../shared/auth-helper')
 
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
 
const API_KEYS_TABLE = process.env.API_KEYS_TABLE
 
/**
 * Generate a secure API key
 * Format: apikey_{id}_{secret}
 */
function generateApiKey(id) {
  const secret = crypto.randomBytes(32).toString('hex')
  return `apikey_${id}_${secret}`
}
 
exports.handler = async (event) => {
  try {
    // Only JWT authentication allowed for admin operations
    const userId = event.requestContext?.authorizer?.claims?.sub
    const flowId = event.requestContext?.authorizer?.claims?.['custom:flowId']
 
    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, permissions, allowedEntityIds, 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 (!permissions || !Array.isArray(permissions) || permissions.length === 0) {
      return {
        statusCode: 400,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'At least one permission is required' })
      }
    }
 
    // Generate API key
    const keyId = crypto.randomUUID()
    const apiKey = generateApiKey(keyId)
    const keyHash = hashApiKey(apiKey)
 
    // Create API key record
    // allowedEntityIds: empty array or omitted = '*' (full access)
    const resolvedEntityIds =
      Array.isArray(allowedEntityIds) && allowedEntityIds.length > 0 ? allowedEntityIds : ['*']
 
    const apiKeyRecord = {
      id: keyId,
      keyHash,
      name,
      description: description || '',
      permissions,
      allowedEntityIds: resolvedEntityIds,
      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)'
      })
    )
 
    // 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,
          permissions,
          allowedEntityIds: apiKeyRecord.allowedEntityIds,
          expiresAt: apiKeyRecord.expiresAt || null,
          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)
 
    return {
      statusCode: 500,
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
      },
      body: JSON.stringify({
        error: 'Failed to create API key',
        message: error.message
      })
    }
  }
}