All files / src/handlers handleIngressAPI.ts

68.29% Statements 28/41
50% Branches 8/16
66.66% Functions 4/6
67.5% Lines 27/40

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                            7x     7x 7x 7x 7x 7x 7x 7x 1x   6x   7x   7x 7x                                                             3x 3x 3x   3x 3x   3x 3x               10x 3x 3x   3x       7x 7x   7x      
import { IntegrationEnv, isOpenClientResponseEnabled, isProxySecretSet } from '../env'
import {
  addProxyIntegrationHeaders,
  addTrafficMonitoringSearchParamsForVisitorIdRequest,
  createErrorResponseForIngress,
  createFallbackErrorResponse,
} from '../utils'
import { getFilteredCookies } from '../utils/cookie'
import { processOpenClientResponse } from '../utils/processOpenClientResponse'
import { cloneFastlyResponse } from '../utils/cloneFastlyResponse'
import { getIngressBackendByRegion } from '../utils/getIngressBackendByRegion'
import { CacheOverride } from 'fastly:cache-override'
 
async function makeIngressRequest(receivedRequest: Request, env: IntegrationEnv) {
  Iif (!isProxySecretSet) {
    console.log("PROXY_SECRET is not set in the integration's Secret store, your integration is not working correctly.")
  }
  const url = new URL(receivedRequest.url)
  url.pathname = ''
  addTrafficMonitoringSearchParamsForVisitorIdRequest(url)
  const oldCookieValue = receivedRequest.headers.get('cookie')
  const newCookieValue = getFilteredCookies(oldCookieValue, (key) => key === '_iidt')
  const request = new Request(url, receivedRequest as RequestInit)
  if (newCookieValue) {
    request.headers.set('cookie', newCookieValue)
  } else {
    request.headers.delete('cookie')
  }
  addProxyIntegrationHeaders(request.headers, receivedRequest.url, env)
 
  console.log(`sending ingress request to ${url.toString()}...`)
  const response = await fetch(request, { backend: getIngressBackendByRegion(url) })
 
  if (!isOpenClientResponseEnabled(env)) {
    console.log(
      "Open client response plugins are disabled. Set OPEN_CLIENT_RESPONSE_PLUGINS_ENABLED to `true` in your proxy integration's Config store to enable them."
    )
    return response
  }
 
  console.log('Plugin system for Open Client Response is enabled')
  if (response.status < 200 || response.status > 299) {
    console.log(
      `Response status is non-successful (HTTP ${response.status}). Skipping plugins and returning the response.`
    )
    return response
  }
 
  const bodyBytes = await response.arrayBuffer()
  Promise.resolve().then(() => {
    processOpenClientResponse(bodyBytes, response, env).catch((e) =>
      console.error(
        'Failed to parse identification response. Make sure Open Client Response is enabled for your Fingerprint workspace: ',
        e
      )
    )
  })
 
  return cloneFastlyResponse(bodyBytes, response)
}
 
function makeCacheEndpointRequest(receivedRequest: Request, routeMatches: RegExpMatchArray | undefined) {
  const url = new URL(receivedRequest.url)
  const pathname = routeMatches ? routeMatches[1] : undefined
  url.pathname = pathname ?? ''
 
  const request = new Request(url, receivedRequest as RequestInit)
  request.headers.delete('Cookie')
 
  console.log(`sending cache request to ${url}...`)
  return fetch(request, { backend: getIngressBackendByRegion(url), cacheOverride: new CacheOverride('pass') })
}
 
export async function handleIngressAPI(
  request: Request,
  env: IntegrationEnv,
  routeMatches: RegExpMatchArray | undefined
) {
  if (request.method === 'GET') {
    try {
      return await makeCacheEndpointRequest(request, routeMatches)
    } catch (e) {
      return createFallbackErrorResponse(request, e)
    }
  }
 
  try {
    return await makeIngressRequest(request, env)
  } catch (e) {
    return createErrorResponseForIngress(request, e)
  }
}