All files / uploads presigned-url.js

98.18% Statements 108/110
96.42% Branches 81/84
100% Functions 11/11
99.05% Lines 105/106

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                    1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x   1x           39x                                                                               49x 3x 2x   1x           46x 46x 46x 46x 46x   46x                 4x 4x 1x       3x           42x 8x 8x 3x       5x           34x 2x 1x   1x           32x 3x 1x   2x           29x 3x 1x   2x           26x 4x   22x                                             35x 170x           35x               33x                             2x 2x                   11x 11x   10x 10x 9x 9x 22x   9x 9x 5x     4x 4x 2x           2x                                 36x 1x                 35x         35x 2x             33x       46x   46x 3x     43x                     43x   30x       11x   11x 5x     6x                   6x   6x     1x 76x           76x 2x             74x             74x 73x   73x 5x     68x 68x 68x   68x 11x     57x 11x   46x   3x 3x      
/**
 * POST /v1/upload/presigned-url
 *
 * Balance preflight against the declared file size before issuing the
 * presigned POST — the actual s3_storage debit happens later, in
 * uploads/s3-usage-consumer.js, once the object really lands in S3.
 *
 * @implements UC-CREDITS-003.1, UC-CREDITS-004.1, UC-SPACE-020.1
 */
 
const { S3Client } = require('@aws-sdk/client-s3')
const { createPresignedPost } = require('@aws-sdk/s3-presigned-post')
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient } = require('@aws-sdk/lib-dynamodb')
const { randomUUID } = require('crypto')
const { MAX_FILE_SIZE_BYTES, isAllowedFileUpload } = require('../utils/fileUploadPolicy')
const { getCreditsBalance } = require('../utils/creditsLedger')
const { isValidUuid } = require('../utils/isValidUuid')
const { loadJoinableFlow, joinFormFields } = require('../utils/spaceJoin')
const { uploadKindOf, draftPrefix } = require('../utils/membershipRequestFiles')
 
const s3Client = new S3Client({ region: 'eu-central-1' })
const docClient = DynamoDBDocumentClient.from(new DynamoDBClient({}))
 
const CORS_HEADERS = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Headers': 'Content-Type'
}
 
function errorResponse(statusCode, error) {
  return { statusCode, headers: CORS_HEADERS, body: JSON.stringify({ error }) }
}
 
/**
 * Resolves the S3 key and object metadata for an upload, shared by both the
 * image and file (both presigned POST) upload paths so every upload kind is
 * namespaced identically. Returns `{ error }` (a Lambda
 * response object) instead of throwing, so callers can `return` it directly.
 *
 *   entities/{entityId}/{fieldName}/{file}           — entity's own picture/icon
 *   entities/{entityId}/{itemId}/{fieldName}/{file}  — item image/file field
 *   flows/{flowId}/{fieldName}/{file}                — flow picture/icon
 *   flows/{flowId}/space-pages/{file}                — an image of the space pages
 *                                                       (UC-SPACE-009.1; the page save
 *                                                       only accepts keys there)
 *   users/{userId}/{fieldName}/{file}                — profile picture (and any
 *                                                       other future account-level upload)
 *   imports/{userId}/{file}                          — import-preview staging
 *   packs/{packId}/pack-picture/{file}               — a pack's picture, on its card
 *                                                       (UC-STORE-014.1; attached by
 *                                                       store/publish.js or update.js,
 *                                                       which check the rights)
 *
 * A public entity's ownership can transfer to another flow (UC-FLOW-007.1
 * AC-4), so entity/item keys never carry a flowId — the S3 object must stay
 * reachable without being moved. Flows and users are never reassigned, so
 * their own key doesn't need to be transfer-safe, but there's no reason to
 * duplicate their id three times either.
 */
function resolveKeyAndMetadata({
  event,
  fileName,
  uniqueFileName,
  flowId,
  entityId,
  itemId,
  fieldName,
  scope,
  packId
}) {
  if (fieldName === 'pack-picture') {
    if (!isValidUuid(packId)) {
      return { error: errorResponse(400, 'Missing or invalid parameter: packId') }
    }
    return {
      metadata: { packId, fieldName, originalFileName: fileName },
      key: `packs/${packId}/${fieldName}/${uniqueFileName}`
    }
  }
 
  const isProfilePicture = fieldName === 'profile-picture'
  const isFlowBranding = fieldName === 'flow-picture' || fieldName === 'flow-icon'
  const isEntityBranding = fieldName === 'entity-picture' || fieldName === 'entity-icon'
  const isUserScope = scope === 'user' || isProfilePicture
  const isImportStaging = scope === 'import-staging'
 
  if (isImportStaging) {
    // Staging area for the Import Preview screen: an entity/import bundle's
    // embedded images are re-uploaded here (before any entity/item exists
    // yet, possibly under a brand new entity id not assigned until the
    // import actually commits) so entities/import.js's existing
    // copyImageObject/copyImageFields (same code fork.js already uses) can
    // copy from this key to the entity's final namespace exactly like it
    // copies from a live source entity. Keyed by the caller's own userId
    // (never client-supplied) so only its owner can ever write here.
    const userId = event.requestContext?.authorizer?.claims?.sub
    if (!userId) {
      return {
        error: errorResponse(401, 'Unauthorized: user identity required for import-staging uploads')
      }
    }
    return {
      metadata: { userId, fieldName, originalFileName: fileName },
      key: `imports/${userId}/${uniqueFileName}`
    }
  }
 
  if (isUserScope) {
    const userId = event.requestContext?.authorizer?.claims?.sub
    if (!userId) {
      return {
        error: errorResponse(401, 'Unauthorized: user identity required for user-scoped uploads')
      }
    }
    return {
      metadata: { userId, fieldName, originalFileName: fileName },
      key: `users/${userId}/${fieldName}/${uniqueFileName}`
    }
  }
 
  if (fieldName === 'space-page-image') {
    if (!flowId) {
      return { error: errorResponse(400, 'Missing required parameter: flowId') }
    }
    return {
      metadata: { flowId, fieldName, originalFileName: fileName },
      key: `flows/${flowId}/space-pages/${uniqueFileName}`
    }
  }
 
  if (isFlowBranding) {
    if (!flowId) {
      return { error: errorResponse(400, 'Missing required parameter: flowId') }
    }
    return {
      metadata: { flowId, fieldName, originalFileName: fileName },
      key: `flows/${flowId}/${fieldName}/${uniqueFileName}`
    }
  }
 
  if (isEntityBranding) {
    if (!entityId) {
      return { error: errorResponse(400, 'Missing required parameter: entityId') }
    }
    return {
      metadata: { entityId, fieldName, originalFileName: fileName },
      key: `entities/${entityId}/${fieldName}/${uniqueFileName}`
    }
  }
 
  if (!flowId || !entityId || !itemId) {
    return { error: errorResponse(400, 'Missing required parameters: flowId, entityId, itemId') }
  }
  return {
    metadata: { flowId, entityId, itemId, fieldName, originalFileName: fileName },
    key: `entities/${entityId}/${itemId}/${fieldName}/${uniqueFileName}`
  }
}
 
/**
 * Both image and generic-file uploads go through a presigned POST, never a
 * presigned PUT: only a POST policy lets S3 itself enforce a
 * `content-length-range` condition (and an exact Content-Type match) at
 * upload time — a presigned PUT URL has no such mechanism, so nothing would
 * stop a client bypassing client-side size/type checks by calling this
 * endpoint directly. (Images used to use PUT, with no size limit at all —
 * see docs/architecture/USAGE_METERING.md "Bounding storage before it can be
 * priced" for why that gap mattered beyond just correctness.)
 */
/** The presigned POST of `resolved.key`, its metadata carrying who uploaded it */
async function presignedPostResponse({ resolved, fileType, userId }) {
  // userId is folded in here (rather than threaded through every
  // resolveKeyAndMetadata branch) so every upload kind — including ones that
  // never needed it before — carries it in S3 object Metadata: the S3 usage
  // consumer reads it back via HeadObjectCommand to know who to charge,
  // since S3 Event Notifications carry no auth context of their own.
  const metadataFields = Object.fromEntries(
    Object.entries({ ...resolved.metadata, userId }).map(([field, value]) => [
      `x-amz-meta-${field}`,
      String(value)
    ])
  )
 
  const { url, fields } = await createPresignedPost(s3Client, {
    Bucket: process.env.ATTACHMENTS_BUCKET_NAME,
    Key: resolved.key,
    Conditions: [['content-length-range', 1, MAX_FILE_SIZE_BYTES]],
    Fields: { 'Content-Type': fileType, ...metadataFields },
    Expires: 900
  })
 
  return {
    statusCode: 200,
    headers: CORS_HEADERS,
    body: JSON.stringify({
      uploadUrl: url,
      uploadFields: fields,
      key: resolved.key,
      bucket: process.env.ATTACHMENTS_BUCKET_NAME,
      maxFileSizeBytes: MAX_FILE_SIZE_BYTES
    })
  }
}
 
/** An extension safe in a key: letters and digits, else `bin` */
function safeExtension(fileName) {
  const extension = fileName.includes('.') ? fileName.split('.').pop() : ''
  return /^[A-Za-z0-9]{1,10}$/.test(extension) ? extension.toLowerCase() : 'bin'
}
 
/**
 * A file of a membership request's form (UC-SPACE-020.1): the requester is not
 * a member, so it goes to their drafts (utils/membershipRequestFiles.js), for
 * a field of the join form of that upload kind. Free: no credits check, and
 * the S3 usage consumer skips `membership-requests/`.
 */
async function handleMembershipRequestUpload(body, userId) {
  const { fileName, fileType, fieldName, uploadKind, slug } = body
  if (!userId) return errorResponse(401, 'Unauthorized: user identity required')
 
  const joinable = await loadJoinableFlow(docClient, slug)
  if (!joinable) return errorResponse(404, 'Space not found')
  const { flow, entity } = joinable
  const field = joinFormFields(entity, flow.space.join.userFieldId).find(
    (candidate) => candidate.fieldId === fieldName
  )
  const kind = uploadKind === 'file' ? 'file' : 'image'
  if (!field || uploadKindOf(field.type) !== kind) {
    return errorResponse(400, 'Not an image or file field of the join form')
  }
  const allowed =
    kind === 'image' ? fileType.startsWith('image/') : isAllowedFileUpload(fileName, fileType)
  if (!allowed) {
    return errorResponse(
      400,
      kind === 'image' ? 'Only image files are allowed' : 'File type not allowed'
    )
  }
 
  return presignedPostResponse({
    resolved: {
      key: `${draftPrefix(userId)}${field.fieldId}/${randomUUID()}.${safeExtension(fileName)}`,
      metadata: { flowId: flow.id, fieldName: field.fieldId, originalFileName: fileName }
    },
    fileType,
    userId
  })
}
 
async function createUploadResponse({ resolved, fileType, userId }) {
  // Checked here — after every upload-kind-specific field validation above
  // has already passed — rather than up front in the handler, so a request
  // with e.g. a missing flowId still gets that more specific 400 instead of
  // a generic 401. In production this can't actually trigger: the API's
  // global CognitoAuth requirement guarantees requestContext.authorizer.claims.sub
  // is always present by the time API Gateway invokes this Lambda at all.
  if (!userId) {
    return errorResponse(401, 'Unauthorized: user identity required')
  }
 
  // Preflight, on general balance only (not an exact-cost estimate): the
  // final object size isn't known until the client's own PUT/POST to S3
  // completes, well after this presign call returns — see
  // docs/architecture/USAGE_METERING.md "S3 storage credits". The exact,
  // proportional debit happens later, event-driven, once the real size is
  // known (see uploads/s3-usage-consumer.js).
  const { balance: creditsBalance, isPlatformAdmin } = await getCreditsBalance(
    docClient,
    process.env.USERS_TABLE_NAME,
    userId
  )
  if (!isPlatformAdmin && creditsBalance < 0) {
    return {
      statusCode: 402,
      headers: CORS_HEADERS,
      body: JSON.stringify({ error: 'INSUFFICIENT_CREDITS', balance: creditsBalance })
    }
  }
 
  return presignedPostResponse({ resolved, fileType, userId })
}
 
async function handleImageUpload(event, body, uniqueFileName, userId) {
  const { fileName, fileType, flowId, entityId, itemId, fieldName, scope, packId } = body
 
  if (!fileType.startsWith('image/')) {
    return errorResponse(400, 'Only image files are allowed')
  }
 
  const resolved = resolveKeyAndMetadata({
    event,
    fileName,
    uniqueFileName,
    flowId,
    entityId,
    itemId,
    fieldName,
    scope,
    packId
  })
  if (resolved.error) return resolved.error
 
  return createUploadResponse({ resolved, fileType, userId })
}
 
async function handleFileUpload(event, body, uniqueFileName, userId) {
  const { fileName, fileType, flowId, entityId, itemId, fieldName, scope } = body
 
  if (!isAllowedFileUpload(fileName, fileType)) {
    return errorResponse(400, 'File type not allowed')
  }
 
  const resolved = resolveKeyAndMetadata({
    event,
    fileName,
    uniqueFileName,
    flowId,
    entityId,
    itemId,
    fieldName,
    scope
  })
  Iif (resolved.error) return resolved.error
 
  return createUploadResponse({ resolved, fileType, userId })
}
 
exports.handler = async (event) => {
  try {
    // Matches the pre-existing check order: httpMethod !== 'POST' catches
    // OPTIONS too, so the dedicated OPTIONS branch below is unreachable via
    // this Lambda today (CORS preflight is handled by API Gateway itself,
    // never forwarded here) — kept as-is rather than "fixed", to avoid
    // changing behavior no caller actually depends on.
    if (event.httpMethod !== 'POST') {
      return {
        statusCode: 405,
        headers: { ...CORS_HEADERS, 'Access-Control-Allow-Methods': 'POST, OPTIONS' },
        body: JSON.stringify({ error: 'Method not allowed' })
      }
    }
 
    Iif (event.httpMethod === 'OPTIONS') {
      return {
        statusCode: 200,
        headers: { ...CORS_HEADERS, 'Access-Control-Allow-Methods': 'POST, OPTIONS' }
      }
    }
 
    const body = JSON.parse(event.body || '{}')
    const { fileName, fileType, fieldName, uploadKind } = body
 
    if (!fileName || !fileType || !fieldName) {
      return errorResponse(400, 'Missing required parameters: fileName, fileType, fieldName')
    }
 
    const fileExtension = fileName.split('.').pop()
    const uniqueFileName = `${randomUUID()}.${fileExtension}`
    const userId = event.requestContext?.authorizer?.claims?.sub
 
    if (body.scope === 'membership-request') {
      return await handleMembershipRequestUpload(body, userId)
    }
 
    if (uploadKind === 'file') {
      return await handleFileUpload(event, body, uniqueFileName, userId)
    }
    return await handleImageUpload(event, body, uniqueFileName, userId)
  } catch (error) {
    console.error('Error generating presigned URL:', error)
    return errorResponse(500, 'Internal server error')
  }
}