All files / uploads presigned-read-url.js

83.72% Statements 36/43
66.66% Branches 16/24
100% Functions 1/1
83.72% Lines 36/43

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 1731x 1x 1x 1x 1x   1x   1x 1x   1x 15x   15x 2x                       13x                       13x 13x 3x                   10x 9x 9x     9x 3x                     6x 6x                     6x         6x 6x     6x     6x             6x                       6x                       6x                                   6x           6x     5x                     2x 2x                    
const { S3Client, GetObjectCommand } = require('@aws-sdk/client-s3')
const { getSignedUrl } = require('@aws-sdk/s3-request-presigner')
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, GetCommand } = require('@aws-sdk/lib-dynamodb')
const { authenticateRequest, canAccessEntity } = require('../shared/auth-helper')
 
const s3Client = new S3Client({ region: 'eu-central-1' })
 
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
 
exports.handler = async (event) => {
  try {
    // Only allow POST requests
    if (event.httpMethod !== 'POST') {
      return {
        statusCode: 405,
        headers: {
          'Access-Control-Allow-Origin': '*',
          'Access-Control-Allow-Headers': 'Content-Type, Authorization, X-API-Key',
          'Access-Control-Allow-Methods': 'POST, OPTIONS'
        },
        body: JSON.stringify({ error: 'Method not allowed' })
      }
    }
 
    // Handle CORS preflight
    Iif (event.httpMethod === 'OPTIONS') {
      return {
        statusCode: 200,
        headers: {
          'Access-Control-Allow-Origin': '*',
          'Access-Control-Allow-Headers': 'Content-Type, Authorization, X-API-Key',
          'Access-Control-Allow-Methods': 'POST, OPTIONS'
        }
      }
    }
 
    // Authenticate request (JWT or API key)
    const auth = await authenticateRequest(event)
    if (!auth.authenticated) {
      return {
        statusCode: 401,
        headers: {
          'Access-Control-Allow-Origin': '*',
          'Access-Control-Allow-Headers': 'Content-Type'
        },
        body: JSON.stringify({ error: auth.error || 'Unauthorized' })
      }
    }
 
    const body = JSON.parse(event.body || '{}')
    const { key } = body
    console.log('Requested key:', key, 'auth type:', auth.type)
 
    // Validate required parameters
    if (!key) {
      return {
        statusCode: 400,
        headers: {
          'Access-Control-Allow-Origin': '*',
          'Access-Control-Allow-Headers': 'Content-Type'
        },
        body: JSON.stringify({ error: 'Missing required parameter: key' })
      }
    }
 
    // Extract entityId from key: {tenantId}/{entityId}/{itemId}/photos/{filename}
    const keyParts = key.split('/')
    Iif (keyParts.length < 2) {
      return {
        statusCode: 400,
        headers: {
          'Access-Control-Allow-Origin': '*',
          'Access-Control-Allow-Headers': 'Content-Type'
        },
        body: JSON.stringify({ error: 'Invalid key format' })
      }
    }
 
    const keyTenantId = keyParts[0]
    // Backward compat: old uploads (before entityId prop existed) used the
    // literal string 'entities' as keyParts[1] and the real entityId at [2].
    // New format: {tenantId}/{entityId}/{itemId}/{fieldName}/{file}
    // Old format: {tenantId}/entities/{entityId}/{fieldName}/{file}
    let entityId = keyParts[1]
    Iif (entityId === 'entities' && keyParts.length >= 5) {
      entityId = keyParts[2]
    }
    console.log('Key tenant:', keyTenantId, 'entityId:', entityId)
 
    // Get entity from DynamoDB
    const entityResult = await docClient.send(
      new GetCommand({
        TableName: process.env.ENTITIES_TABLE_NAME,
        Key: { id: entityId }
      })
    )
 
    Iif (!entityResult.Item) {
      return {
        statusCode: 404,
        headers: {
          'Access-Control-Allow-Origin': '*',
          'Access-Control-Allow-Headers': 'Content-Type'
        },
        body: JSON.stringify({ error: 'Entity not found' })
      }
    }
 
    // Check if auth has access to this entity
    Iif (!canAccessEntity(auth, entityResult.Item)) {
      return {
        statusCode: 403,
        headers: {
          'Access-Control-Allow-Origin': '*',
          'Access-Control-Allow-Headers': 'Content-Type'
        },
        body: JSON.stringify({ error: 'Access denied to this entity' })
      }
    }
 
    // Validate that the key tenant matches the entity tenant
    Iif (keyTenantId !== entityResult.Item.tenantId) {
      console.log(
        'Tenant mismatch: key tenant',
        keyTenantId,
        'entity tenant',
        entityResult.Item.tenantId
      )
      return {
        statusCode: 403,
        headers: {
          'Access-Control-Allow-Origin': '*',
          'Access-Control-Allow-Headers': 'Content-Type'
        },
        body: JSON.stringify({ error: 'Access denied: key does not belong to entity tenant' })
      }
    }
 
    // Create the GetObject command
    const command = new GetObjectCommand({
      Bucket: process.env.ATTACHMENTS_BUCKET_NAME,
      Key: key
    })
 
    // Generate presigned URL (expires in 1 hour for reading)
    const signedUrl = await getSignedUrl(s3Client, command, { expiresIn: 3600 })
 
    // Return the presigned URL
    return {
      statusCode: 200,
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Headers': 'Content-Type'
      },
      body: JSON.stringify({
        readUrl: signedUrl
      })
    }
  } catch (error) {
    console.error('Error generating read presigned URL:', error)
    return {
      statusCode: 500,
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Headers': 'Content-Type'
      },
      body: JSON.stringify({ error: 'Internal server error' })
    }
  }
}