All files / utils packSnapshot.js

100% Statements 123/123
95.55% Branches 86/90
100% Functions 25/25
100% Lines 107/107

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                                9x 9x 9x             9x 9x 9x   9x             9x   131x   9x                                   41x       38x 38x 266x   38x     9x 9x   16x                   38x 38x 42x   38x 38x 210x 208x 208x 208x 208x     38x 38x 42x 13x 24x 13x 2x   11x 11x 13x 13x 24x 24x 20x 6x 6x   6x     6x 3x 2x       1x   3x 14x 7x 7x 7x 3x   4x   4x 3x   4x     11x   9x   34x                                       44x 40x     8x 7x 7x   8x     40x 40x 44x 44x 54x 54x 50x 50x   4x 2x   2x               42x     38x 5x   38x 42x     38x   37x             34x           37x                   9x                 27x   12x 14x 14x 14x                         27x       24x                         65x 65x 57x 57x   8x 1x                             43x 43x 83x 83x                             9x                      
/**
 * A pack version's frozen schema, with the items of the entities its publisher
 * chose (at most MAX_PACK_ITEMS_PER_ENTITY each): an export bundle gzipped in
 * S3 and written once. Everything it keeps is public, and whoever installs or
 * reports must see all of it, so it is an allowlist rather than a list of what
 * to strip: an item keeps only the values of its entity's fields, never who
 * wrote it, and never a member (`user` fields). Images and files of items are
 * copied under the version (`packs/{packId}/{version}/files/`), so that the
 * pack does not depend on Alice's objects.
 *
 * Its S3 metadata is what bills it: uploads/s3-usage-consumer.js debits the
 * `s3_storage` rate to the `userid` it finds there.
 *
 * @implements UC-STORE-003.1, UC-STORE-005.1
 */
 
const { createHash } = require('crypto')
const { gzipSync, gunzipSync } = require('zlib')
const { randomUUID } = require('crypto')
const {
  S3Client,
  GetObjectCommand,
  PutObjectCommand,
  CopyObjectCommand,
  HeadObjectCommand
} = require('@aws-sdk/client-s3')
const { BUNDLE_VERSION } = require('./bundleFormat')
const { fetchEntity } = require('./entityBundleDiscovery')
 
const s3Client = new S3Client({})
 
/**
 * Stands in for a private entity left out of the pack, in an optional `entity_ref`
 * field: no private id leaks, and at install the existing import resolution finds
 * nothing behind it and drops the field (UC-ENTITY-023.1 AC-9).
 */
const UNAVAILABLE_REFERENCE = 'unavailable'
 
const bucket = () => process.env.ATTACHMENTS_BUCKET_NAME
 
const ALLOWED_ENTITY_KEYS = [
  'name',
  'description',
  'fields',
  'forms',
  'emailTemplates',
  'defaultLanguage',
  'enabledLanguages'
]
 
/**
 * Which entity of the pack an entity is, across versions: `tempId`s are mere
 * positions in one snapshot. Derived from the source entity's id, which must
 * not leak, so a one-way hash; the same source entity keeps the same key in
 * every version of the pack. An installed copy remembers it (UC-STORE-005.1),
 * so that a later version can be matched to the copy.
 */
function packEntityKey(packId, sourceEntityId) {
  return createHash('sha256').update(`${packId}:${sourceEntityId}`).digest('hex').slice(0, 32)
}
 
function toPackEntity(entity) {
  const kept = {}
  for (const key of ALLOWED_ENTITY_KEYS) {
    if (entity[key] !== undefined) kept[key] = entity[key]
  }
  return kept
}
 
const IMAGE_TYPES = ['image', 'image_set']
const FILE_TYPES = ['file', 'file_set']
 
const asList = (value) => (Array.isArray(value) ? value : [value])
 
/**
 * The items of the pack, with ids of their own (`i1`, `i2`...: Alice's ids stay
 * hers) that links between items of the pack use, remapped at install. A link
 * to an item left out is dropped, unless it points at a public entity's item,
 * which anyone can read; one that leaves a mandatory field empty refuses the
 * publication. Images and files point at copies to make under the version.
 */
function buildPackItems(entries, { packId, version, publicTargetIds }) {
  const localIds = new Map()
  for (const { items } of entries) {
    for (const item of items || []) localIds.set(item.id, `i${localIds.size + 1}`)
  }
  const files = []
  const copyOf = (sourceKey) => {
    if (typeof sourceKey !== 'string' || !sourceKey) return null
    const extension = sourceKey.includes('.') ? sourceKey.split('.').pop() : 'bin'
    const targetKey = `packs/${packId}/${version}/files/${randomUUID()}.${extension}`
    files.push({ sourceKey, targetKey })
    return targetKey
  }
 
  const byTempId = new Map()
  for (const { tempId, entity, items } of entries) {
    if (!items?.length) continue
    const fields = entity.fields || []
    const member = fields.find((field) => field.type === 'user' && field.mandatory)
    if (member)
      return { refusal: { memberField: { entityName: entity.name, fieldName: member.name } } }
 
    const packItems = []
    for (const item of items) {
      const kept = { originalId: localIds.get(item.id) }
      for (const field of fields) {
        const value = item[field.fieldId]
        if (value === undefined || value === null || field.type === 'user') continue
        if (field.type === 'entity_ref') {
          const target = field.reference?.entityId
          const links = asList(value)
            .map((id) =>
              localIds.has(id) ? localIds.get(id) : publicTargetIds.has(target) ? id : null
            )
            .filter(Boolean)
          if (links.length === 0) {
            if (field.mandatory) {
              return {
                refusal: { itemReference: { entityName: entity.name, fieldName: field.name } }
              }
            }
            continue
          }
          kept[field.fieldId] = Array.isArray(value) ? links : links[0]
        } else if (IMAGE_TYPES.includes(field.type)) {
          const copies = asList(value).map(copyOf).filter(Boolean)
          if (copies.length > 0) kept[field.fieldId] = Array.isArray(value) ? copies : copies[0]
        } else if (FILE_TYPES.includes(field.type)) {
          const copies = asList(value)
            .map((file) =>
              file && typeof file === 'object' ? { ...file, key: copyOf(file.key) } : null
            )
            .filter((file) => file?.key)
          if (copies.length > 0) kept[field.fieldId] = Array.isArray(value) ? copies : copies[0]
        } else {
          kept[field.fieldId] = value
        }
      }
      packItems.push(kept)
    }
    byTempId.set(tempId, packItems)
  }
  return { byTempId, files }
}
 
/**
 * Builds the snapshot from `discoverBundle`'s entries, whose internal references
 * are already `tempId`s. What is left is a reference leaving the pack: to a public
 * entity it stays as it is, and to anything else it cannot be kept: an optional
 * field becomes unavailable, a mandatory one refuses the publication. Items come
 * with the entries that have them (buildPackItems).
 *
 * @param {Array<{ tempId: string, entity: object, items?: Array<object> }>} entries
 * @param {string} packId the pack the version is for, keying its entities
 * @param {number} [version] the version, under which item files are copied
 * @returns {Promise<
 *   { bundle: object, entitiesPreview: Array<object>, files: Array<{ sourceKey: string, targetKey: string }> } |
 *   { mandatoryReference: { entityName: unknown, fieldName: unknown } } |
 *   { refusal: { memberField?: object, itemReference?: object } }
 * >}
 */
async function buildPackBundle(entries, packId, version = 1) {
  const tempIds = new Set(entries.map((entry) => entry.tempId))
  const publicTargets = new Map()
 
  async function isPublicTarget(targetId) {
    if (!publicTargets.has(targetId)) {
      const target = await fetchEntity(targetId)
      publicTargets.set(targetId, target?.visibility === 'public')
    }
    return publicTargets.get(targetId)
  }
 
  const packEntities = []
  for (const { tempId, entity } of entries) {
    const fields = []
    for (const field of entity.fields || []) {
      const targetId = field.type === 'entity_ref' ? field.reference?.entityId : undefined
      if (!targetId || tempIds.has(targetId) || (await isPublicTarget(targetId))) {
        fields.push(field)
        continue
      }
      if (field.mandatory) {
        return { mandatoryReference: { entityName: entity.name, fieldName: field.name } }
      }
      fields.push({
        ...field,
        reference: {
          ...(field.reference.kind && { kind: field.reference.kind }),
          entityId: UNAVAILABLE_REFERENCE
        }
      })
    }
    packEntities.push({ tempId, entity: { ...entity, fields } })
  }
 
  const publicTargetIds = new Set(
    [...publicTargets].filter(([, isPublic]) => isPublic).map(([id]) => id)
  )
  const items = buildPackItems(
    entries.map((entry, index) => ({ ...entry, entity: packEntities[index].entity })),
    { packId, version, publicTargetIds }
  )
  if (items.refusal) return { refusal: items.refusal }
 
  const entities = entries.map(({ tempId, entity }, index) => ({
    tempId,
    packEntityKey: packEntityKey(packId, entity.id),
    entity: toPackEntity(packEntities[index].entity),
    items: items.byTempId.get(tempId) || []
  }))
 
  return {
    bundle: {
      bundleVersion: BUNDLE_VERSION,
      exportedAt: new Date().toISOString(),
      entities
    },
    entitiesPreview: entities.map(({ entity, items: entityItems }) => ({
      name: entity.name,
      fieldCount: entity.fields.length,
      ...(entityItems.length > 0 && { itemCount: entityItems.length })
    })),
    files: items.files
  }
}
 
/** How many copies run at once: hundreds at most, well within a publication. */
const COPY_CONCURRENCY = 8
 
/**
 * Copies the items' images and files under the version, owned by the
 * publisher, who is billed for them as for the snapshot (the `userid` and
 * `flowid` metadata, uploads/s3-usage-consumer.js). Any failure fails the
 * publication: a pack never points at Alice's own objects.
 */
async function copyPackFiles(files, { userId, flowId }) {
  let next = 0
  async function worker() {
    while (next < files.length) {
      const { sourceKey, targetKey } = files[next++]
      const head = await s3Client.send(new HeadObjectCommand({ Bucket: bucket(), Key: sourceKey }))
      await s3Client.send(
        new CopyObjectCommand({
          Bucket: bucket(),
          Key: targetKey,
          CopySource: encodeURIComponent(`${bucket()}/${sourceKey}`),
          MetadataDirective: 'REPLACE',
          Metadata: { userid: userId, flowid: flowId },
          ...(head.ContentType && { ContentType: head.ContentType }),
          ...(head.ContentDisposition && { ContentDisposition: head.ContentDisposition })
        })
      )
    }
  }
  await Promise.all(Array.from({ length: Math.min(COPY_CONCURRENCY, files.length) }, worker))
}
 
async function writeSnapshot({ key, bundle, userId, flowId }) {
  await s3Client.send(
    new PutObjectCommand({
      Bucket: bucket(),
      Key: key,
      Body: gzipSync(JSON.stringify(bundle)),
      ContentType: 'application/gzip',
      Metadata: { userid: userId, flowid: flowId }
    })
  )
}
 
/** @returns {Promise<object | null>} the bundle, or null when the snapshot is gone */
async function readSnapshot(key) {
  try {
    const result = await s3Client.send(new GetObjectCommand({ Bucket: bucket(), Key: key }))
    const bytes = await result.Body.transformToByteArray()
    return JSON.parse(gunzipSync(Buffer.from(bytes)).toString('utf8'))
  } catch (error) {
    if (error.name === 'NoSuchKey') return null
    throw error
  }
}
 
/**
 * The import entries of an installation: the entities of the stored snapshot, with
 * the installer's choices. Only `create` and `skip`: a pack's items come with the
 * entities it installs, never into one Bob has. An entity without a choice is
 * skipped; its items come with it unless the installer declines them.
 *
 * @param {object} bundle
 * @param {Array<{ tempId: string, mode: string, name?: unknown, includeItems?: boolean }>} choices
 * @returns {Array<object>}
 */
function buildPackImportEntries(bundle, choices) {
  const choiceByTempId = new Map(choices.map((choice) => [choice.tempId, choice]))
  return bundle.entities.map(({ tempId, packEntityKey: entityKey, entity, items = [] }) => {
    const choice = choiceByTempId.get(tempId)
    return {
      tempId,
      // Absent from versions published before copies remembered their origin
      ...(entityKey && { packEntityKey: entityKey }),
      mode: choice?.mode === 'create' ? 'create' : 'skip',
      ...(choice?.name && { name: choice.name }),
      entity,
      // Their images and files are the pack's: the installer is billed for the copies
      fromPack: true,
      includeItems: items.length > 0 && choice?.includeItems !== false,
      items
    }
  })
}
 
module.exports = {
  UNAVAILABLE_REFERENCE,
  s3Client,
  toPackEntity,
  packEntityKey,
  buildPackBundle,
  copyPackFiles,
  writeSnapshot,
  readSnapshot,
  buildPackImportEntries
}