All files / api-keys revoke.js

100% Statements 28/28
100% Branches 17/17
100% Functions 1/1
100% Lines 28/28

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                      1x           1x   1x 1x   1x   1x 13x   13x   13x 1x                     12x   12x 1x                     11x             10x 1x                     9x 1x                         8x       8x 2x             2x                           6x                                       4x                         3x 1x                   2x   2x                          
/**
 * Revoke/Delete API Key Lambda
 * DELETE /v1/admin/api-keys/{id}
 *
 * If the key is still active (and not expired), revokes it (sets status to 'revoked').
 * If the key is already revoked or expired, permanently deletes it — there is no
 * automatic cleanup (no DynamoDB TTL configured on ApiKeysTable), so this is the
 * only way for a user to get rid of an inactive key.
 * Requires JWT authentication and ownership verification
 */
 
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const {
  DynamoDBDocumentClient,
  GetCommand,
  UpdateCommand,
  DeleteCommand
} = require('@aws-sdk/lib-dynamodb')
 
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
 
const API_KEYS_TABLE = process.env.API_KEYS_TABLE
 
exports.handler = async (event) => {
  try {
    // Only JWT authentication allowed for admin operations
    const userId = event.requestContext?.authorizer?.claims?.sub
 
    if (!userId) {
      return {
        statusCode: 401,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'Authentication required' })
      }
    }
 
    // Get API key ID from path
    const keyId = event.pathParameters?.id
 
    if (!keyId) {
      return {
        statusCode: 400,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'API key ID is required' })
      }
    }
 
    // Get existing API key
    const getResult = await docClient.send(
      new GetCommand({
        TableName: API_KEYS_TABLE,
        Key: { id: keyId }
      })
    )
 
    if (!getResult.Item) {
      return {
        statusCode: 404,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'API key not found' })
      }
    }
 
    // Verify ownership
    if (getResult.Item.createdBy !== userId) {
      return {
        statusCode: 403,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'You do not have permission to revoke this API key' })
      }
    }
 
    // An already-revoked key, or an active key past its expiresAt, is inactive
    // and can never be used again — permanently delete it instead of soft-revoking again.
    const isExpired =
      getResult.Item.status === 'active' &&
      getResult.Item.expiresAt &&
      new Date(getResult.Item.expiresAt) < new Date()
 
    if (getResult.Item.status === 'revoked' || isExpired) {
      await docClient.send(
        new DeleteCommand({
          TableName: API_KEYS_TABLE,
          Key: { id: keyId }
        })
      )
 
      return {
        statusCode: 200,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({
          message: 'API key deleted permanently',
          id: keyId
        })
      }
    }
 
    // Revoke the API key
    await docClient.send(
      new UpdateCommand({
        TableName: API_KEYS_TABLE,
        Key: { id: keyId },
        UpdateExpression: 'SET #status = :status, revokedAt = :revokedAt, revokedBy = :revokedBy',
        // An UpdateItem upserts: without this, a key deleted since the read above
        // (e.g. its flow was just deleted) would come back as a stub row holding
        // only the revocation attributes.
        ConditionExpression: 'attribute_exists(id)',
        ExpressionAttributeNames: {
          '#status': 'status'
        },
        ExpressionAttributeValues: {
          ':status': 'revoked',
          ':revokedAt': new Date().toISOString(),
          ':revokedBy': userId
        }
      })
    )
 
    return {
      statusCode: 200,
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
      },
      body: JSON.stringify({
        message: 'API key revoked successfully',
        id: keyId
      })
    }
  } catch (error) {
    // The key was deleted between the read and the update (see the condition above).
    if (error.name === 'ConditionalCheckFailedException') {
      return {
        statusCode: 404,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'API key not found' })
      }
    }
 
    console.error('Error revoking API key:', error)
 
    return {
      statusCode: 500,
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
      },
      body: JSON.stringify({
        error: 'Failed to revoke API key',
        message: error.message
      })
    }
  }
}