All files / proxy/utils headers.ts

100% Statements 72/72
100% Branches 25/25
100% Functions 11/11
100% Lines 66/66

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    7x 7x   7x   7x                                                         7x   7x                     7x   7x   7x         20x 6x   14x   14x 14x 14x 13x   14x   14x     16x   7x 33x 120x 120x 57x 18x         102x 37x 37x 15x 15x     37x   102x       7x 12x   7x 19x   19x     79x 18x     61x 6x           55x 55x                 19x       102x 53x   49x 94x 12x     37x       79x 10x   69x 136x 8x     61x     7x 180x 164x     16x     7x 180x 180x   180x 93x   87x    
import { CloudFrontHeaders, CloudFrontRequest } from 'aws-lambda'
import { IncomingHttpHeaders, OutgoingHttpHeaders } from 'http'
import { filterCookie } from './cookie'
import { updateCacheControlHeader } from './cache-control'
import { CustomerVariables } from './customer-variables/customer-variables'
import { getPreSharedSecret } from './customer-variables/selectors'
 
const BLACKLISTED_HEADERS = new Set([
  'connection',
  'expect',
  'keep-alive',
  'proxy-authenticate',
  'proxy-authorization',
  'proxy-connection',
  'trailer',
  'upgrade',
  'x-accel-buffering',
  'x-accel-charset',
  'x-accel-limit-rate',
  'x-accel-redirect',
  'x-amzn-auth',
  'x-amzn-cf-billing',
  'x-amzn-cf-id',
  'x-amzn-cf-xff',
  'x-amzn-errortype',
  'x-amzn-fle-profile',
  'x-amzn-header-count',
  'x-amzn-header-order',
  'x-amzn-lambda-integration-tag',
  'x-amzn-requestid',
  'x-cache',
  'x-forwarded-proto',
  'x-real-ip',
  'strict-transport-security',
])
 
const BLACKLISTED_HEADERS_PREFIXES = ['x-edge-', 'x-amz-cf-']
 
const READ_ONLY_RESPONSE_HEADERS = new Set([
  'accept-encoding',
  'content-length',
  'if-modified-since',
  'if-none-match',
  'if-range',
  'if-unmodified-since',
  'transfer-encoding',
  'via',
])
 
const READ_ONLY_REQUEST_HEADERS = new Set(['content-length', 'host', 'transfer-encoding', 'via'])
 
const CACHE_CONTROL_HEADER_NAME = 'cache-control'
 
export async function prepareHeadersForIngressAPI(
  request: CloudFrontRequest,
  variables: CustomerVariables,
  isIngressCall: boolean
): Promise<OutgoingHttpHeaders> {
  if (!isIngressCall) {
    return filterRequestHeaders(request, true)
  }
  const headers = filterRequestHeaders(request)
 
  headers['fpjs-proxy-client-ip'] = request.clientIp
  const preSharedSecret = await getPreSharedSecret(variables)
  if (preSharedSecret) {
    headers['fpjs-proxy-secret'] = preSharedSecret
  }
  headers['fpjs-proxy-forwarded-host'] = getHost(request)
 
  return headers
}
 
export const getHost = (request: CloudFrontRequest) => request.headers['host'][0].value
 
export function filterRequestHeaders(request: CloudFrontRequest, dropCookies = false): OutgoingHttpHeaders {
  return Object.entries(request.headers).reduce((result: { [key: string]: string }, [name, value]) => {
    const headerName = name.toLowerCase()
    if (dropCookies) {
      if (headerName === 'cookie') {
        return result
      }
    }
 
    // Lambda@Edge function can't add read-only headers from a client request to Ingress API request
    if (isHeaderAllowedForRequest(headerName)) {
      let headerValue = value[0].value
      if (headerName === 'cookie') {
        headerValue = headerValue.split(/; */).join('; ')
        headerValue = filterCookie(headerValue, (key) => key === '_iidt')
      }
 
      result[headerName] = headerValue
    }
    return result
  }, {})
}
 
export const updateResponseHeadersForAgentDownload = (headers: IncomingHttpHeaders) =>
  updateResponseHeaders(headers, true)
 
export function updateResponseHeaders(headers: IncomingHttpHeaders, overrideCacheControl = false): CloudFrontHeaders {
  const resultHeaders: CloudFrontHeaders = {}
 
  for (const [key, value] of Object.entries(headers)) {
    // Lambda@Edge function can't add read-only headers to response to CloudFront
    // So, such headers from IngressAPI response are filtered out before return the response to CloudFront
    if (!isHeaderAllowedForResponse(key)) {
      continue
    }
 
    if (overrideCacheControl && key == CACHE_CONTROL_HEADER_NAME && typeof value === 'string') {
      resultHeaders[CACHE_CONTROL_HEADER_NAME] = [
        {
          key: CACHE_CONTROL_HEADER_NAME,
          value: updateCacheControlHeader(value),
        },
      ]
    } else if (value) {
      resultHeaders[key] = [
        {
          key: key,
          value: value.toString(),
        },
      ]
    }
  }
 
  return resultHeaders
}
 
function isHeaderAllowedForRequest(headerName: string) {
  if (READ_ONLY_REQUEST_HEADERS.has(headerName) || BLACKLISTED_HEADERS.has(headerName)) {
    return false
  }
  for (let i = 0; i < BLACKLISTED_HEADERS_PREFIXES.length; i++) {
    if (headerName.startsWith(BLACKLISTED_HEADERS_PREFIXES[i])) {
      return false
    }
  }
  return true
}
 
function isHeaderAllowedForResponse(headerName: string) {
  if (READ_ONLY_RESPONSE_HEADERS.has(headerName) || BLACKLISTED_HEADERS.has(headerName)) {
    return false
  }
  for (let i = 0; i < BLACKLISTED_HEADERS_PREFIXES.length; i++) {
    if (headerName.startsWith(BLACKLISTED_HEADERS_PREFIXES[i])) {
      return false
    }
  }
  return true
}
 
export function getOriginForHeaders({ origin }: CloudFrontRequest) {
  if (origin?.s3) {
    return origin.s3
  }
 
  return origin?.custom
}
 
export function getHeaderValue(request: CloudFrontRequest, name: string) {
  const origin = getOriginForHeaders(request)
  const headers = origin?.customHeaders
 
  if (!headers?.[name]) {
    return null
  }
  return headers[name][0].value
}