All files / entities get.js

94.28% Statements 33/35
84% Branches 21/25
100% Functions 1/1
94.28% Lines 33/35

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 1401x 1x 1x 1x           1x 1x   1x 1x   1x 16x   16x   16x                     16x   16x 1x                   15x 15x                   15x 1x 1x                                   14x             13x 1x                   12x         12x   12x 12x 2x                       10x 1x     9x                   1x 1x                    
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, GetCommand } = require('@aws-sdk/lib-dynamodb')
const { ENTITY_SCHEMA } = require('../utils/schemas/entity-schema')
const { withPackSources } = require('../utils/packSource')
const {
  authenticateRequest,
  hasPermission,
  hasEntityReadPermission,
  canAccessEntity
} = require('../shared/auth-helper')
const { isPlatformAdminUser } = require('../utils/platformAdmin')
 
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
 
exports.handler = async (event) => {
  try {
    // Authenticate (supports JWT and API keys)
    const auth = await authenticateRequest(event)
 
    Iif (!auth || auth.error) {
      return {
        statusCode: 401,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: auth?.error || 'Authentication required' })
      }
    }
 
    const id = event.pathParameters?.entityId
 
    if (!id) {
      return {
        statusCode: 400,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'Missing id' })
      }
    }
 
    const requiredPermission = `entities-${id}:read`
    const permissionDenied = {
      statusCode: 403,
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
      },
      body: JSON.stringify({ error: `Permission denied: ${requiredPermission} required` })
    }
 
    // Check if requesting system entity schema
    if (id === 'entity') {
      Eif (!(await hasPermission(auth, requiredPermission))) {
        return permissionDenied
      }
      return {
        statusCode: 200,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({
          ...ENTITY_SCHEMA,
          flowId: auth.flowId, // Associate with current flow context
          createdBy: 'SYSTEM',
          createdAt: '2026-01-01T00:00:00Z',
          updatedAt: '2026-01-01T00:00:00Z'
        })
      }
    }
 
    const result = await docClient.send(
      new GetCommand({
        TableName: process.env.TABLE_NAME,
        Key: { id }
      })
    )
 
    if (!result.Item) {
      return {
        statusCode: 404,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'Entity not found' })
      }
    }
 
    const entity = result.Item
 
    // Check entity access (public or owned by flow). A platform admin reads
    // any entity, a private one of another flow included, to act on a report
    // (UC-REPORT-004.1); that grants no access to its items.
    const accessible = canAccessEntity(auth, entity)
    const viaPlatformAdmin =
      !accessible && auth.type === 'jwt' && (await isPlatformAdminUser(docClient, auth.userId))
    if (!accessible && !viaPlatformAdmin) {
      return {
        statusCode: 403,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'Access denied' })
      }
    }
 
    // Checked once the entity is loaded: a public entity of another flow
    // needs no role, so a user without an active flow can read it too
    if (!viaPlatformAdmin && !(await hasEntityReadPermission(auth, entity, requiredPermission))) {
      return permissionDenied
    }
 
    return {
      statusCode: 200,
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
      },
      // A copy installed from a pack says which (UC-STORE-016.1)
      body: JSON.stringify((await withPackSources(docClient, [entity]))[0])
    }
  } catch (error) {
    console.error('Error:', error)
    return {
      statusCode: 500,
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
      },
      body: JSON.stringify({ error: 'Failed to fetch entity' })
    }
  }
}