All files / content-reports appeal.js

100% Statements 50/50
84.37% Branches 27/32
100% Functions 6/6
100% Lines 44/44

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                                        1x 1x 1x               1x   1x   1x         17x               10x   10x 11x                   11x 11x   10x         9x 9x 5x   4x   3x   1x   3x     1x 17x   17x 17x     16x 16x   1x   15x 15x   10x 10x 10x     7x 6x 6x 1x     5x                                   5x 5x               2x 1x     3x   1x 1x      
/**
 * Appeal a Moderation Decision Lambda
 * POST /v1/content-reports/appeals
 *
 * A signed-in user contests a platform admin's decision on reports
 * (admin/decide-content-report.js), within six months, once: the DSA's
 * internal complaint handling (Art. 20). Who may appeal:
 * - the author of actioned content: the action and the sanction
 * - a reporter whose report was dismissed: the dismissal
 * Anybody else is told the decision does not exist (404), as for an unknown
 * one. The appeal lands on the Administration page's Appeals tab
 * (admin/list-appeals.js), and a restriction does not prevent it.
 *
 * Body: `{ targetKey, decisionId, message }`, both ids from the notification
 * that told the user about the decision. Appealing twice is idempotent: the
 * first appeal stands (200 with `alreadyAppealed: true`).
 *
 * @implements UC-REPORT-009.1
 */
 
const { randomUUID } = require('crypto')
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, PutCommand, QueryCommand } = require('@aws-sdk/lib-dynamodb')
const {
  REPORT_STATUS,
  APPEAL_LIST_KEY,
  APPEAL_ROLE,
  APPEAL_STATUS,
  APPEAL_WINDOW_MS,
  validateAppealInput
} = require('../utils/contentReports')
 
const docClient = DynamoDBDocumentClient.from(new DynamoDBClient({}))
 
const corsHeaders = {
  'Content-Type': 'application/json',
  'Access-Control-Allow-Origin': '*'
}
 
const respond = (statusCode, body) => ({
  statusCode,
  headers: corsHeaders,
  body: JSON.stringify(body)
})
 
/** The reports the decision closed: one partition, filtered on its id. */
async function listDecisionReports(targetKey, decisionId) {
  const reports = []
  let ExclusiveStartKey
  do {
    const page = await docClient.send(
      new QueryCommand({
        TableName: process.env.CONTENT_REPORTS_TABLE_NAME,
        KeyConditionExpression: 'targetKey = :targetKey',
        FilterExpression: '#decision.#id = :decisionId',
        ExpressionAttributeNames: { '#decision': 'decision', '#id': 'id' },
        ExpressionAttributeValues: { ':targetKey': targetKey, ':decisionId': decisionId },
        ExclusiveStartKey
      })
    )
    reports.push(...(page.Items || []))
    ExclusiveStartKey = page.LastEvaluatedKey
  } while (ExclusiveStartKey)
  return reports
}
 
/** The appellant's side of the decision, or null when they have no say in it. */
function appellantRole(reports, userId) {
  const { outcome } = reports[0].decision
  if (outcome === REPORT_STATUS.ACTIONED && reports[0].reportedUserId === userId) {
    return APPEAL_ROLE.AUTHOR
  }
  if (
    outcome === REPORT_STATUS.DISMISSED &&
    reports.some((report) => report.reporterId === userId)
  ) {
    return APPEAL_ROLE.REPORTER
  }
  return null
}
 
exports.handler = async (event) => {
  try {
    // An appeal is a person's: an API key cannot file one
    const userId = event.requestContext?.authorizer?.claims?.sub
    if (!userId) return respond(401, { error: 'Unauthorized' })
 
    let payload
    try {
      payload = JSON.parse(event.body || '{}')
    } catch {
      return respond(400, { error: 'Invalid JSON body' })
    }
    const input = validateAppealInput(payload)
    if (!input.valid) return respond(400, { error: input.error })
 
    const reports = await listDecisionReports(input.targetKey, input.decisionId)
    const role = reports.length > 0 ? appellantRole(reports, userId) : null
    if (!role) return respond(404, { error: 'Decision not found' })
 
    // The reporter's own report, or the first one: they all carry the decision
    const report = reports.find((row) => row.reporterId === userId) || reports[0]
    const { decision } = report
    if (Date.now() - Date.parse(decision.decidedAt) > APPEAL_WINDOW_MS) {
      return respond(400, { error: 'APPEAL_EXPIRED' })
    }
 
    const appeal = {
      decisionId: input.decisionId,
      appellantId: userId,
      id: randomUUID(),
      listKey: APPEAL_LIST_KEY,
      status: APPEAL_STATUS.OPEN,
      role,
      message: input.message,
      targetKey: input.targetKey,
      targetType: report.targetType,
      target: report.target || {},
      reason: report.reason,
      reportedUserId: report.reportedUserId || null,
      snapshot: report.snapshot || {},
      decision,
      createdAt: new Date().toISOString()
    }
 
    try {
      await docClient.send(
        new PutCommand({
          TableName: process.env.MODERATION_APPEALS_TABLE_NAME,
          Item: appeal,
          ConditionExpression: 'attribute_not_exists(decisionId)'
        })
      )
    } catch (error) {
      if (error.name !== 'ConditionalCheckFailedException') throw error
      return respond(200, { alreadyAppealed: true })
    }
 
    return respond(201, { id: appeal.id, alreadyAppealed: false })
  } catch (error) {
    console.error('[content-reports/appeal] Exception:', error.message, error.stack)
    return respond(500, { error: 'Failed to appeal the decision' })
  }
}