All files / store publish.js

100% Statements 149/149
96.19% Branches 101/105
100% Functions 15/15
100% Lines 135/135

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                                                        1x 1x 1x         1x         1x 1x 1x 1x 1x 1x                               1x 1x 1x 1x 1x 1x   1x 1x 1x               7x 7x             1x         151x               41x 41x 41x 41x 40x 1x   39x   39x                                 23x                       23x 14x                                                       9x 9x 9x                                     9x                 83x         83x       83x                   1x 56x 56x 56x 55x 55x 55x 54x 1x     53x 53x     52x 52x   1x     51x 51x   50x 50x 49x 1x     48x 1x   47x           47x   41x       41x 41x     39x 39x             39x 1x         38x 39x 1x       37x 37x 1x           36x 36x 1x         35x 2x   33x     33x 4x 3x     30x 30x 1x   29x 1x   28x 1x   27x 1x   26x 1x         25x         25x 1x     24x   24x     24x   24x 24x   24x 7x 9x   24x 24x   1x 1x   23x   23x                           23x                 23x                                                   23x 23x   6x   6x 4x   4x 4x 3x   1x 1x     2x         17x                   17x 7x       7x     17x   3x 3x      
/**
 * POST /v1/store
 *
 * Publishes a pack, or the next version of the active flow's pack `packId`: a
 * frozen copy of the schema of the given entities and of the private
 * entities they reference, which is in the Store at once, in place of the previous
 * version. Packs are not moderated. The source entities are left untouched. Body:
 * { name: Text, description?: Text, entityIds: string[], excludeEntityIds?: string[],
 *   itemsEntityIds?: string[], packId?: string, commentsEnabled?: boolean }
 * The entities chosen, the dependencies left out and the entities whose items
 * go with the pack are kept on the pack (`source`), private to its flow: the
 * next version starts from them (store/get.js).
 * where Text is a string or an object keyed by language code. A new version
 * may take a new name, English one included; a new pack cannot take the name
 * of another pack of the flow (409 PACK_NAME_TAKEN). `commentsEnabled`
 * (default true) only applies to a new pack: a new version keeps the pack's
 * setting, which its managers change from the pack (store/update.js).
 *
 * The snapshot goes to S3 first and the rows second, in one transaction: a refused
 * transaction leaves no pack, and its snapshot is removed. See
 * docs/architecture/ENTITY_STORE.md.
 *
 * A new version is then told to the owners of the flows that installed the
 * pack, by store/notify-worker.js (UC-STORE-013.1).
 *
 * @implements UC-STORE-003.1, UC-STORE-008.2, UC-STORE-009.1, UC-STORE-010.1, UC-STORE-011.1, UC-STORE-013.1
 */
 
const { randomUUID } = require('crypto')
const { SQSClient, SendMessageCommand } = require('@aws-sdk/client-sqs')
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const {
  DynamoDBDocumentClient,
  GetCommand,
  TransactWriteCommand
} = require('@aws-sdk/lib-dynamodb')
const {
  authenticateModerator: authenticateUser,
  errorResponse,
  jsonResponse
} = require('../utils/moderation/access')
const { hasPermission } = require('../shared/auth-helper')
const { permissionChecker } = require('../utils/PermissionChecker')
const { isAccessible, fetchEntity, discoverBundle } = require('../utils/entityBundleDiscovery')
const { getCreditsBalance } = require('../utils/creditsLedger')
const { isE2eTestEmail } = require('../utils/e2eTestUser')
const {
  PUBLISH_PERMISSION,
  MAX_PACK_ENTITIES,
  MAX_PACK_SNAPSHOT_BYTES,
  MAX_PACK_ITEMS_PER_ENTITY,
  MAX_PACK_ITEM_FILES,
  isPackPictureKey,
  packsTable,
  versionsTable,
  namesTable,
  storePartitionFor,
  buildPackStatsSync,
  snapshotKeyFor,
  validatePackInput,
  resolvePublication
} = require('../utils/packs')
const { buildPackBundle, copyPackFiles, writeSnapshot, s3Client } = require('../utils/packSnapshot')
const { deleteKeys } = require('../utils/s3Cleanup')
const { isValidUuid } = require('../utils/isValidUuid')
const { removeStaleSnapshots } = require('../utils/packCleanup')
const { syncPackSearchIndex } = require('../utils/directorySearchIndex')
 
const { checkCanPost } = require('../utils/accountSanctions')
const docClient = DynamoDBDocumentClient.from(new DynamoDBClient({}))
const sqsClient = new SQSClient({})
 
/**
 * Queues the notification of a new version to the flows that installed the
 * pack. Best-effort: the version is published either way, and Bob still finds
 * the update on the pack page.
 */
async function queueVersionNotification(packId, version) {
  try {
    await sqsClient.send(
      new SendMessageCommand({
        QueueUrl: process.env.PACK_NOTIFY_QUEUE_URL,
        MessageBody: JSON.stringify({ packId, version })
      })
    )
  } catch (error) {
    console.error('[store/publish] Could not queue the version notification:', error.message)
  }
}
 
function asIdList(value) {
  return Array.isArray(value) ? value.filter((id) => typeof id === 'string') : []
}
 
/**
 * The starting entities, or the refusal: they must belong to the active flow, as a
 * pack only ever publishes the flow's own schema.
 */
async function loadStartingEntities(entityIds, flowId, callerPermissions) {
  const entities = []
  for (const id of entityIds) {
    const entity = await fetchEntity(id)
    if (!entity) return { response: errorResponse(404, `Entity not found: ${id}`) }
    if (entity.flowId !== flowId || !isAccessible(entity, flowId, callerPermissions)) {
      return { response: errorResponse(403, `Access denied to entity: ${id}`) }
    }
    entities.push(entity)
  }
  return { entities }
}
 
/**
 * The writes creating a pack with its first version, or moving an existing one to
 * its next. The pack row carries a copy of the current version, so that the Store
 * lists it without reading versions.
 */
function buildPackWrites({
  publication,
  packId,
  current,
  userId,
  flowId,
  commentsEnabled,
  picture
}) {
  const storeFields = {
    currentVersion: current.version,
    name: current.name,
    description: current.description,
    snapshotKey: current.snapshotKey,
    entitiesPreview: current.entitiesPreview,
    publishedAt: current.publishedAt,
    storeKey: current.storeKey,
    // What the publisher chose, for the next version to start from (store/get.js)
    source: current.source,
    storeSortKey: `${current.publishedAt}#${packId}`
  }
  if (publication.isNew) {
    return [
      {
        Put: {
          TableName: namesTable(),
          Item: { nameKey: publication.nameKey, packId },
          ConditionExpression: 'attribute_not_exists(nameKey)'
        }
      },
      {
        Put: {
          TableName: packsTable(),
          Item: {
            id: packId,
            flowId,
            authorId: userId,
            nameKey: publication.nameKey,
            ...storeFields,
            commentsEnabled,
            ...(picture && { picture }),
            createdAt: current.publishedAt
          },
          ConditionExpression: 'attribute_not_exists(id)'
        }
      }
    ]
  }
  // A new name moves the pack's reservation: the old name is freed, the new
  // one claimed, in the same transaction
  const renamed = publication.nameKey !== publication.pack.nameKey
  if (renamed) storeFields.nameKey = publication.nameKey
  const nameWrites = renamed
    ? [
        {
          Put: {
            TableName: namesTable(),
            Item: { nameKey: publication.nameKey, packId },
            ConditionExpression: 'attribute_not_exists(nameKey)'
          }
        },
        {
          Delete: {
            TableName: namesTable(),
            Key: { nameKey: publication.pack.nameKey },
            ConditionExpression: 'packId = :packId',
            ExpressionAttributeValues: { ':packId': packId }
          }
        }
      ]
    : []
  return [
    ...nameWrites,
    {
      Update: {
        TableName: packsTable(),
        Key: { id: packId },
        // The owner publishing takes the pack over, which keeps it maintainable
        // once its author has left the flow.
        UpdateExpression: `SET authorId = :me, ${Object.keys(storeFields)
          .map((field) => `#${field} = :${field}`)
          .join(', ')}`,
        // Another publication of the same name since we read the pack wins
        ConditionExpression: 'currentVersion = :previous',
        ExpressionAttributeNames: Object.fromEntries(
          Object.keys(storeFields).map((field) => [`#${field}`, field])
        ),
        ExpressionAttributeValues: {
          ...Object.fromEntries(
            Object.entries(storeFields).map(([field, value]) => [`:${field}`, value])
          ),
          ':previous': publication.pack.currentVersion,
          ':me': userId
        }
      }
    }
  ]
}
 
exports.handler = async (event) => {
  try {
    const caller = await authenticateUser(event)
    if (caller.response) return caller.response
    const { auth } = caller
    const { userId, flowId } = auth
    if (!flowId) return errorResponse(403, 'NO_ACTIVE_FLOW')
    if (!(await hasPermission(auth, PUBLISH_PERMISSION))) {
      return errorResponse(403, 'PACK_PUBLISH_FORBIDDEN')
    }
    // A restricted or banned account publishes nothing (UC-REPORT-007.1)
    const restricted = await checkCanPost(docClient, userId)
    if (restricted) return restricted
 
    let payload
    try {
      payload = JSON.parse(event.body || '{}')
    } catch {
      return errorResponse(400, 'Invalid JSON body')
    }
 
    const input = validatePackInput(payload)
    if (!input.valid) return errorResponse(400, input.error)
 
    const entityIds = asIdList(payload.entityIds)
    if (entityIds.length === 0) return errorResponse(400, 'Missing entityIds')
    if (entityIds.length > MAX_PACK_ENTITIES) {
      return errorResponse(400, 'PACK_TOO_MANY_ENTITIES', { max: MAX_PACK_ENTITIES })
    }
 
    if (payload.packId !== undefined && typeof payload.packId !== 'string') {
      return errorResponse(400, 'Invalid packId')
    }
    const publication = await resolvePublication(docClient, {
      flowId,
      userId,
      name: input.name,
      packId: payload.packId
    })
    if (publication.refusal) return errorResponse(publication.status, publication.refusal)
 
    const { permissions: callerPermissions = [] } = await permissionChecker.getUserPermissions(
      userId,
      flowId
    )
    const starting = await loadStartingEntities(entityIds, flowId, callerPermissions)
    if (starting.response) return starting.response
 
    // Items of the entities the publisher chose, at most MAX_PACK_ITEMS_PER_ENTITY each
    const itemsEntityIds = asIdList(payload.itemsEntityIds)
    const { entries } = await discoverBundle(starting.entities, flowId, {
      itemsMode: itemsEntityIds.length > 0 ? 'full' : 'skip',
      includeItemsEntityIds: new Set(itemsEntityIds),
      maxItemsPerEntity: MAX_PACK_ITEMS_PER_ENTITY,
      excludeEntityIds: new Set(asIdList(payload.excludeEntityIds)),
      callerPermissions
    })
    if (entries.length > MAX_PACK_ENTITIES) {
      return errorResponse(400, 'PACK_TOO_MANY_ENTITIES', { max: MAX_PACK_ENTITIES })
    }
 
    // The permission that making an entity public needs: exposing a schema to the
    // whole platform must not be open to someone who merely reads it.
    for (const { entity } of entries) {
      if (!(await hasPermission(auth, `entities-${entity.id}:update`, entity))) {
        return errorResponse(403, 'PACK_ENTITY_NOT_EDITABLE', { entityName: entity.name })
      }
    }
 
    const crowded = entries.find((entry) => entry.tooManyItems)
    if (crowded) {
      return errorResponse(400, 'PACK_TOO_MANY_ITEMS', {
        entityName: crowded.entity.name,
        max: MAX_PACK_ITEMS_PER_ENTITY
      })
    }
    // Items may hold personal data: the publisher confirms they may share them
    const withItems = entries.some((entry) => entry.items.length > 0)
    if (withItems && payload.itemsConfirmed !== true) {
      return errorResponse(400, 'PACK_ITEMS_CONFIRMATION_REQUIRED')
    }
 
    // A new pack may come with its id, chosen by the panel, so that its picture is
    // uploaded under it before it exists (as an entity's, entities/create.js)
    if (payload.id !== undefined && !(publication.isNew && isValidUuid(payload.id))) {
      return errorResponse(400, 'Invalid id')
    }
    const packId = publication.isNew ? payload.id || randomUUID() : publication.pack.id
    // The picture is the pack's, set with the first version and changed from its
    // page (store/update.js): a new version keeps it
    if (payload.picture !== undefined && payload.picture !== null) {
      if (!publication.isNew || !isPackPictureKey(packId, payload.picture)) {
        return errorResponse(400, 'PACK_PICTURE_INVALID')
      }
    }
    const built = await buildPackBundle(entries, packId, publication.version)
    if (built.mandatoryReference) {
      return errorResponse(400, 'PACK_MANDATORY_REFERENCE', built.mandatoryReference)
    }
    if (built.refusal?.memberField) {
      return errorResponse(400, 'PACK_ITEMS_MEMBER_FIELD', built.refusal.memberField)
    }
    if (built.refusal?.itemReference) {
      return errorResponse(400, 'PACK_ITEMS_REFERENCE', built.refusal.itemReference)
    }
    if (built.files.length > MAX_PACK_ITEM_FILES) {
      return errorResponse(400, 'PACK_TOO_MANY_FILES', { max: MAX_PACK_ITEM_FILES })
    }
    if (Buffer.byteLength(JSON.stringify(built.bundle), 'utf8') > MAX_PACK_SNAPSHOT_BYTES) {
      return errorResponse(400, 'PACK_TOO_LARGE', { maxBytes: MAX_PACK_SNAPSHOT_BYTES })
    }
 
    // The same general-balance preflight as an upload (uploads/presigned-url.js):
    // the exact s3_storage debit follows once the snapshot is stored.
    const { balance, isPlatformAdmin } = await getCreditsBalance(
      docClient,
      process.env.USERS_TABLE_NAME,
      userId
    )
    if (!isPlatformAdmin && balance < 0) {
      return errorResponse(402, 'INSUFFICIENT_CREDITS', { balance })
    }
 
    const { version } = publication
 
    const authorResult = await docClient.send(
      new GetCommand({ TableName: process.env.USERS_TABLE_NAME, Key: { id: userId } })
    )
    const storeKey = storePartitionFor({ isTest: isE2eTestEmail(authorResult.Item?.email) })
 
    const snapshotKey = snapshotKeyFor(packId, version)
    const fileKeys = built.files.map((file) => file.targetKey)
    // What this publication stored, removed if it does not commit (never throws: logged)
    const discardStored = () =>
      deleteKeys(s3Client, process.env.ATTACHMENTS_BUCKET_NAME, [snapshotKey, ...fileKeys], (key) =>
        key.startsWith(`packs/${packId}/${version}/`)
      )
    try {
      await copyPackFiles(built.files, { userId, flowId })
    } catch (copyError) {
      await discardStored()
      throw copyError
    }
    await writeSnapshot({ key: snapshotKey, bundle: built.bundle, userId, flowId })
 
    const current = {
      version,
      name: input.name,
      description: input.description,
      snapshotKey,
      entitiesPreview: built.entitiesPreview,
      publishedAt: new Date().toISOString(),
      storeKey,
      source: {
        entityIds,
        excludeEntityIds: asIdList(payload.excludeEntityIds),
        itemsEntityIds
      }
    }
    const packWrites = buildPackWrites({
      publication,
      packId,
      current,
      userId,
      flowId,
      commentsEnabled: payload.commentsEnabled !== false,
      picture: payload.picture || undefined
    })
    const transactItems = [
      ...packWrites,
      {
        Put: {
          TableName: versionsTable(),
          Item: {
            packId,
            version,
            authorId: userId,
            name: input.name,
            description: input.description,
            snapshotKey,
            entitiesPreview: built.entitiesPreview,
            // The items' copies, removed with the snapshot (utils/packCleanup.js)
            ...(fileKeys.length > 0 && { fileKeys }),
            // Who confirmed the items may be shared, and when
            ...(withItems && { itemsConfirmedAt: current.publishedAt }),
            createdAt: current.publishedAt
          },
          ConditionExpression: 'attribute_not_exists(packId)'
        }
      },
      // The Store sorted by likes lists the pack in its partition, at once
      { Update: buildPackStatsSync(packId, storeKey) }
    ]
 
    try {
      await docClient.send(new TransactWriteCommand({ TransactItems: transactItems }))
    } catch (error) {
      await discardStored()
 
      if (error.name === 'TransactionCanceledException') {
        const reasons = error.CancellationReasons || []
        // The name, claimed first, went to another pack meanwhile
        const claimsName = transactItems[0].Put?.TableName === namesTable()
        if (claimsName && reasons[0]?.Code === 'ConditionalCheckFailed') {
          return errorResponse(409, 'PACK_NAME_TAKEN')
        }
        Eif (reasons.some((r) => r?.Code === 'ConditionalCheckFailed')) {
          return errorResponse(409, 'PACK_CONFLICT')
        }
      }
      throw error
    }
 
    // The Store search follows the new name and description. Best-effort: a
    // failure only leaves the pack unfindable by search until republished.
    await syncPackSearchIndex(
      docClient,
      process.env.FIELD_VALUE_INDEX_TABLE_NAME,
      packId,
      publication.isNew ? null : publication.pack,
      current
    )
 
    // The previous snapshot stays until the next publication: an install queued
    // just before this one still finds it.
    if (!publication.isNew) {
      await removeStaleSnapshots(docClient, {
        packId,
        keepVersions: [publication.pack.currentVersion, version]
      })
      await queueVersionNotification(packId, version)
    }
 
    return jsonResponse(201, { id: packId, version, isNewPack: publication.isNew })
  } catch (error) {
    console.error('[store/publish] Exception:', error.message, error.stack)
    return errorResponse(500, 'Failed to publish pack')
  }
}