All files / utils commentAccess.js

97.64% Statements 83/85
92.53% Branches 62/67
100% Functions 15/15
98.73% Lines 78/79

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 2718x 8x 8x 8x 8x 8x   8x           98x                 191x   191x 7x   184x     184x       163x     163x                       35x       24x   11x                                     129x                       37x 11x                       11x                 5x 2x                   15x 15x 13x 2x   11x                               139x 1x     138x 138x 1x         137x 137x 5x 2x   3x     135x 104x 104x 3x           132x 2x     130x     130x 1x     129x                                 158x 158x 154x   154x 154x     154x   140x                       33x 33x 30x   30x   30x 4x 4x 3x 1x   2x     26x 1x     25x 25x 1x     24x 3x     21x         82x 82x           82x     8x                  
const { GetCommand } = require('@aws-sdk/lib-dynamodb')
const { authenticateRequest, hasPermission, canAccessEntity } = require('../shared/auth-helper')
const { isPlatformAdminUser } = require('./platformAdmin')
const { canDeletePack } = require('./packAccess')
const { getPack } = require('./packs')
const { SUBJECT_TYPE } = require('./moderation/constants')
 
const CORS_HEADERS = {
  'Content-Type': 'application/json',
  'Access-Control-Allow-Origin': '*'
}
 
function errorResponse(statusCode, error, extra = {}) {
  return { statusCode, headers: CORS_HEADERS, body: JSON.stringify({ error, ...extra }) }
}
 
/**
 * Comments always belong to a signed-in user: an API key is rejected. An
 * active flow is not required — a public entity's comments, and a pack's, are
 * open to any signed-in user, including one who has no flow yet.
 */
async function authenticateCaller(event) {
  const auth = await authenticateRequest(event)
 
  if (!auth || auth.error) {
    return { response: errorResponse(401, auth?.error || 'Authentication required') }
  }
  Iif (!auth.userId) {
    return { response: errorResponse(401, 'Comments require a signed-in user') }
  }
  return { auth }
}
 
async function loadEntity(docClient, entityId) {
  const result = await docClient.send(
    new GetCommand({ TableName: process.env.ENTITIES_TABLE_NAME, Key: { id: entityId } })
  )
  return result.Item
}
 
/**
 * Whether the caller may manage the comments of `entity`: delete any approved
 * comment, block users from commenting. That is a holder of
 * `entities-{id}:update` acting in the entity's own flow, or a platform admin.
 * Nobody can decide a pending comment: the community alone does.
 * Deliberately no new permission verb: it would need the RBAC grammar, the UI
 * mirror and the role presets to change — see docs/architecture/MODERATION.md.
 */
async function canManageComments(docClient, auth, entity) {
  if (
    entity.flowId === auth.flowId &&
    (await hasPermission(auth, `entities-${entity.id}:update`, entity))
  ) {
    return true
  }
  return isPlatformAdminUser(docClient, auth.userId)
}
 
/**
 * A comment thread: what every comments endpoint needs, whichever content the
 * comments hang from.
 * - key: the CommentsTable partition (`itemId` attribute) and the comment
 *   counter's key — an item id, or a pack id
 * - blocksKey: the CommentBlocksTable partition (`entityId` attribute) — the
 *   entity, or the pack, whose managers block users
 * - moderated: whether new comments go through the community first
 * - rowFields: what each comment of the thread stores besides its own fields
 * - owns(comment): whether a stored comment belongs to this thread
 * - canManage(): whether the caller may delete anyone's comment and block users
 * - viaPlatformAdmin (item threads): the caller reaches a private entity of
 *   another flow only as a platform admin — they may read and manage the
 *   thread, not take part in it
 */
function itemThread(docClient, auth, entity, item) {
  return {
    kind: 'item',
    key: item.id,
    blocksKey: entity.id,
    // Everything on a public entity is moderated by the community first, the
    // owner's and the flow members' comments included; a private entity only
    // has members, who are trusted — see docs/architecture/MODERATION.md.
    moderated: entity.visibility === 'public',
    subjectType: SUBJECT_TYPE.ITEM_COMMENT,
    subjectRef: { entityId: entity.id, itemId: item.id },
    scopeFlowId: entity.flowId,
    rowFields: { entityId: entity.id, flowId: entity.flowId },
    owns: (comment) => comment.entityId === entity.id,
    canManage: () => canManageComments(docClient, auth, entity),
    entity,
    item
  }
}
 
/**
 * A store pack's thread. Packs are public by nature, so their comments are
 * always moderated. Each comment remembers the version it was written on: the
 * comments stay on the pack across versions, as its likes do.
 */
function packThread(docClient, auth, pack) {
  return {
    kind: 'pack',
    key: pack.id,
    blocksKey: pack.id,
    moderated: true,
    subjectType: SUBJECT_TYPE.PACK_COMMENT,
    subjectRef: { packId: pack.id },
    scopeFlowId: pack.flowId,
    rowFields: { packId: pack.id, flowId: pack.flowId, packVersion: pack.currentVersion },
    owns: (comment) => comment.packId === pack.id,
    canManage: () => canDeletePack(docClient, pack, auth.userId),
    pack
  }
}
 
/**
 * The thread of `/v1/store/{packId}/...`: any signed-in user may read and
 * write the comments of a pack, as anyone may open it in the Store.
 */
async function resolvePackThread(docClient, auth, packId, { requireEnabled }) {
  const pack = await getPack(docClient, packId)
  if (!pack) return { response: errorResponse(404, 'Pack not found') }
  if (requireEnabled && pack.commentsEnabled !== true) {
    return { response: errorResponse(403, 'COMMENTS_DISABLED') }
  }
  return { thread: packThread(docClient, auth, pack) }
}
 
/**
 * The thread of `/v1/entities/{entityId}/items/{itemId}/...`.
 *
 * Access follows items/like.js rather than items/get.js's stricter
 * `item.flowId === auth.flowId` check, which would wrongly reject a public
 * entity's item viewed from another flow (catalog, home feed):
 * - a user from another flow needs no RBAC permission to see a public
 *   entity's comments — like subscribing, they are a personal action, and
 *   the caller has no membership in the owning flow to check;
 * - a user acting in the entity's own flow needs the usual
 *   `entities-{id}:items:read` permission.
 */
async function resolveItemThread(docClient, auth, { entityId, itemId }, { requireEnabled }) {
  if (!entityId || !itemId) {
    return { response: errorResponse(400, 'Missing entityId or itemId') }
  }
 
  const entity = await loadEntity(docClient, entityId)
  if (!entity) {
    return { response: errorResponse(404, 'Entity not found') }
  }
 
  // A platform admin reads and manages any thread, a private entity of
  // another flow included, to act on a report (UC-REPORT-004.1)
  let viaPlatformAdmin = false
  if (!canAccessEntity(auth, entity)) {
    if (!(await isPlatformAdminUser(docClient, auth.userId))) {
      return { response: errorResponse(403, 'Access denied to this entity') }
    }
    viaPlatformAdmin = true
  }
 
  if (entity.flowId === auth.flowId) {
    const requiredPermission = `entities-${entityId}:items:read`
    if (!(await hasPermission(auth, requiredPermission))) {
      return {
        response: errorResponse(403, `Permission denied: ${requiredPermission} required`)
      }
    }
  }
 
  if (requireEnabled && entity.commentsEnabled !== true) {
    return { response: errorResponse(403, 'COMMENTS_DISABLED') }
  }
 
  const itemResult = await docClient.send(
    new GetCommand({ TableName: process.env.ITEMS_TABLE_NAME, Key: { entityId, id: itemId } })
  )
  if (!itemResult.Item) {
    return { response: errorResponse(404, 'Item not found') }
  }
 
  return { thread: { ...itemThread(docClient, auth, entity, itemResult.Item), viaPlatformAdmin } }
}
 
/**
 * Shared preamble of every comments endpoint: authenticates the caller and
 * resolves the thread the comments hang from — an item, or a store pack when
 * the route carries `packId` — applying the access rules of
 * docs/architecture/MODERATION.md.
 *
 * @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
 * @param {object} event API Gateway event
 * @param {{ requireEnabled?: boolean }} [options] requireEnabled (default true)
 *   rejects threads whose comments are disabled. Deleting one's own comment
 *   stays possible after comments are switched off, so it opts out.
 * @returns {Promise<{ response: object } | { auth: object, thread: object }>}
 */
async function resolveCommentContext(docClient, event, { requireEnabled = true } = {}) {
  const caller = await authenticateCaller(event)
  if (caller.response) return caller
  const { auth } = caller
 
  const params = event.pathParameters || {}
  const resolved = params.packId
    ? await resolvePackThread(docClient, auth, params.packId, { requireEnabled })
    : await resolveItemThread(docClient, auth, params, { requireEnabled })
  if (resolved.response) return resolved
 
  return { auth, thread: resolved.thread }
}
 
/**
 * Preamble of the endpoints that manage a block list: authenticates, loads the
 * entity or the pack and requires its managers' rights. Unlike
 * resolveCommentContext there is no item and no commentsEnabled requirement —
 * managers can tidy up a block list whether or not comments are currently on.
 *
 * @returns {Promise<{ response: object } | { auth: object, blocksKey: string }>}
 */
async function resolveManagerContext(docClient, event) {
  const caller = await authenticateCaller(event)
  if (caller.response) return caller
  const { auth } = caller
 
  const { entityId, packId } = event.pathParameters || {}
 
  if (packId) {
    const pack = await getPack(docClient, packId)
    if (!pack) return { response: errorResponse(404, 'Pack not found') }
    if (!(await canDeletePack(docClient, pack, auth.userId))) {
      return { response: errorResponse(403, 'Only pack managers can manage comments') }
    }
    return { auth, blocksKey: pack.id }
  }
 
  if (!entityId) {
    return { response: errorResponse(400, 'Missing entityId') }
  }
 
  const entity = await loadEntity(docClient, entityId)
  if (!entity) {
    return { response: errorResponse(404, 'Entity not found') }
  }
 
  if (!(await canManageComments(docClient, auth, entity))) {
    return { response: errorResponse(403, 'Only entity managers can manage comments') }
  }
 
  return { auth, blocksKey: entityId }
}
 
/** True when `userId` was blocked from commenting on `blocksKey` (an entity or a pack) by its managers. */
async function isBlockedFromCommenting(docClient, blocksKey, userId) {
  Iif (!process.env.COMMENT_BLOCKS_TABLE_NAME) return false
  const result = await docClient.send(
    new GetCommand({
      TableName: process.env.COMMENT_BLOCKS_TABLE_NAME,
      Key: { entityId: blocksKey, userId }
    })
  )
  return !!result.Item
}
 
module.exports = {
  resolveCommentContext,
  resolveManagerContext,
  canManageComments,
  isPlatformAdminUser,
  isBlockedFromCommenting,
  errorResponse,
  CORS_HEADERS
}