All files / admin decide-appeal.js

98.91% Statements 91/92
92.85% Branches 52/56
100% Functions 6/6
100% Lines 82/82

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                                                  1x             1x       1x 1x                   1x         1x   1x 1x   1x         21x             12x 12x     12x               6x 6x 6x 6x 6x   5x 5x 5x     6x     6x 2x 2x 2x   6x 6x 1x 1x 1x   6x 5x                                       3x   3x 4x                         4x 4x     3x 3x 4x 4x                               2x   2x     2x         2x           1x 21x   21x 21x   1x   20x 20x   14x           14x 14x 13x   12x   12x   12x 12x 12x 6x 6x 1x               12x 3x     11x                 11x                                 11x 11x 11x 10x                       10x     11x 11x   2x 1x   9x   9x             2x 2x      
/**
 * Decide an Appeal (Platform Admin) Lambda
 * POST /v1/platform-admin/appeals/decision
 *
 * Requires `isPlatformAdmin: true`. Answers an appeal of a moderation decision
 * (content-reports/appeal.js), with an optional note to the appellant:
 * - `upheld`: the decision stands
 * - `overturned`: the decision is undone.
 *   - An author's appeal: the decision's strike is taken off, and its
 *     sanction lifted when it is still the one in force (a restriction with
 *     the same end, the ban it started, whose account is enabled again in
 *     Cognito). Removed content is not restored: the author may post it again.
 *   - A reporter's appeal of a dismissal: every report the decision closed
 *     is open again, keeping the dismissal as `previousDecision`, for an admin
 *     to decide anew on the Reports tab.
 * The appellant is notified either way.
 *
 * Retry-safe: the Cognito account and the reports are put back first (both
 * idempotent), then one transaction, conditioned on the appeal still being
 * open, closes it, lifts the sanction and writes the notification
 * (`409 APPEAL_DECIDED` for a second admin).
 *
 * @implements UC-REPORT-010.1
 */
 
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const {
  DynamoDBDocumentClient,
  GetCommand,
  QueryCommand,
  TransactWriteCommand,
  UpdateCommand
} = require('@aws-sdk/lib-dynamodb')
const {
  CognitoIdentityProviderClient,
  AdminEnableUserCommand
} = require('@aws-sdk/client-cognito-identity-provider')
const { requirePlatformAdmin } = require('../utils/requirePlatformAdmin')
const {
  REPORT_LIST_KEY,
  REPORT_STATUS,
  APPEAL_LIST_KEY,
  APPEAL_CLOSED_LIST_KEY,
  APPEAL_ROLE,
  APPEAL_STATUS,
  validateAppealDecisionInput,
  reportExcerpt
} = require('../utils/contentReports')
const {
  NOTIFICATION_TYPE,
  buildNotificationWrites,
  pushNotification
} = require('../utils/notifications')
 
const docClient = DynamoDBDocumentClient.from(new DynamoDBClient({}))
const cognitoClient = new CognitoIdentityProviderClient({})
 
const corsHeaders = {
  'Content-Type': 'application/json',
  'Access-Control-Allow-Origin': '*'
}
 
const respond = (statusCode, body) => ({
  statusCode,
  headers: corsHeaders,
  body: JSON.stringify(body)
})
 
async function getUser(userId) {
  Iif (!userId) return null
  const result = await docClient.send(
    new GetCommand({ TableName: process.env.USERS_TABLE_NAME, Key: { id: userId } })
  )
  return result.Item || null
}
 
/**
 * What undoing the decision changes on its author's row, or null when nothing
 * is left to change. A sanction decided since is not this decision's to lift.
 */
function buildSanctionUndo(user, decision) {
  const removes = []
  const conditions = ['attribute_exists(id)']
  const values = {}
  const strikeIndex = Array.isArray(user.strikes) ? user.strikes.indexOf(decision.decidedAt) : -1
  if (strikeIndex >= 0) {
    // Strikes are only ever appended: the index stays right until the write
    removes.push(`strikes[${strikeIndex}]`)
    conditions.push(`strikes[${strikeIndex}] = :strike`)
    values[':strike'] = decision.decidedAt
  }
  const unrestrict =
    decision.sanction === 'restriction' &&
    !!decision.restrictedUntil &&
    user.restrictedUntil === decision.restrictedUntil
  if (unrestrict) {
    removes.push('restrictedUntil')
    conditions.push('restrictedUntil = :until')
    values[':until'] = decision.restrictedUntil
  }
  const unban = decision.sanction === 'ban' && user.bannedAt === decision.decidedAt
  if (unban) {
    removes.push('bannedAt')
    conditions.push('bannedAt = :bannedAt')
    values[':bannedAt'] = decision.decidedAt
  }
  if (removes.length === 0) return null
  return {
    unban,
    sanctionLifted: unrestrict || unban,
    write: {
      Update: {
        TableName: process.env.USERS_TABLE_NAME,
        Key: { id: user.id },
        UpdateExpression: `REMOVE ${removes.join(', ')}`,
        ConditionExpression: conditions.join(' AND '),
        ExpressionAttributeValues: values
      }
    }
  }
}
 
/**
 * Opens again the reports the dismissal closed. Each one is conditioned on
 * still carrying that decision, so sending the request again changes nothing.
 */
async function reopenReports(appeal) {
  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': appeal.targetKey,
          ':decisionId': appeal.decisionId
        },
        ExclusiveStartKey
      })
    )
    reports.push(...(page.Items || []))
    ExclusiveStartKey = page.LastEvaluatedKey
  } while (ExclusiveStartKey)
 
  let reopened = 0
  for (const report of reports) {
    try {
      await docClient.send(
        new UpdateCommand({
          TableName: process.env.CONTENT_REPORTS_TABLE_NAME,
          Key: { targetKey: report.targetKey, reporterId: report.reporterId },
          UpdateExpression:
            'SET listKey = :open, #status = :status, previousDecision = :previous REMOVE #decision',
          ConditionExpression: '#decision.#id = :decisionId',
          ExpressionAttributeNames: { '#status': 'status', '#decision': 'decision', '#id': 'id' },
          ExpressionAttributeValues: {
            ':open': REPORT_LIST_KEY,
            ':status': REPORT_STATUS.OPEN,
            ':decisionId': appeal.decisionId,
            ':previous': report.decision
          }
        })
      )
      reopened += 1
    } catch (error) {
      if (error.name !== 'ConditionalCheckFailedException') throw error
    }
  }
  return reopened
}
 
/** Whether the appeal itself, the transaction's first write, was closed meanwhile. */
function isAppealClosedMeanwhile(error) {
  return (
    error.name === 'TransactionCanceledException' &&
    error.CancellationReasons?.[0]?.Code === 'ConditionalCheckFailed'
  )
}
 
exports.handler = requirePlatformAdmin(async (event) => {
  try {
    let payload
    try {
      payload = JSON.parse(event.body || '{}')
    } catch {
      return respond(400, { error: 'Invalid JSON body' })
    }
    const input = validateAppealDecisionInput(payload)
    if (!input.valid) return respond(400, { error: input.error })
 
    const result = await docClient.send(
      new GetCommand({
        TableName: process.env.MODERATION_APPEALS_TABLE_NAME,
        Key: { decisionId: input.decisionId, appellantId: input.appellantId }
      })
    )
    const appeal = result.Item
    if (!appeal) return respond(404, { error: 'Appeal not found' })
    if (appeal.listKey !== APPEAL_LIST_KEY) return respond(409, { error: 'APPEAL_DECIDED' })
 
    const overturned = input.outcome === APPEAL_STATUS.OVERTURNED
    // A deleted account has nobody left to tell, nor any sanction to lift
    const appellant = await getUser(appeal.appellantId)
 
    let undo = null
    let reopened = 0
    if (overturned && appeal.role === APPEAL_ROLE.AUTHOR && appellant) {
      undo = buildSanctionUndo(appellant, appeal.decision)
      if (undo?.unban) {
        await cognitoClient.send(
          new AdminEnableUserCommand({
            UserPoolId: process.env.COGNITO_USER_POOL_ID,
            Username: appellant.id
          })
        )
      }
    }
    if (overturned && appeal.role === APPEAL_ROLE.REPORTER) {
      reopened = await reopenReports(appeal)
    }
 
    const appealDecision = {
      outcome: input.outcome,
      note: input.note,
      sanctionLifted: !!undo?.sanctionLifted,
      reopened,
      decidedBy: event.requestContext.authorizer.claims.sub,
      decidedAt: new Date().toISOString()
    }
 
    const writes = [
      {
        Update: {
          TableName: process.env.MODERATION_APPEALS_TABLE_NAME,
          Key: { decisionId: appeal.decisionId, appellantId: appeal.appellantId },
          UpdateExpression: 'SET #status = :status, listKey = :closed, appealDecision = :decision',
          ConditionExpression: 'listKey = :open',
          ExpressionAttributeNames: { '#status': 'status' },
          ExpressionAttributeValues: {
            ':status': input.outcome,
            ':closed': APPEAL_CLOSED_LIST_KEY,
            ':open': APPEAL_LIST_KEY,
            ':decision': appealDecision
          }
        }
      }
    ]
    if (undo) writes.push(undo.write)
    let told = null
    if (appellant) {
      told = buildNotificationWrites(appellant.id, {
        type: NOTIFICATION_TYPE.APPEAL_DECIDED,
        data: {
          role: appeal.role,
          outcome: input.outcome,
          targetType: appeal.targetType,
          contentExcerpt: reportExcerpt(appeal),
          ...(appeal.snapshot?.name !== undefined && { packName: appeal.snapshot.name }),
          sanctionLifted: appealDecision.sanctionLifted,
          note: input.note
        }
      })
      writes.push(...told.writes)
    }
 
    try {
      await docClient.send(new TransactWriteCommand({ TransactItems: writes }))
    } catch (error) {
      if (isAppealClosedMeanwhile(error)) return respond(409, { error: 'APPEAL_DECIDED' })
      throw error
    }
    if (told) await pushNotification(appellant.id, told.notification)
 
    return respond(200, {
      decisionId: appeal.decisionId,
      appellantId: appeal.appellantId,
      status: input.outcome,
      appealDecision
    })
  } catch (error) {
    console.error('Error deciding appeal:', error)
    return respond(500, { error: 'Failed to decide the appeal' })
  }
})