All files / shared auth-helper.js

68.8% Statements 86/125
65.93% Branches 60/91
83.33% Functions 10/12
72.8% Lines 83/114

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 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368          28x 28x 28x 28x 28x   28x 28x       28x 28x 28x                                                       1x 1x   1x 1x                                                                               45x 45x 1x     28x                   703x   703x   703x           658x 658x                       45x 45x                               45x   45x   8x       37x     2x 2x                     23x 3x       20x       20x 20x 1x     19x   19x 19x             18x   18x 1x       17x 1x       16x 1x       15x 2x 2x 1x             14x 3x       11x 1x       11x           11x                       8x 7x   1x 1x                   53x               11x 11x                                                 433x   413x 411x       411x     20x 19x 19x   1x 1x       1x                         304x 50x     254x 253x     1x                                 72x 12x   60x     28x                  
/**
 * 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 { permissionChecker } = require('../utils/PermissionChecker')
const { resolveActiveFlow } = require('./activeFlow')
 
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 raw Cognito JWT string using JWKs signature verification.
 * Returns the decoded payload or null if invalid. Shared by
 * verifyJwtFromHeader (REST endpoints with authorizationType NONE) and the
 * WebSocket $connect handler (websocket/connect.js), which has no
 * Authorization header to read from — the browser WebSocket client can't
 * set custom headers, so the token instead rides the connect URL's query
 * string and is verified via this same core.
 */
async function verifyJwt(token) {
  try {
    Iif (!token) return null
 
    const parts = token.split('.')
    Eif (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
  }
}
 
/**
 * Verify a Cognito JWT from the Authorization header using JWKs signature verification.
 * Returns the decoded payload or null if invalid.
 */
async function verifyJwtFromHeader(event) {
  const authHeader = event.headers?.Authorization || event.headers?.authorization
  if (!authHeader?.startsWith('Bearer ')) return null
  return verifyJwt(authHeader.slice(7))
}
 
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', flowId, userId, permissions } or { error: string }
 */
async function authenticateRequest(event) {
  try {
    // 1. Check for JWT token (Cognito authorizer)
    const userId = event.requestContext?.authorizer?.claims?.sub
 
    if (userId) {
      // JWT authentication successful
      // Note: JWT users' permissions are checked via RBAC system (not here).
      // The active flow comes from X-Flow-Id, verified against the caller's
      // memberships (shared/activeFlow.js); null when absent or not an
      // active member — e.g. a user who has not created or joined a flow yet.
      const activeFlow = await resolveActiveFlow(event, userId)
      return {
        authenticated: true,
        type: 'jwt',
        flowId: activeFlow?.flowId || null,
        membership: activeFlow?.membership || null,
        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 jwtUserId = jwtPayload.sub
      if (jwtUserId) {
        const activeFlow = await resolveActiveFlow(event, jwtUserId)
        return {
          authenticated: true,
          type: 'jwt',
          flowId: activeFlow?.flowId || null,
          membership: activeFlow?.membership || null,
          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')
      }
    }
 
    // Keys are always created for one flow (api-keys/create.js requires it);
    // a record without one is not a valid key, and would authenticate with no
    // flow scope at all
    if (!keyRecord.flowId) {
      throw new Error('UNAUTHORIZED: API key is not bound to a flow')
    }
 
    // Update last used timestamp (fire and forget)
    updateLastUsed(keyId).catch((err) => {
      console.error('Failed to update lastUsedAt:', err)
    })
 
    // Resolve the key's roleIds into its effective permission set
    const permissions = await permissionChecker.getRolesPermissions(
      keyRecord.roleIds || [],
      keyRecord.flowId
    )
 
    // Return auth details
    return {
      authenticated: true,
      type: 'apikey',
      keyId: keyRecord.id,
      keyName: keyRecord.name,
      flowId: keyRecord.flowId,
      userId: null, // API keys have no userId of their own: permissions come from roleIds
      createdBy: keyRecord.createdBy || null, // the user the key acts for (billing, activity)
      permissions,
      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.
 * JWT users are checked against their roles via PermissionChecker (owner bypass included).
 * API-key users are checked against the permissions resolved from the key's roleIds
 * (see validateApiKey), with the same wildcard matching roles get, so both auth types
 * share one permission vocabulary.
 * @param {Object} auth - Auth object from authenticateRequest
 * @param {string} permission - Permission to check (e.g., 'entities-{id}:read')
 * @param {Object} [entity] - The entity `permission` is scoped to, when already loaded —
 *   spares PermissionChecker a read of its visibility (restricted entities)
 * @returns {Promise<boolean>}
 */
async function hasPermission(auth, permission, entity) {
  if (auth.type === 'jwt') {
    // No active flow means no membership, hence no role to grant anything
    if (!auth.flowId) return false
    const result = await permissionChecker.hasPermission(auth.userId, auth.flowId, permission, {
      entity,
      membership: auth.membership
    })
    return result.hasPermission
  }
 
  if (auth.type === 'apikey') {
    try {
      return await permissionChecker.permissionsGrant(auth.permissions || [], permission, entity)
    } catch (error) {
      console.error('Error checking API key permission:', error)
      return false
    }
  }
 
  return false
}
 
/**
 * Check if auth can access a specific entity.
 * Both JWT users and API keys can access entities in their own flow, plus any
 * public entity regardless of flow.
 * @param {Object} auth - Auth object from authenticateRequest
 * @param {Object} entity - Entity object with flowId and visibility properties
 * @returns {boolean}
 */
function canAccessEntity(auth, entity) {
  // Entity is public - anyone can access
  if (entity.visibility === 'public') {
    return true
  }
 
  if (auth.type === 'jwt' || auth.type === 'apikey') {
    return entity.flowId === auth.flowId
  }
 
  return false
}
 
/**
 * Check if auth holds a read-type permission (`entities-{id}:read`,
 * `:items:list`, `:items:read`) on an entity it can already access
 * (see canAccessEntity).
 * A signed-in user reading a public entity of another flow needs no RBAC
 * permission: they have no membership in the owning flow to check, and may
 * have no active flow at all (UC-ENTITY-010.1). Within their own flow, roles
 * apply as usual. API keys stay bound to their role-scoped permissions.
 * @param {Object} auth - Auth object from authenticateRequest
 * @param {Object} entity - Entity object with flowId and visibility properties
 * @param {string} permission - Permission to check otherwise
 * @returns {Promise<boolean>}
 */
async function hasEntityReadPermission(auth, entity, permission) {
  if (auth.type === 'jwt' && entity.visibility === 'public' && entity.flowId !== auth.flowId) {
    return true
  }
  return hasPermission(auth, permission, entity)
}
 
module.exports = {
  authenticateRequest,
  validateApiKey,
  hashApiKey,
  hasPermission,
  hasEntityReadPermission,
  canAccessEntity,
  verifyJwt
}