All files / shared activeFlow.js

100% Statements 41/41
94.59% Branches 35/37
100% Functions 9/9
100% Lines 37/37

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                                    70x 70x       70x   42x 42x     70x     70x     70x   70x               1477x 1477x 1362x 1361x     116x       43x   1x 1x   42x               40x 40x                           80x 80x   79x 79x   79x     41x     79x   77x 77x       2x 2x     79x 79x                   2x 2x                       8x     70x                
/**
 * Active flow of a request.
 *
 * The active flow is chosen by the client, per browser tab (it is part of the
 * UI's URL: /flows/:slug/...), and sent on every request in the `X-Flow-Id`
 * header — it is never stored on the user, so two tabs or devices can work in
 * two different flows at the same time.
 *
 * The header is client-controlled: it is only trusted once the caller is an
 * *active* member of that flow. Every reader of the active flow goes through
 * resolveActiveFlow(), so no handler can act on a flow the caller does not
 * belong to (or no longer belongs to, or was only invited to).
 *
 * The membership read is done once per invocation: the result is cached
 * against the event object, and handed to PermissionChecker (see
 * requirePermission.js) so a permission check does not read it again.
 */
 
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, GetCommand } = require('@aws-sdk/lib-dynamodb')
 
// Created on first use: modules that only read the header (and their tests)
// never need a DynamoDB client
let docClient = null
function getDocClient() {
  if (!docClient) docClient = DynamoDBDocumentClient.from(new DynamoDBClient({}))
  return docClient
}
 
const FLOW_ID_HEADER = 'x-flow-id'
/** Error returned when a flow-scoped request has no verified active flow */
const NO_ACTIVE_FLOW_ERROR =
  'No active flow: X-Flow-Id must name a flow you are an active member of'
 
/** event -> Promise<{ flowId, membership } | null> */
const resolutions = new WeakMap()
/** event -> verified active flow id, readable synchronously once resolved */
const resolvedFlowIds = new WeakMap()
 
/**
 * The raw `X-Flow-Id` header (case-insensitive), not yet verified.
 * @param {Object} event - API Gateway event
 * @returns {string|null}
 */
function readFlowIdHeader(event) {
  const headers = event?.headers || {}
  for (const [name, value] of Object.entries(headers)) {
    if (name.toLowerCase() === FLOW_ID_HEADER && typeof value === 'string' && value.trim()) {
      return value.trim()
    }
  }
  return null
}
 
async function loadActiveMembership(userId, flowId) {
  if (!process.env.FLOW_MEMBERSHIPS_TABLE_NAME) {
    // Fail closed: without the table nothing can be verified
    console.error('activeFlow: FLOW_MEMBERSHIPS_TABLE_NAME is not set')
    return null
  }
  const result = await getDocClient().send(
    new GetCommand({
      TableName: process.env.FLOW_MEMBERSHIPS_TABLE_NAME,
      Key: { userId, flowId },
      // A member removed a moment ago must lose access on the very next request
      ConsistentRead: true
    })
  )
  const membership = result.Item
  return membership && membership.status === 'active' ? membership : null
}
 
/**
 * The request's active flow, verified: `{ flowId, membership }` when the
 * caller is an active member of the flow named by `X-Flow-Id`, else null
 * (no header, not a member, invitation not accepted, membership suspended).
 *
 * @param {Object} event - API Gateway event
 * @param {string} [userId] - Caller's user id; defaults to the Cognito
 *   authorizer's `sub` (pass it for endpoints verifying the JWT themselves)
 * @returns {Promise<{flowId: string, membership: Object}|null>}
 */
function resolveActiveFlow(event, userId) {
  const cached = resolutions.get(event)
  if (cached) return cached
 
  const callerId = userId || event?.requestContext?.authorizer?.claims?.sub
  const flowId = readFlowIdHeader(event)
  const resolution =
    !callerId || !flowId
      ? Promise.resolve(null)
      : loadActiveMembership(callerId, flowId).then((membership) =>
          membership ? { flowId, membership } : null
        )
 
  const settled = resolution.then(
    (result) => {
      if (result) resolvedFlowIds.set(event, result.flowId)
      return result
    },
    (error) => {
      // Let a later call retry instead of caching a transient failure
      resolutions.delete(event)
      throw error
    }
  )
  Eif (event && typeof event === 'object') resolutions.set(event, settled)
  return settled
}
 
/**
 * The request's verified active flow id, or null.
 * @param {Object} event - API Gateway event
 * @param {string} [userId] - see resolveActiveFlow
 * @returns {Promise<string|null>}
 */
async function getActiveFlowId(event, userId) {
  const resolved = await resolveActiveFlow(event, userId)
  return resolved ? resolved.flowId : null
}
 
/**
 * Synchronous read of the active flow id already verified during this
 * invocation (null when the handler never resolved it, or it was invalid).
 * For after-the-fact consumers such as usage tracking, which must never
 * attribute usage to a flow the caller merely named in a header.
 * @param {Object} event - API Gateway event
 * @returns {string|null}
 */
function getResolvedActiveFlowId(event) {
  return (event && typeof event === 'object' && resolvedFlowIds.get(event)) || null
}
 
module.exports = {
  FLOW_ID_HEADER,
  NO_ACTIVE_FLOW_ERROR,
  readFlowIdHeader,
  resolveActiveFlow,
  getActiveFlowId,
  getResolvedActiveFlowId
}