All files / shared auth-helper.js

64.4% Statements 76/118
68.13% Branches 62/91
80% Functions 8/10
68.22% Lines 73/107

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 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316          6x 6x 6x   6x 6x       6x 6x 6x                                             12x 12x 12x                                                                             6x                   49x   49x 49x   49x     37x                     12x 12x                             12x   12x   3x       9x     1x 1x                     17x 3x       14x       14x 14x 1x     13x   13x 13x             12x   12x 1x       11x 1x       10x 1x       9x 2x 2x 1x         8x 1x       8x                       5x 4x   1x 1x                   35x               8x 8x                                     37x 29x     8x 7x     1x                     35x 5x       30x 24x       6x 5x   5x       5x   5x     3x     2x         1x     6x              
/**
 * Authentication Helper
 * Supports both JWT (Cognito) and API Key authentication
 */
 
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, GetCommand } = require('@aws-sdk/lib-dynamodb')
const crypto = require('crypto')
 
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
 
// --- JWT verification via Cognito JWKs (for NONE-authorizer endpoints) ---
 
let jwksCache = null
let jwksCacheTime = 0
const JWKS_CACHE_TTL = 3600 * 1000 // 1 hour
 
async function getCognitoJwks() {
  const now = Date.now()
  if (jwksCache && now - jwksCacheTime < JWKS_CACHE_TTL) {
    return jwksCache
  }
  const userPoolId = process.env.COGNITO_USER_POOL_ID
  if (!userPoolId) return null
  const region = process.env.AWS_REGION || 'eu-central-1'
  const url = `https://cognito-idp.${region}.amazonaws.com/${userPoolId}/.well-known/jwks.json`
  const response = await fetch(url)
  if (!response.ok) return null
  jwksCache = await response.json()
  jwksCacheTime = now
  return jwksCache
}
 
/**
 * Verify a Cognito JWT from the Authorization header using JWKs signature verification.
 * Returns the decoded payload or null if invalid.
 */
async function verifyJwtFromHeader(event) {
  try {
    const authHeader = event.headers?.Authorization || event.headers?.authorization
    Eif (!authHeader?.startsWith('Bearer ')) return null
 
    const token = authHeader.slice(7)
    const parts = token.split('.')
    if (parts.length !== 3) return null
 
    const [headerB64, payloadB64, signatureB64] = parts
 
    const header = JSON.parse(Buffer.from(headerB64, 'base64url').toString('utf8'))
    const payload = JSON.parse(Buffer.from(payloadB64, 'base64url').toString('utf8'))
 
    // Check token expiry
    if (payload.exp && payload.exp < Date.now() / 1000) return null
 
    // Get JWKs and find matching key by kid
    const jwks = await getCognitoJwks()
    if (!jwks?.keys) return null
    const jwk = jwks.keys.find((k) => k.kid === header.kid)
    if (!jwk) return null
 
    // Import JWK and verify signature using Node.js crypto.subtle (Node 18+)
    const key = await crypto.subtle.importKey(
      'jwk',
      jwk,
      { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' },
      false,
      ['verify']
    )
    const data = Buffer.from(`${headerB64}.${payloadB64}`)
    const signature = Buffer.from(signatureB64, 'base64url')
    const valid = await crypto.subtle.verify('RSASSA-PKCS1-v1_5', key, signature, data)
    if (!valid) return null
 
    return payload
  } catch {
    return null
  }
}
 
const API_KEYS_TABLE = process.env.API_KEYS_TABLE
 
/**
 * Validate and extract authentication details from event
 * Supports both Cognito JWT and API Keys
 *
 * @param {Object} event - Lambda event
 * @returns {Promise<Object>} { type: 'jwt'|'apikey', tenantId, userId, permissions } or { error: string }
 */
async function authenticateRequest(event) {
  try {
    // 1. Check for JWT token (Cognito authorizer)
    const tenantId = event.requestContext?.authorizer?.claims?.['custom:tenantId']
    const userId = event.requestContext?.authorizer?.claims?.sub
 
    if (tenantId && userId) {
      // JWT authentication successful
      // Note: JWT users' permissions are checked via RBAC system (not here)
      return {
        authenticated: true,
        type: 'jwt',
        tenantId,
        userId,
        source: 'cognito'
      }
    }
 
    // 1b. Fallback: verify JWT from Authorization header when no Cognito authorizer
    //     (endpoints with authorizationType: NONE that also support API key auth)
    const jwtPayload = await verifyJwtFromHeader(event)
    Iif (jwtPayload) {
      const jwtTenantId = jwtPayload['custom:tenantId']
      const jwtUserId = jwtPayload.sub
      if (jwtTenantId && jwtUserId) {
        return {
          authenticated: true,
          type: 'jwt',
          tenantId: jwtTenantId,
          userId: jwtUserId,
          source: 'cognito'
        }
      }
    }
 
    // 2. Check for API Key in headers
    const apiKey = event.headers?.['x-api-key'] || event.headers?.['X-API-Key']
 
    if (apiKey) {
      // Validate API key
      return await validateApiKey(apiKey)
    }
 
    // 3. No authentication provided
    return { error: 'No valid authentication provided' }
  } catch (error) {
    // Convert thrown errors to error response
    const errorMessage = error.message?.replace('UNAUTHORIZED: ', '') || 'Authentication failed'
    return { error: errorMessage }
  }
}
 
/**
 * Validate API key and return auth details
 * @param {string} apiKey - API key from request
 * @returns {Promise<Object>} Auth details
 * @throws {Error} If API key is invalid
 */
async function validateApiKey(apiKey) {
  if (!apiKey || !apiKey.startsWith('apikey_')) {
    throw new Error('UNAUTHORIZED: Invalid API key format')
  }
 
  // Hash the API key (we store hashes in DB for security)
  const keyHash = hashApiKey(apiKey)
 
  // Look up API key in database (we can't query by hash, so we need a pattern)
  // For now, extract the ID from the key format: apikey_{id}_{secret}
  const parts = apiKey.split('_')
  if (parts.length < 3) {
    throw new Error('UNAUTHORIZED: Invalid API key format')
  }
 
  const keyId = parts[1]
 
  try {
    const result = await docClient.send(
      new GetCommand({
        TableName: API_KEYS_TABLE,
        Key: { id: keyId }
      })
    )
 
    const keyRecord = result.Item
 
    if (!keyRecord) {
      throw new Error('UNAUTHORIZED: API key not found')
    }
 
    // Verify key hash matches
    if (keyRecord.keyHash !== keyHash) {
      throw new Error('UNAUTHORIZED: Invalid API key')
    }
 
    // Check if key is active
    if (keyRecord.status !== 'active') {
      throw new Error('UNAUTHORIZED: API key is revoked or inactive')
    }
 
    // Check expiration
    if (keyRecord.expiresAt) {
      const expiresAt = new Date(keyRecord.expiresAt)
      if (expiresAt < new Date()) {
        throw new Error('UNAUTHORIZED: API key has expired')
      }
    }
 
    // Update last used timestamp (fire and forget)
    updateLastUsed(keyId).catch((err) => {
      console.error('Failed to update lastUsedAt:', err)
    })
 
    // Return auth details
    return {
      authenticated: true,
      type: 'apikey',
      keyId: keyRecord.id,
      keyName: keyRecord.name,
      tenantId: keyRecord.tenantId || null, // API keys can be tenant-specific or global
      userId: null, // API keys are not user-specific
      permissions: keyRecord.permissions || [],
      allowedEntityIds: keyRecord.allowedEntityIds || [],
      source: 'apikey'
    }
  } catch (error) {
    if (error.message.startsWith('UNAUTHORIZED:')) {
      throw error
    }
    console.error('Error validating API key:', error)
    throw new Error('UNAUTHORIZED: Failed to validate API key')
  }
}
 
/**
 * Hash an API key for storage/comparison
 * @param {string} apiKey - Plain text API key
 * @returns {string} SHA-256 hash
 */
function hashApiKey(apiKey) {
  return crypto.createHash('sha256').update(apiKey).digest('hex')
}
 
/**
 * Update lastUsedAt timestamp for an API key
 * @param {string} keyId - API key ID
 */
async function updateLastUsed(keyId) {
  const { UpdateCommand } = require('@aws-sdk/lib-dynamodb')
  await docClient.send(
    new UpdateCommand({
      TableName: API_KEYS_TABLE,
      Key: { id: keyId },
      UpdateExpression: 'SET lastUsedAt = :now',
      ExpressionAttributeValues: {
        ':now': new Date().toISOString()
      }
    })
  )
}
 
/**
 * Check if auth has a specific permission
 * @param {Object} auth - Auth object from authenticateRequest
 * @param {string} permission - Permission to check (e.g., 'entities:read')
 * @returns {boolean}
 */
function hasPermission(auth, permission) {
  if (auth.type === 'jwt') {
    return true // JWT users have all permissions
  }
 
  if (auth.type === 'apikey') {
    return auth.permissions.includes('*') || auth.permissions.includes(permission)
  }
 
  return false
}
 
/**
 * Check if auth can access a specific entity
 * @param {Object} auth - Auth object from authenticateRequest
 * @param {Object} entity - Entity object with tenantId and isPublic properties
 * @returns {boolean}
 */
function canAccessEntity(auth, entity) {
  // Entity is public - anyone can access (handle both string 'true' and boolean true)
  if (entity.isPublic === 'true' || entity.isPublic === true) {
    return true
  }
 
  // JWT users can access entities in their own tenant
  if (auth.type === 'jwt') {
    return entity.tenantId === auth.tenantId
  }
 
  // API key users: check allowedEntityIds and tenant access
  if (auth.type === 'apikey') {
    const allowed = auth.allowedEntityIds || []
 
    console.error(
      `[canAccessEntity] apikey=${auth.keyId} allowed=${JSON.stringify(allowed)} entity.id=${entity.id} entity.tenantId=${entity.tenantId} entity.isPublic=${entity.isPublic}`
    )
 
    const entityAllowed = allowed.includes('*') || allowed.includes(entity.id)
 
    if (!entityAllowed) return false
 
    // Wildcard: admin explicitly granted full access, skip tenant check
    if (allowed.includes('*')) return true
 
    // Explicit entity ID: also verify same tenant or public
    return (
      entity.tenantId === auth.tenantId || entity.isPublic === 'true' || entity.isPublic === true
    )
  }
 
  return false
}
 
module.exports = {
  authenticateRequest,
  validateApiKey,
  hashApiKey,
  hasPermission,
  canAccessEntity
}