All files / utils s3Cleanup.js

100% Statements 82/82
100% Branches 45/45
100% Functions 22/22
100% Lines 61/61

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 18830x                             30x   30x     30x           30x   30x   345x       84x 18x 10x                     121x 121x 121x 49x 49x 84x 84x     121x         496x         134x 134x                     182x 34x 62x       112x   55x       51x 10x       129x 129x 77x 77x 77x     2603x     71x 71x 1x   71x   6x     129x                         324x 2615x 81x 81x 2601x 18x   81x                           261x 62x 9x 9x   53x 53x   53x 54x             48x     20x   48x     6x   53x     30x                    
const { DeleteObjectsCommand, ListObjectsV2Command } = require('@aws-sdk/client-s3')
 
// Best-effort removal of the S3 objects a DynamoDB row points at, called AFTER
// the row itself is gone or rewritten: a leaked object costs a few cents of
// storage, a row pointing at a deleted object is a broken image, so S3 always
// goes last and a failure here never fails the request. Anything that slips
// through is caught by scripts/cleanup-s3-orphans.js.
//
// Two safety rules, because the keys come from user-writable data:
//  - a key read from a row is only deleted if it sits inside its owner's own
//    namespace (see the *KeyGuard helpers) — otherwise a user could store
//    someone else's key in an image field and delete it along with the item;
//  - prefix deletion only accepts `{known top folder}/{id}/`, never anything
//    broader.
 
const ID_PATTERN = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'
// Any UUID version: Cognito user ids (`sub`) are not v4.
const ID_REGEX = new RegExp(`^${ID_PATTERN}$`, 'i')
// A membership request's files (docs/architecture/FLOW_SPACE.md, "Images and
// files in the join form"): a flow's, one request's, or one user's drafts.
const PREFIX_REGEX = new RegExp(
  `^((entities|flows|users|imports|exports|packs)/${ID_PATTERN}|membership-requests/(drafts/${ID_PATTERN}|${ID_PATTERN}(/${ID_PATTERN})?))/$`,
  'i'
)
 
// DeleteObjects accepts at most 1000 keys per request.
const DELETE_BATCH_SIZE = 1000
 
const FILE_FIELD_TYPES = new Set(['image', 'image_set', 'file', 'file_set'])
 
const isId = (value) => typeof value === 'string' && ID_REGEX.test(value)
 
/** `image` stores a bare key, `file` stores `{ key, name, size, type }`. */
function keyOfValue(value) {
  if (typeof value === 'string') return value
  if (value && typeof value === 'object' && typeof value.key === 'string') return value.key
  return null
}
 
/**
 * Every S3 key held by an item's image / image_set / file / file_set fields.
 *
 * @param {Array<{ type: string, fieldId: string }>} fields
 * @param {Record<string, unknown>} item
 * @returns {string[]}
 */
function getItemFileKeys(fields, item) {
  const keys = []
  for (const field of fields || []) {
    if (!FILE_FIELD_TYPES.has(field.type)) continue
    const value = item?.[field.fieldId]
    for (const entry of Array.isArray(value) ? value : [value]) {
      const key = keyOfValue(entry)
      if (key) keys.push(key)
    }
  }
  return keys
}
 
/** The picture / icon keys of an entity or flow row. */
function getBrandingKeys(record) {
  return [record?.picture, record?.icon].filter((key) => typeof key === 'string' && key)
}
 
/** Keys present in `before` and no longer in `after` (a replaced or cleared file). */
function getRemovedKeys(before, after) {
  const kept = new Set(after)
  return [...new Set(before)].filter((key) => !kept.has(key))
}
 
/**
 * Key guards: accept a key only if it is inside the given owner's namespace,
 * in either layout ever written by uploads/presigned-url.js — the current
 * `entities/{id}/…`, `flows/{id}/…`, `users/{id}/…`, and the older
 * `{flowId}/{entityId}/{itemId}/…` and `{flowId}/entities/{entityId}/…`.
 * A malformed owner id yields a guard that accepts nothing.
 */
function entityKeyGuard(entityId) {
  if (!isId(entityId)) return () => false
  const legacy = new RegExp(`^${ID_PATTERN}/(entities/)?${entityId}/`, 'i')
  return (key) => key.startsWith(`entities/${entityId}/`) || legacy.test(key)
}
 
function flowKeyGuard(flowId) {
  if (!isId(flowId)) return () => false
  // The legacy flow picture/icon key is `{flowId}/{flowId}/{flowId}/{field}/…`.
  return (key) => key.startsWith(`flows/${flowId}/`) || key.startsWith(`${flowId}/${flowId}/`)
}
 
function userKeyGuard(userId) {
  if (!isId(userId)) return () => false
  return (key) => key.startsWith(`users/${userId}/`)
}
 
async function sendDeleteBatches(s3Client, bucket, keys) {
  let deleted = 0
  for (let i = 0; i < keys.length; i += DELETE_BATCH_SIZE) {
    const batch = keys.slice(i, i + DELETE_BATCH_SIZE)
    try {
      const result = await s3Client.send(
        new DeleteObjectsCommand({
          Bucket: bucket,
          Delete: { Objects: batch.map((Key) => ({ Key })), Quiet: true }
        })
      )
      const failed = result?.Errors ?? []
      for (const error of failed) {
        console.error(`Failed to delete S3 object ${error.Key}: ${error.Code} ${error.Message}`)
      }
      deleted += batch.length - failed.length
    } catch (error) {
      console.error('Failed to delete S3 objects:', error)
    }
  }
  return deleted
}
 
/**
 * Deletes the given keys, skipping any that `guard` rejects. Never throws.
 *
 * @param {import('@aws-sdk/client-s3').S3Client} s3Client
 * @param {string} bucket
 * @param {string[]} keys
 * @param {(key: string) => boolean} guard  one of the *KeyGuard helpers
 * @returns {Promise<number>} number of objects deleted
 */
async function deleteKeys(s3Client, bucket, keys, guard) {
  if (!bucket) return 0
  const candidates = [...new Set(keys)].filter((key) => typeof key === 'string' && key.length > 0)
  const allowed = []
  for (const key of candidates) {
    if (guard(key)) allowed.push(key)
    else console.error(`Refusing to delete S3 key outside its owner's namespace: ${key}`)
  }
  return sendDeleteBatches(s3Client, bucket, allowed)
}
 
/**
 * Deletes every object under `{entities|flows|users|imports|exports|packs}/{id}/`,
 * `membership-requests/{flowId}/`, `membership-requests/{flowId}/{userId}/` or
 * `membership-requests/drafts/{userId}/`. Anything else is refused. Never throws.
 *
 * @param {import('@aws-sdk/client-s3').S3Client} s3Client
 * @param {string} bucket
 * @param {string} prefix
 * @returns {Promise<number>} number of objects deleted
 */
async function deletePrefix(s3Client, bucket, prefix) {
  if (!bucket) return 0
  if (!PREFIX_REGEX.test(prefix)) {
    console.error(`Refusing to delete S3 prefix: ${prefix}`)
    return 0
  }
  let deleted = 0
  try {
    let continuationToken
    do {
      const page = await s3Client.send(
        new ListObjectsV2Command({
          Bucket: bucket,
          Prefix: prefix,
          ContinuationToken: continuationToken
        })
      )
      deleted += await sendDeleteBatches(
        s3Client,
        bucket,
        (page.Contents ?? []).map((object) => object.Key)
      )
      continuationToken = page.IsTruncated ? page.NextContinuationToken : undefined
    } while (continuationToken)
  } catch (error) {
    console.error(`Failed to list S3 prefix ${prefix}:`, error)
  }
  return deleted
}
 
module.exports = {
  getItemFileKeys,
  getBrandingKeys,
  getRemovedKeys,
  entityKeyGuard,
  flowKeyGuard,
  userKeyGuard,
  deleteKeys,
  deletePrefix
}