How can I change status code in viewer-response Cloudfront event?

Viewed 1140

I want to secure Cloudfront response using S3 object metadata and some role data in DB (or some remote service), specif for current user. I think I should use viewer-response event here, to have access to S3 data and user data together. I try to set status and statusDescription in response object, but it does not work for viewer-response event, works for all other events. Setting headers still works.

exports.handler = async (event) => {

  const response = event.Records[0].cf.response;
  const request = event.Records[0].cf.request;
  const isUserAllowed = await allowedByTokenAndDb(request);
  const isS3ObjectAllowed = response.headers['x-amz-meta-isSecure'][0].value === 'true';

  if (!isUserAllowed || !isS3ObjectAllowed) {
    response.status = '403'; // does not work
    response.statusDescription = 'Nothing';
  }

  response.headers['X-Powered-By'] = [{  // works, header will be added
    key: 'X-Powered-By',
    value: 'lol',
  }] 

  return response;
}

Is there any way to make viewer-response return another status? AWS documentation does not tell that it is possible or not. Maybe there is another solution?

3 Answers

According to the documentation, it looks like you can only change responses in viewer-request, origin-request, and origin-response event handlers. This page doesn't explicitly state you CAN'T change the response in viewer-response event handler, but it does imply that since it only talks about the other three as being supported: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-updating-http-responses.html

Like you, I also couldn't get it to work, but I ended up using origin-response to meet my needs.

Follow official documents: Restrictions on edge functions

CloudFront does not invoke edge functions for viewer response events when the origin returns HTTP status code 400 or higher.

Hence, the function is not working.

Related