All files / utils membershipRequestFiles.js

100% Statements 118/118
96.61% Branches 57/59
100% Functions 29/29
100% Lines 99/99

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                        11x 11x 11x   11x   11x 11x 11x 11x   11x   56x 69x       12x 7x 2x     50x 85x     29x 43x 19x       34x 26x               15x 4x 1x   2x 1x   1x     11x 21x 21x       12x 12x 10x   2x 1x         21x                     11x 47x 233x 106x 37x                         25x 25x   25x 23x 15x 15x   20x 20x 20x 9x         12x 12x 12x 12x 12x 12x 9x 9x 9x 9x 9x 8x 8x 8x   8x     1x 1x   11x                                           22x 22x 22x 22x 22x 14x 14x 14x 14x 12x 12x 12x                       11x 11x   13x 11x 1x     1x 1x   21x         7x 5x         5x 5x         22x         1x         6x 6x         1x     11x                            
// @implements UC-SPACE-020.1
/**
 * The images and files of a membership request (docs/architecture/FLOW_SPACE.md,
 * "Images and files in the join form"). The requester is not a member yet, so
 * the files live under their own prefix until the request is decided:
 *
 *   membership-requests/drafts/{userId}/{fieldId}/{file}     — uploaded, form not sent
 *   membership-requests/{flowId}/{userId}/{fieldId}/{file}   — sent with the request
 *
 * On approval they are copied into the membership item's own keys
 * (`entities/{entityId}/{itemId}/{fieldId}/{file}`), billed to the approver.
 */
const { S3Client, CopyObjectCommand, HeadObjectCommand } = require('@aws-sdk/client-s3')
const { randomUUID } = require('crypto')
const { deleteKeys, deletePrefix } = require('./s3Cleanup')
 
const s3Client = new S3Client({})
 
const ROOT = 'membership-requests/'
const IMAGE_FIELD_TYPES = ['image', 'image_set']
const FILE_FIELD_TYPES = ['file', 'file_set']
const UPLOAD_FIELD_TYPES = [...IMAGE_FIELD_TYPES, ...FILE_FIELD_TYPES]
/** A file name segment of a key: no slash, no `..` */
const FILE_SEGMENT = /^[A-Za-z0-9-]+(\.[A-Za-z0-9]+)?$/
 
const draftPrefix = (userId) => `${ROOT}drafts/${userId}/`
const requestPrefix = (flowId, userId) => `${ROOT}${flowId}/${userId}/`
 
/** The upload kind (`uploads/presigned-url.js`'s `uploadKind`) a field takes, or null */
function uploadKindOf(fieldType) {
  if (IMAGE_FIELD_TYPES.includes(fieldType)) return 'image'
  if (FILE_FIELD_TYPES.includes(fieldType)) return 'file'
  return null
}
 
const isSet = (field) => field.type === 'image_set' || field.type === 'file_set'
const isImage = (field) => IMAGE_FIELD_TYPES.includes(field.type)
 
/** The entries of an answer: a set's elements, or the single value */
const entriesOf = (field, value) => (isSet(field) ? value : [value])
const keyOfEntry = (field, entry) => (isImage(field) ? entry : entry?.key)
const withKey = (field, entry, key) => (isImage(field) ? key : { ...entry, key })
 
/** Whether `key` is directly under `{prefix}{fieldId}/` */
function isKeyOf(key, prefix, fieldId) {
  if (typeof key !== 'string' || !key.startsWith(`${prefix}${fieldId}/`)) return false
  return FILE_SEGMENT.test(key.slice(`${prefix}${fieldId}/`.length))
}
 
/**
 * The shape of an image answer (an item's file answers are already checked by
 * validateFieldTypes): a key, or an array of keys within the field's maximum.
 */
function imageShapeError(field, value) {
  if (field.type === 'image') return typeof value === 'string' ? null : 'INVALID_IMAGE_VALUE'
  if (!Array.isArray(value) || !value.every((key) => typeof key === 'string')) {
    return 'INVALID_IMAGE_VALUE'
  }
  if (typeof field.maxImages === 'number' && value.length > field.maxImages) {
    return 'IMAGE_SET_TOO_MANY_IMAGES'
  }
  return null
}
 
const extensionOf = (key) => {
  const name = key.slice(key.lastIndexOf('/') + 1)
  return name.includes('.') ? name.split('.').pop() : 'bin'
}
 
async function objectExists(bucket, key) {
  try {
    await s3Client.send(new HeadObjectCommand({ Bucket: bucket, Key: key }))
    return true
  } catch (error) {
    if (error.name === 'NotFound' || error.$metadata?.httpStatusCode === 404) return false
    throw error
  }
}
 
async function copyObject(bucket, sourceKey, targetKey, overrides = {}) {
  await s3Client.send(
    new CopyObjectCommand({
      Bucket: bucket,
      Key: targetKey,
      CopySource: encodeURIComponent(`${bucket}/${sourceKey}`),
      ...overrides
    })
  )
}
 
/** Answers of upload fields: `[{ field, value }]` */
const uploadAnswers = (fields, answers) =>
  fields
    .filter((field) => UPLOAD_FIELD_TYPES.includes(field.type))
    .filter((field) => answers[field.fieldId] !== undefined && answers[field.fieldId] !== null)
    .map((field) => ({ field, value: answers[field.fieldId] }))
 
/**
 * Turns the caller's drafts named in `answers` into the request's own files:
 * each key must be one of the caller's drafts of that field and exist; it is
 * copied under the request's prefix and the answer rewritten. Nothing is
 * copied unless every key passes. The drafts are left to the caller to delete
 * once the request is written (`deleteDraftKeys`): another form of the same
 * user may still be using its own.
 *
 * @returns {Promise<{ answers: object, copiedKeys: string[], draftKeys: string[] } | { error: string, fieldId: string }>}
 */
async function promoteDraftAnswers({ bucket, fields, answers, flowId, userId }) {
  const uploads = uploadAnswers(fields, answers)
  const drafts = draftPrefix(userId)
 
  for (const { field, value } of uploads) {
    if (isImage(field)) {
      const shapeError = imageShapeError(field, value)
      if (shapeError) return { error: shapeError, fieldId: field.fieldId }
    }
    for (const entry of entriesOf(field, value)) {
      const key = keyOfEntry(field, entry)
      if (!isKeyOf(key, drafts, field.fieldId) || !(await objectExists(bucket, key))) {
        return { error: 'INVALID_FILE_VALUE', fieldId: field.fieldId }
      }
    }
  }
 
  const promoted = { ...answers }
  const copiedKeys = []
  const draftKeys = []
  const target = requestPrefix(flowId, userId)
  try {
    for (const { field, value } of uploads) {
      const copied = []
      for (const entry of entriesOf(field, value)) {
        const key = keyOfEntry(field, entry)
        const targetKey = `${target}${field.fieldId}/${randomUUID()}.${extensionOf(key)}`
        await copyObject(bucket, key, targetKey)
        draftKeys.push(key)
        copiedKeys.push(targetKey)
        copied.push(withKey(field, entry, targetKey))
      }
      promoted[field.fieldId] = isSet(field) ? copied : copied[0]
    }
  } catch (error) {
    await deleteRequestKeys(bucket, flowId, userId, copiedKeys)
    throw error
  }
  return { answers: promoted, copiedKeys, draftKeys }
}
 
/**
 * Copies a request's files (`data`'s upload fields) into the membership
 * item's own keys, billed to `owner` (the approver): the S3 usage consumer
 * charges the `userid` of the object's metadata. A key that is not one of the
 * request's is dropped from the data rather than copied. Throws when a copy
 * fails, after deleting the copies already made.
 *
 * @returns {Promise<{ data: object, copiedKeys: string[] }>}
 */
async function copyRequestFilesToItem({
  bucket,
  fields,
  data,
  flowId,
  userId,
  entityId,
  itemId,
  owner
}) {
  const source = requestPrefix(flowId, userId)
  const copiedData = { ...data }
  const copiedKeys = []
  try {
    for (const { field, value } of uploadAnswers(fields, data)) {
      const copied = []
      for (const entry of Array.isArray(value) ? value : [value]) {
        const key = keyOfEntry(field, entry)
        if (!isKeyOf(key, source, field.fieldId)) continue
        const head = await s3Client.send(new HeadObjectCommand({ Bucket: bucket, Key: key }))
        const targetKey = `entities/${entityId}/${itemId}/${field.fieldId}/${randomUUID()}.${extensionOf(key)}`
        await copyObject(bucket, key, targetKey, {
          MetadataDirective: 'REPLACE',
          Metadata: {
            ...(head.Metadata || {}),
            userid: owner.userId,
            flowid: owner.flowId,
            entityid: entityId,
            itemid: itemId,
            fieldname: field.fieldId
          },
          ...(head.ContentType && { ContentType: head.ContentType })
        })
        copiedKeys.push(targetKey)
        copied.push(withKey(field, entry, targetKey))
      }
      if (isSet(field)) copiedData[field.fieldId] = copied
      else if (copied.length) copiedData[field.fieldId] = copied[0]
      else delete copiedData[field.fieldId]
    }
  } catch (error) {
    await deleteItemCopies(bucket, entityId, itemId, copiedKeys)
    throw error
  }
  return { data: copiedData, copiedKeys }
}
 
/** Deletes copies made into an item that was not written after all */
function deleteItemCopies(bucket, entityId, itemId, keys) {
  return deleteKeys(s3Client, bucket, keys, (key) =>
    key.startsWith(`entities/${entityId}/${itemId}/`)
  )
}
 
function deleteRequestKeys(bucket, flowId, userId, keys) {
  const prefix = requestPrefix(flowId, userId)
  return deleteKeys(s3Client, bucket, keys, (key) => key.startsWith(prefix))
}
 
/** Deletes every file of one request. Never throws. */
function deleteRequestFiles(bucket, flowId, userId) {
  return deletePrefix(s3Client, bucket, requestPrefix(flowId, userId))
}
 
/** Deletes every request file of a flow. Never throws. */
function deleteFlowRequestFiles(bucket, flowId) {
  return deletePrefix(s3Client, bucket, `${ROOT}${flowId}/`)
}
 
/** Deletes the given drafts of a user. Never throws. */
function deleteDraftKeys(bucket, userId, keys) {
  const prefix = draftPrefix(userId)
  return deleteKeys(s3Client, bucket, keys, (key) => key.startsWith(prefix))
}
 
/** Deletes all of a user's drafts (their account is deleted). Never throws. */
function deleteDrafts(bucket, userId) {
  return deletePrefix(s3Client, bucket, draftPrefix(userId))
}
 
module.exports = {
  UPLOAD_FIELD_TYPES,
  uploadKindOf,
  draftPrefix,
  requestPrefix,
  promoteDraftAnswers,
  copyRequestFilesToItem,
  deleteItemCopies,
  deleteRequestKeys,
  deleteRequestFiles,
  deleteFlowRequestFiles,
  deleteDraftKeys,
  deleteDrafts
}