All files / uploads presigned-read-url.js

98.82% Statements 84/85
97.33% Branches 73/75
100% Functions 4/4
98.82% Lines 84/85

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 2851x 1x 1x 1x 1x   1x   1x 1x     24x 19x     5x 5x 2x     3x       8x   8x 8x 8x   8x 8x   8x 1x     8x 1x     8x 1x     8x 1x     8x 1x     8x     1x 26x   26x 2x                       24x                       24x 24x 3x                   21x 20x 20x     20x 3x                     17x 17x 1x                   16x         16x 16x 1x   16x 16x 16x     16x             16x   6x         6x             3x             3x     6x 3x                     3x         3x   3x                         10x 1x                     9x 1x 1x                     8x 8x 8x   8x 2x   10x     2x 2x   2x                         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)
 
function parsePositiveInt(value) {
  if (value === undefined || value === null || value === '') {
    return null
  }
 
  const parsed = Number.parseInt(String(value), 10)
  if (Number.isNaN(parsed) || parsed <= 0) {
    return null
  }
 
  return parsed
}
 
function buildTransformQuery(params) {
  const query = new URLSearchParams()
 
  const width = parsePositiveInt(params.width || params.w)
  const height = parsePositiveInt(params.height || params.h)
  const quality = parsePositiveInt(params.quality || params.q)
 
  const fit = typeof params.fit === 'string' ? params.fit.trim().toLowerCase() : ''
  const format = typeof params.format === 'string' ? params.format.trim().toLowerCase() : ''
 
  if (width) {
    query.set('w', String(Math.min(width, 4096)))
  }
 
  if (height) {
    query.set('h', String(Math.min(height, 4096)))
  }
 
  if (quality) {
    query.set('q', String(Math.min(Math.max(quality, 30), 95)))
  }
 
  if (['cover', 'contain', 'fill', 'inside', 'outside'].includes(fit)) {
    query.set('fit', fit)
  }
 
  if (['auto', 'jpeg', 'jpg', 'png', 'webp', 'avif'].includes(format)) {
    query.set('format', format)
  }
 
  return query.toString()
}
 
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, width, height, w, h, quality, q, fit, format } = 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: {flowId}/{entityId}/{itemId}/photos/{filename}
    const keyParts = key.split('/')
    if (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 keyFlowId = 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: {flowId}/{entityId}/{itemId}/{fieldName}/{file}
    // Old format: {flowId}/entities/{entityId}/{fieldName}/{file}
    let entityId = keyParts[1]
    if (entityId === 'entities' && keyParts.length >= 5) {
      entityId = keyParts[2]
    }
    const keyItemId = keyParts[2]
    const keyFieldName = keyParts[3]
    console.log('Key flow:', keyFlowId, 'entityId:', entityId)
 
    // Get entity from DynamoDB
    const entityResult = await docClient.send(
      new GetCommand({
        TableName: process.env.ENTITIES_TABLE_NAME,
        Key: { id: entityId }
      })
    )
 
    if (!entityResult.Item) {
      let isOwnProfilePicture =
        auth.type === 'jwt' &&
        keyFieldName === 'profile-picture' &&
        keyFlowId === auth.flowId &&
        (keyItemId === auth.userId || entityId === auth.userId)
 
      if (
        !isOwnProfilePicture &&
        auth.type === 'jwt' &&
        keyFieldName === 'profile-picture' &&
        keyFlowId === auth.flowId &&
        process.env.USERS_TABLE_NAME
      ) {
        const userResult = await docClient.send(
          new GetCommand({
            TableName: process.env.USERS_TABLE_NAME,
            Key: { id: auth.userId }
          })
        )
 
        isOwnProfilePicture = userResult.Item?.profilePicture === key
      }
 
      if (!isOwnProfilePicture) {
        return {
          statusCode: 404,
          headers: {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Headers': 'Content-Type'
          },
          body: JSON.stringify({ error: 'Entity not found' })
        }
      }
 
      // User profile pictures are not tied to an entity; authorize only own key.
      const profileCommand = new GetObjectCommand({
        Bucket: process.env.ATTACHMENTS_BUCKET_NAME,
        Key: key
      })
 
      const profileSignedUrl = await getSignedUrl(s3Client, profileCommand, { expiresIn: 3600 })
 
      return {
        statusCode: 200,
        headers: {
          'Access-Control-Allow-Origin': '*',
          'Access-Control-Allow-Headers': 'Content-Type'
        },
        body: JSON.stringify({
          readUrl: profileSignedUrl
        })
      }
    }
 
    // Check if auth has access to this entity
    if (!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 flow matches the entity flow
    if (keyFlowId !== entityResult.Item.flowId) {
      console.log('Flow mismatch: key flow', keyFlowId, 'entity flow', entityResult.Item.flowId)
      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 flow' })
      }
    }
 
    const isPublicEntity =
      entityResult.Item.visibility === 'public' || entityResult.Item.isPublic === 'true'
    const cdnDomain = process.env.ATTACHMENTS_CDN_DOMAIN
    const transformQuery = buildTransformQuery({ width, height, w, h, quality, q, fit, format })
 
    if (isPublicEntity && cdnDomain) {
      const encodedKey = key
        .split('/')
        .map((segment) => encodeURIComponent(segment))
        .join('/')
 
      const baseUrl = `https://${cdnDomain}/${encodedKey}`
      const readUrl = transformQuery ? `${baseUrl}?${transformQuery}` : baseUrl
 
      return {
        statusCode: 200,
        headers: {
          'Access-Control-Allow-Origin': '*',
          'Access-Control-Allow-Headers': 'Content-Type'
        },
        body: JSON.stringify({
          readUrl
        })
      }
    }
 
    // Private entities keep time-limited presigned S3 URLs.
    const command = new GetObjectCommand({
      Bucket: process.env.ATTACHMENTS_BUCKET_NAME,
      Key: key
    })
 
    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' })
    }
  }
}