All files / uploads presigned-read-url.js

97.48% Statements 155/159
96.22% Branches 153/159
100% Functions 9/9
98.7% Lines 152/154

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 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 6021x 1x 1x 1x 1x 1x   1x   1x 1x     60x 55x     5x 5x 2x     3x       20x   20x 20x 20x   20x 20x   20x 1x     20x 1x     20x 1x     20x 1x     20x 1x     20x             5x     5x       14x 14x           14x       4x 4x     4x                         7x         7x 6x 2x   4x 4x 4x 4x     3x             3x               7x   7x           4x   4x 3x                     4x 4x   4x                   1x 72x   72x 2x                       70x                       70x 70x 4x                   66x 65x 65x     65x 3x                   62x 62x 1x                           61x 2x 2x 1x                       1x       1x   1x                                                 59x 7x                         7x       7x   7x                           52x 3x 2x                 1x       1x                       49x 3x     46x 7x                         39x 12x 12x     4x     8x 8x                               27x 27x 27x 1x   27x 27x   39x     39x 4x       35x             35x           12x       1x       1x   1x                                 11x 11x   11x 9x 9x   9x 7x           7x           9x 6x 7x 2x 2x           11x 6x                     5x         5x   5x                         23x 2x                     21x       1x                               20x 20x 20x             20x 3x   15x     3x 3x   3x                           17x                   17x     16x                     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, hasPermission } = require('../shared/auth-helper')
const { draftPrefix } = require('../utils/membershipRequestFiles')
 
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()
}
 
// Reflects a client-supplied filename into a Content-Disposition header value —
// strips quotes/control characters/newlines so it can't break out of the
// quoted-string or inject additional response headers.
function sanitizeFileNameForHeader(fileName) {
  const cleaned = String(fileName || 'download')
    .replace(/["\r\n]/g, '')
    .trim()
  return cleaned || 'download'
}
 
async function isActiveFlowMember(userId, flowId) {
  Iif (!userId || !flowId || !process.env.FLOW_MEMBERSHIPS_TABLE_NAME) return false
  const result = await docClient.send(
    new GetCommand({
      TableName: process.env.FLOW_MEMBERSHIPS_TABLE_NAME,
      Key: { userId, flowId }
    })
  )
  return result?.Item?.status === 'active'
}
 
async function flowExists(flowId) {
  Iif (!flowId || !process.env.FLOWS_TABLE_NAME) return true // fail closed if misconfigured
  const result = await docClient.send(
    new GetCommand({ TableName: process.env.FLOWS_TABLE_NAME, Key: { id: flowId } })
  )
  return Boolean(result?.Item)
}
 
// Shared by both the current (flows/{flowId}/{fieldName}/{file}) and legacy
// ({flowId}/{flowId}/{flowId}/flow-picture|flow-icon/{file}) flow-branding key
// shapes — there's no entity to look up, so membership is the only gate.
/**
 * A membership request's file (UC-SPACE-020.1): a draft
 * (`membership-requests/drafts/{userId}/…`) only for its uploader; a sent one
 * (`membership-requests/{flowId}/{userId}/…`) for the requester and for a
 * member of that flow, as their active flow, holding `members:approve`.
 */
async function respondWithMembershipRequestReadUrl(auth, keyParts, key, download, fileName) {
  const denied = {
    statusCode: 403,
    headers: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': 'Content-Type' },
    body: JSON.stringify({ error: 'Access denied' })
  }
  if (auth.type !== 'jwt' || !auth.userId || keyParts.length !== 5) return denied
  if (keyParts[1] === 'drafts') {
    if (!key.startsWith(draftPrefix(auth.userId))) return denied
  } else {
    const [, flowId, requesterId] = keyParts
    const isRequester = requesterId === auth.userId
    const isApprover = auth.flowId === flowId && (await hasPermission(auth, 'members:approve'))
    if (!isRequester && !isApprover) return denied
  }
 
  const command = new GetObjectCommand({
    Bucket: process.env.ATTACHMENTS_BUCKET_NAME,
    Key: key,
    ...(download && {
      ResponseContentDisposition: `attachment; filename="${sanitizeFileNameForHeader(fileName)}"`
    })
  })
  return {
    statusCode: 200,
    headers: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': 'Content-Type' },
    body: JSON.stringify({ readUrl: await getSignedUrl(s3Client, command, { expiresIn: 3600 }) })
  }
}
 
async function respondWithFlowBrandingReadUrl(auth, flowId, key) {
  const isFlowMember = auth.type === 'jwt' && (await isActiveFlowMember(auth.userId, flowId))
 
  if (!isFlowMember) {
    // The flow may not exist yet: its picture/icon can be uploaded during
    // creation, before the flow record (and any membership) exists — the
    // frontend generates the flow's id up front (see UC-FLOW-008.1 AC-3).
    // Any authenticated user may preview it in that narrow pre-creation
    // window; once the flow exists, only active members can read it.
    const isPendingCreation = auth.type === 'jwt' && !(await flowExists(flowId))
 
    if (!isPendingCreation) {
      return {
        statusCode: 403,
        headers: {
          'Access-Control-Allow-Origin': '*',
          'Access-Control-Allow-Headers': 'Content-Type'
        },
        body: JSON.stringify({ error: 'Access denied: not a member of this flow' })
      }
    }
  }
 
  const command = new GetObjectCommand({ Bucket: process.env.ATTACHMENTS_BUCKET_NAME, Key: key })
  const signedUrl = await getSignedUrl(s3Client, command, { expiresIn: 3600 })
 
  return {
    statusCode: 200,
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Headers': 'Content-Type'
    },
    body: JSON.stringify({ readUrl: signedUrl })
  }
}
 
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, download, fileName } = 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' })
      }
    }
 
    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' })
      }
    }
 
    // Import-staging keys: imports/{userId}/{file} (uploads/presigned-url.js's
    // import-staging scope) — owner-only, no fellow-member fallback: these
    // are private scratch objects for the Import Preview screen's thumbnails,
    // not shared content like a profile picture.
    if (keyParts[0] === 'imports') {
      const keyUserId = keyParts[1]
      if (!auth.userId || auth.userId !== keyUserId) {
        return {
          statusCode: 403,
          headers: {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Headers': 'Content-Type'
          },
          body: JSON.stringify({
            error: 'Access denied: import-staging key belongs to a different user'
          })
        }
      }
 
      const importCommand = new GetObjectCommand({
        Bucket: process.env.ATTACHMENTS_BUCKET_NAME,
        Key: key
      })
      const importSignedUrl = await getSignedUrl(s3Client, importCommand, { expiresIn: 3600 })
 
      return {
        statusCode: 200,
        headers: {
          'Access-Control-Allow-Origin': '*',
          'Access-Control-Allow-Headers': 'Content-Type'
        },
        body: JSON.stringify({ readUrl: importSignedUrl })
      }
    }
 
    // User-owned keys: users/{userId}/{fieldName}/{file} (current) or
    // users/{userId}/{entityId}/{itemId}/{fieldName}/{file} (legacy
    // scope="user" uploads) — the owner id is always at position 1 regardless
    // of how many segments follow, so both shapes are handled identically.
    // Not tied to a flow: this namespace is used exclusively for profile
    // pictures, which are public information (same as nickname/name/status,
    // already exposed to anyone via GET /v1/users/{userId}) — any
    // authenticated (Cognito JWT) caller may read one. This used to be
    // scoped to "owner, or a fellow active member of the requester's own
    // flow" for the Members-page avatar use case only, but DM conversation
    // partners, followers/following, and public-profile viewers are not
    // necessarily flow members, so that check has been dropped rather than
    // grown into a union of every relationship that can legitimately see a
    // profile picture. API keys (used for cross-flow public entity access)
    // are still rejected — they aren't tied to an end user.
    if (keyParts[0] === 'users') {
      Iif (auth.type !== 'jwt') {
        return {
          statusCode: 403,
          headers: {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Headers': 'Content-Type'
          },
          body: JSON.stringify({
            error: 'Access denied: user-scoped key requires an authenticated user'
          })
        }
      }
 
      const userCommand = new GetObjectCommand({
        Bucket: process.env.ATTACHMENTS_BUCKET_NAME,
        Key: key
      })
      const userSignedUrl = await getSignedUrl(s3Client, userCommand, { expiresIn: 3600 })
 
      return {
        statusCode: 200,
        headers: {
          'Access-Control-Allow-Origin': '*',
          'Access-Control-Allow-Headers': 'Content-Type'
        },
        body: JSON.stringify({ readUrl: userSignedUrl })
      }
    }
 
    // Flow branding: flows/{flowId}/{fieldName}/{file} (current) — the flow's
    // own picture/icon, never tied to an entity.
    // A pack's picture is shown on its card to every signed-in user, like the
    // Store; nothing else under a pack is read through here (UC-STORE-014.1)
    if (keyParts[0] === 'packs') {
      if (auth.type !== 'jwt' || keyParts.length !== 4 || keyParts[2] !== 'pack-picture') {
        return {
          statusCode: 403,
          headers: {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Headers': 'Content-Type'
          },
          body: JSON.stringify({ error: 'Access denied' })
        }
      }
      const packCommand = new GetObjectCommand({
        Bucket: process.env.ATTACHMENTS_BUCKET_NAME,
        Key: key
      })
      return {
        statusCode: 200,
        headers: {
          'Access-Control-Allow-Origin': '*',
          'Access-Control-Allow-Headers': 'Content-Type'
        },
        body: JSON.stringify({
          readUrl: await getSignedUrl(s3Client, packCommand, { expiresIn: 3600 })
        })
      }
    }
 
    if (keyParts[0] === 'flows') {
      return await respondWithFlowBrandingReadUrl(auth, keyParts[1], key)
    }
 
    if (keyParts[0] === 'membership-requests') {
      return await respondWithMembershipRequestReadUrl(auth, keyParts, key, download, fileName)
    }
 
    // Entity/item image keys: entities/{entityId}/{itemId}/{fieldName}/{file}
    // No flowId segment — a public entity's ownership can transfer to another
    // flow (UC-FLOW-007.1 AC-4), and the object must stay reachable without
    // being moved. Access is authorized below purely from the entity's
    // *current* flowId, looked up fresh from DynamoDB, never from the key.
    let keyFlowId
    let entityId
    let keyItemId
    let keyFieldName
 
    if (keyParts[0] === 'entities') {
      entityId = keyParts[1]
      if (keyParts.length === 4) {
        // Entity's own picture/icon: entities/{entityId}/{fieldName}/{file}
        // — no itemId, since it isn't tied to any item.
        keyFieldName = keyParts[2]
      } else {
        // Item image field: entities/{entityId}/{itemId}/{fieldName}/{file}
        keyItemId = keyParts[2]
        keyFieldName = keyParts[3]
      }
    } else {
      // Legacy, flowId-prefixed keys minted before entity/item images, flow
      // branding, and profile pictures each moved to their current,
      // flowId-less scheme above. keyFlowId is kept only for the legacy
      // flow-branding branch below — it is deliberately never compared
      // against the entity's current flowId (see canAccessEntity below): that
      // comparison used to 403 every image on a transferred entity
      // (UC-FLOW-007.1 AC-4).
      //
      // Sub-formats:
      //   {flowId}/{entityId}/{itemId}/{fieldName}/{file}          (entity/item image)
      //   {flowId}/entities/{entityId}/{fieldName}/{file}          (pre-itemId entity image)
      //   {flowId}/{flowId}/{flowId}/flow-picture|flow-icon/{file} (flow branding)
      //   {flowId}/{userId}/{userId}/profile-picture/{file}        (profile picture)
      keyFlowId = keyParts[0]
      entityId = keyParts[1]
      if (entityId === 'entities' && keyParts.length >= 5) {
        entityId = keyParts[2]
      }
      keyItemId = keyParts[2]
      keyFieldName = keyParts[3]
    }
    console.log('Key flow:', keyFlowId, 'entityId:', entityId)
 
    // Legacy flow branding (current uploads use the flows/ branch above).
    if (keyFieldName === 'flow-picture' || keyFieldName === 'flow-icon') {
      return await respondWithFlowBrandingReadUrl(auth, keyFlowId, key)
    }
 
    // Get entity from DynamoDB
    const entityResult = await docClient.send(
      new GetCommand({
        TableName: process.env.ENTITIES_TABLE_NAME,
        Key: { id: entityId }
      })
    )
 
    if (!entityResult.Item) {
      // The entity's own picture/icon may be uploaded before the entity is
      // created — the frontend generates the entity's id up front (see
      // UC-ENTITY-001.1). Any authenticated user may preview it in that
      // narrow pre-creation window; once the entity exists, normal entity
      // access rules (canAccessEntity, below) apply instead.
      if (
        auth.type === 'jwt' &&
        (keyFieldName === 'entity-picture' || keyFieldName === 'entity-icon')
      ) {
        const pendingCommand = new GetObjectCommand({
          Bucket: process.env.ATTACHMENTS_BUCKET_NAME,
          Key: key
        })
        const pendingSignedUrl = await getSignedUrl(s3Client, pendingCommand, { expiresIn: 3600 })
 
        return {
          statusCode: 200,
          headers: {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Headers': 'Content-Type'
          },
          body: JSON.stringify({ readUrl: pendingSignedUrl })
        }
      }
 
      // Legacy profile picture (current uploads use the users/ branch above).
      // The owner id ends up in both candidate slots for a normal upload
      // ({flowId}/{userId}/{userId}/profile-picture/{file}), so both are
      // checked. Unlike the legacy flow-branding branch above, this
      // deliberately does NOT gate on keyFlowId === auth.flowId: what matters
      // is the requester's *current* active flow, not whatever flow happened
      // to be active when the picture was uploaded.
      let isOwnProfilePicture = false
      let isFellowMemberProfilePicture = false
 
      if (auth.type === 'jwt' && keyFieldName === 'profile-picture') {
        const ownerCandidates = [...new Set([entityId, keyItemId].filter(Boolean))]
        isOwnProfilePicture = Boolean(auth.userId) && ownerCandidates.includes(auth.userId)
 
        if (!isOwnProfilePicture && auth.userId && 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
        }
 
        // Not the requester's own picture — allow reading a teammate's
        // profile picture when its owner is an active member of the
        // requester's own active flow (needed to show avatars on member cards).
        if (!isOwnProfilePicture && auth.flowId) {
          for (const ownerUserId of ownerCandidates) {
            if (await isActiveFlowMember(ownerUserId, auth.flowId)) {
              isFellowMemberProfilePicture = true
              break
            }
          }
        }
      }
 
      if (!isOwnProfilePicture && !isFellowMemberProfilePicture) {
        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' })
      }
    }
 
    // A restricted entity's files are as hidden as the entity itself (UC-ENTITY-007.2 AC-5).
    if (
      entityResult.Item.visibility === 'restricted' &&
      !(await hasPermission(auth, `entities-${entityResult.Item.id}:read`, 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' })
      }
    }
 
    // No key-flow-vs-entity-flow check here by design: the entity's flowId
    // above is already the live source of truth used by canAccessEntity, and
    // a transferred public entity's images must stay readable even though
    // their key still carries the previous owner flow's id (UC-FLOW-007.1 AC-4).
 
    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 })
 
    // `download: true` (file/file_set fields) always forces a presigned S3 GET
    // with Content-Disposition: attachment, even for a public entity — the
    // CDN path below has no mechanism to set that header, and a generic
    // uploaded file (unlike an image) should never render inline in the
    // browser regardless of caching/transform benefits.
    if (isPublicEntity && cdnDomain && !download) {
      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 (and any download=true request) keep time-limited
    // presigned S3 URLs.
    const command = new GetObjectCommand({
      Bucket: process.env.ATTACHMENTS_BUCKET_NAME,
      Key: key,
      ...(download
        ? {
            ResponseContentDisposition: `attachment; filename="${sanitizeFileNameForHeader(fileName)}"`
          }
        : {})
    })
 
    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' })
    }
  }
}