AWS CDK 实战:用 CloudFront Functions 在边缘侧改造请求与响应(aws-cdk-examples 之 demo-cloudfront-functions 详解)

原创2026-10-14 18:48:431,927 阅读

AWS CDK 实战:用 CloudFront Functions 在边缘侧改造请求与响应(aws-cdk-examples 之 demo-cloudfront-functions 详解)

本指南基于 aws-cdk-examples 仓库中的 demo-cloudfront-functions 示例,完整讲解如何用 AWS CDK 一次性搭建「S3 静态站点 + CloudFront CDN + 两个 CloudFront Functions」的边缘处理链路。读完本文,你将掌握 CloudFront Functions 的 viewer-request 与 viewer-response 两种事件挂载方式,理解如何在边缘侧实现 URL 重定向、访问控制、请求头/查询串/Cookie 改写与对象级缓存控制,并学会用 CDK 部署、验证与销毁整套基础设施。

示例概览:在 CDN 边缘做"轻量计算"

demo-cloudfront-functions 是一个纯演示用途的项目(README 中明确提示 "This project is intended to be just a sample demonstration. Please, do not use it in production"),它的核心思路是:

  1. 用 S3 Bucket 存放简单的 HTML 文件,作为网站源站;
  2. 用 CloudFront Distribution 对外提供 CDN 分发;
  3. 挂载两个 CloudFront Functions,分别作用于请求阶段和响应阶段,对每个 viewer 请求/响应做轻量级改造。

示例创建的基础设施组件与仓库内对应实现如下:

组件 作用 源码位置
S3 Bucket 承载网站静态文件(index.html、error.html、not-found.html 等) lib/demo-cloudfront-functions-stack.ts
BucketDeployment 把 website/ 目录内容发布到 Bucket 同上
OriginAccessIdentity / OAC 控制 CloudFront 回源 S3 的访问权限 同上
CloudFront Function(RequestFunction) viewer-request 事件:重定向、鉴权、请求头/Cookie 改写 resources/functions/request-function.js
CloudFront Function(ResponseFunction) viewer-response 事件:对象级缓存头与自定义响应头 resources/functions/response-function.js
CloudFront Distribution 对外分发入口,默认根对象 index.html lib/demo-cloudfront-functions-stack.ts

从源码结构看,该项目由三部分构成:bin/(CDK 应用入口)、lib/(基础设施栈定义)、resources/functions/(两个 CloudFront Functions 的 JS 代码),外加 test/ 下的合成(synthesize)测试,体现了"基础设施代码 + 边缘函数代码 + 自动化验证"的完整示例形态。

环境准备与依赖安装

在项目目录下,需要先安装 AWS CDK 工具与项目依赖。README 给出的步骤为:

$ npm install -g aws-cdk
$ npm install

其中第一条命令将 CDK CLI 安装为全局命令,第二条命令安装项目自身的依赖。以仓库当前版本为准,package.json 中声明了核心依赖:aws-cdk-lib(版本 2.262.1)与 constructs,开发依赖包括 aws-cdk(版本 2.1133.0)、typescript、jest 等;脚本方面提供了 build(tsc 编译)、test(jest 运行测试)、watch(tsc 增量编译)与 cdk 命令。

项目根目录的 cdk.json 告诉 CDK Toolkit 如何执行应用,其 app 字段为:

"app": "npx tsc && npx tsx bin/demo-cloudfront-functions.ts"

也就是说,CDK 会先通过 tsc 编译 TypeScript,再用 tsx 直接运行 bin/demo-cloudfront-functions.ts。入口文件本身非常简单:创建 cdk.App 后实例化 DemoCloudfrontFunctionsStack:

const app = new cdk.App();
new DemoCloudfrontFunctionsStack(app, 'DemoCloudfrontFunctionsStack', {});

部署解决方案

依赖安装完成后,执行:

$ cdk deploy --all

注意:部署命令执行完毕后,控制台会输出类似如下的结果(Output): DemoCloudfrontFunctionsStack.DistributionDomainName = xxxxxxxx.cloudfront.net 该 URL 即 CloudFront 分配域名,后续测试网站都通过它访问。

这个输出对应栈末尾定义的 cdk.CfnOutput:

new cdk.CfnOutput(this, 'DistributionDomainName', {
  value: distribution.domainName,
});

因此拿到 DistributionDomainName 这个输出项,就拿到了测试所需的访问入口。

核心源码解析:基础设施栈

整个基础设施由 lib/demo-cloudfront-functions-stack.ts 中的 DemoCloudfrontFunctionsStack 定义,按顺序可分为五步。

1. 创建并加固 S3 网站 Bucket

const bucket = new Bucket(this, 'WebsiteBucket', {
  encryption: BucketEncryption.S3_MANAGED,        // 使用 S3 托管密钥加密
  versioned: true,                                 // 开启版本化
  enforceSSL: true,                                // 强制 HTTPS 访问
  blockPublicAccess: BlockPublicAccess.BLOCK_ALL,  // 彻底屏蔽公共访问
  removalPolicy: RemovalPolicy.DESTROY,            // 栈销毁时删除 Bucket
  autoDeleteObjects: true                          // 删除前自动清空对象
});

每个配置项都值得展开说明:

  • BucketEncryption.S3_MANAGED:使用 S3 托管密钥(SSE-S3)对对象进行服务端加密;
  • versioned: true:开启版本控制,便于回滚与审计;
  • enforceSSL: true:拒绝非 HTTPS 的访问请求;
  • BlockPublicAccess.BLOCK_ALL:从 Account 与 Bucket 两层彻底禁止公共读写,是静态站点的安全基线——结合下面的 Origin Access Identity/OAC 实现"私有 Bucket + CDN 回源"的经典模式;
  • RemovalPolicy.DESTROY 配合 autoDeleteObjects: true:栈销毁时自动清空并删除 Bucket,避免演示项目残留资源与费用。

2. 发布网站文件

new BucketDeployment(this, 'WebsiteFiles', {
  destinationBucket: bucket,
  sources: [Source.asset('./website')],
  contentType: 'text/html',
  retainOnDelete: false,
});

BucketDeployment 会把本地 website 目录下的文件上传到 Bucket。仓库中该目录包含四个 HTML 文件:根路径的 index.html(正文为 It works!)、error.html(Sorry, an error occurred)、not-found.html(The page could not be found.)以及 subdir/test.html(This is a test file for you)。其中 subdir/test.html 是后面重定向测试的落点。

3. 配置回源访问权限

const cloudfrontOAI = new OriginAccessIdentity(this, 'cloudfront-OAI', {
  comment: `OAI for ${id}`
});
bucket.grantRead(cloudfrontOAI);

示例先创建一个 Origin Access Identity 并向其授予 Bucket 读权限;而行为(behavior)中实际使用的是 S3BucketOrigin.withOriginAccessControl(bucket)(见下文),即通过 Origin Access Control(OAC)回源。两者并存属于示例代码中的过渡写法,从代码结构可以推断:OAI 的 grantRead 与 OAC 的授权在 CDK 中都是"让 CloudFront 以最小权限读取私有 S3"的常用手段,读者在生产环境中只需保留其中一种即可。

4. 定义两个 CloudFront Functions

const requestFunction = new Function(this, 'RequestFunction', {
  functionName: 'RequestFunction',
  runtime: FunctionRuntime.JS_2_0,
  code: FunctionCode.fromFile({
    filePath: './resources/functions/request-function.js'
  })
});

const responseFunction = new Function(this, 'ResponseFunction', {
  functionName: 'ResponseFunction',
  runtime: FunctionRuntime.JS_2_0,
  code: FunctionCode.fromFile({
    filePath: './resources/functions/response-function.js'
  })
});

要点:

  • runtime: FunctionRuntime.JS_2_0 指定 CloudFront Functions 的 JavaScript 运行时;cdk.json 的 context 中也有 @aws-cdk/aws-cloudfront:defaultFunctionRuntimeV2_0: true 与之呼应;
  • 函数代码通过 FunctionCode.fromFile 直接读取本地 JS 文件,由 CDK 打包为 CloudFront Function 资源;
  • 函数代码的核心逻辑详见后文两节。

5. 组装 Distribution 与行为

const defaultBehavior = {
  origin: S3BucketOrigin.withOriginAccessControl(bucket),
  compress: true,
  allowedMethods: AllowedMethods.ALLOW_ALL,
  functionAssociations: [
    { function: requestFunction,  eventType: FunctionEventType.VIEWER_REQUEST  },
    { function: responseFunction, eventType: FunctionEventType.VIEWER_RESPONSE }
  ]
};

const distribution = new Distribution(this, 'SiteDistribution', {
  comment: 'CloudFront Functions example',
  defaultRootObject: 'index.html',
  defaultBehavior: defaultBehavior,
});

这是全示例的关键所在:

  • 事件类型:VIEWER_REQUEST 表示在 CloudFront 收到 viewer 请求、尚未访问缓存/回源前执行;VIEWER_RESPONSE 表示在向 viewer 返回响应前执行。一个行为可以同时挂多个函数、对应不同事件;
  • 默认根对象:defaultRootObject: 'index.html' 让根路径 / 直接解析到 index.html;
  • 回源:S3BucketOrigin.withOriginAccessControl(bucket) 使用 OAC 作为 S3 源站;
  • 压缩与请求方法:开启 compress: true,允许所有 HTTP 方法(AllowedMethods.ALLOW_ALL)。

请求函数:在 viewer-request 阶段做边缘改造

request-function.js 定义了 handler(event),按顺序处理五类逻辑,最终返回修改后的 event.request。完整的处理规则如下:

1. 查询字符串清理

if (event.request.uri === '/' && event.request.querystring !== {}) {
    event.request.querystring = {};
}

当访问根路径且携带查询字符串时,将查询串重置为空对象。从代码写法看,示例用 event.request.querystring !== {} 作判断条件,这在 JavaScript 中属于对象引用比较(每个 {} 字面量都是新对象,比较结果恒为真),可以推断作者的意图是"只要存在查询串就清空它"——实际效果即:对根路径的访问一律剥离查询参数,让带 ?foo=bar 的请求与不带参数的请求命中同一个缓存对象。

2. 基于 URI 列表的 308 永久重定向

const domain = event.request.headers.host.value;
const redirects = {
    '/test.html': `https://${domain}/subdir/test.html`,
    '/test':      `https://${domain}/subdir/test.html`
}
const redirectUrl = redirects[event.request.uri];

if (redirectUrl) {
    return {
        statusCode: 308,
        statusDescription: 'Permanent Redirect',
        headers: { 'location': { value: redirectUrl } }
    };
}

读取请求头中的 host 动态拼出目标 URL,把 /test.html 与 /test 两个路径统一 308 重定向到 /subdir/test.html,并携带 location 响应头。308 表示"永久重定向且方法/主体不变",是 CloudFront Functions 返回自定义响应的常见形态。

3. URL 校验与访问控制

if (new RegExp('^/invalid').test(event.request.uri)) {
    return {
        statusCode: 403,
        statusDescription: 'Forbidden',
    };
}

凡是以 /invalid 开头的路径,直接返回 403 Forbidden 且不携带响应体——这是"在边缘层拦截非法路径"的最小实现。

4. 请求头校验与改写

if (event.request.headers['x-correlation-id'] && event.request.headers['x-correlation-id'].value === 'abcde') {
    event.request.headers['x-correlation-id'].value = 'random-correlation-id';
}

当请求头 x-correlation-id 的值恰为 abcde 时,将其改写为 random-correlation-id,演示了边缘层对请求头的条件改写能力。

5. Cookie 校验与注入

if (event.request.cookies['foo'] && event.request.cookies['foo'].value === 'bar') {
    event.request.cookies['should-cache'] = {value: 'true'}
}

当 Cookie foo=bar 存在时,向请求注入新的 Cookie should-cache=true,演示了基于 Cookie 条件注入的能力(可用于后续行为级缓存策略的决策依据)。

响应函数:在 viewer-response 阶段改造响应

response-function.js 定义了 handler(event),开头通过 console.log(event) 打印完整事件——CloudFront Functions 的日志会进入 CloudWatch Logs,这也是 README 提到"部分规则通过 CloudWatch Logs 验证"的原因。核心逻辑是对 test.html 做对象级缓存与响应头控制:

if (event.request.uri.endsWith('test.html')) {
    event.response.headers['cache-control'] = { value: 'max-age=60' }
    event.response.headers['x-test-header'] = { value: 'this is a test' }
}
return event.response;

含义:

  • 对任何以 test.html 结尾的 URI,在响应中写入 cache-control: max-age=60,即告诉 viewer/下游缓存该对象最多缓存 60 秒——这是"按对象粒度在边缘覆盖缓存策略"的典型写法(注意 CloudFront Functions 的 viewer-response 阶段设置在响应头里);
  • 同时写入自定义响应头 x-test-header: this is a test,可用于调试或标识响应来源。

端到端测试验证

要开始测试,需要拿到部署输出的 DistributionDomainName 对应的分配 URL,并使用能分析网络请求/响应的工具(如 Chrome 开发者工具、curl、wget 等)。以下五组用例均来自 README,且每组都能在请求函数/响应函数源码中找到对应规则。

测试根路径

  1. 访问分配的基础 URL(https://xxxxxxxx.cloudfront.net/)
  2. 返回 200
  3. 响应体包含文本 It works!

测试带查询字符串的根路径

  1. 在基础 URL 末尾追加 ?foo=bar
  2. 返回 200
  3. 响应体包含文本 It works!

对应 request-function 中"根路径剥离查询串"的逻辑:?foo=bar 被清空,因此仍命中 index.html 并返回 200。

测试重定向路由

  1. 在基础 URL 末尾追加 /test 或 /test.html
  2. 返回 308(永久重定向)
  3. URL 变为 /subdir/test.html
  4. 再次返回 200
  5. 响应体包含文本 This is a test file for you

对应 request-function 的 308 重定向规则与 response-function 的 test.html 响应头规则:/test 与 /test.html 先被 308 跳转到 subdir/test.html,随后该文件以 200 返回,并附带 cache-control: max-age=60 与 x-test-header 响应头。

测试非法路由

  1. 在基础 URL 末尾追加 /invalid
  2. 返回 403
  3. 无任何响应体

对应 request-function 中 ^/invalid 正则的拦截规则。

其他测试用例

除了上述路径级用例,请求函数与响应函数还包含更多处理规则,可以阅读 request-function.js 与 response-function.js 深入探索,例如:

  • 请求头 x-correlation-id 值为 abcde 时被改写为 random-correlation-id;
  • Cookie foo=bar 时注入 should-cache=true;
  • 响应函数为 test.html 写入 cache-control 与 x-test-header。

其中部分规则由于其性质(日志、请求/响应头),需要通过 CloudWatch Logs 与 X-Ray 进行观测验证——例如 response-function 中 console.log(event) 产生的日志可在 CloudWatch Logs 中查看完整事件结构。

单元测试:验证基础设施合成结果

示例还附带一个基于 aws-cdk-lib/assertions 的合成测试 test/demo-cloudfront-functions.test.ts,通过 Template.fromStack 对生成的 CloudFormation 模板做断言:

template.resourceCountIs('AWS::S3::Bucket', 1);
template.resourceCountIs('AWS::CloudFront::Function', 2);
template.resourcePropertiesCountIs('AWS::CloudFront::Function', Match.objectLike({
  "Name": "RequestFunction",
}), 1);
template.resourcePropertiesCountIs('AWS::CloudFront::Function', Match.objectLike({
  "Name": "ResponseFunction",
}), 1);
template.resourcePropertiesCountIs('AWS::CloudFront::Distribution', {
  "DistributionConfig": Match.objectLike({
    "DefaultCacheBehavior": Match.objectLike({
      "FunctionAssociations": [
        { "EventType": "viewer-request",  "FunctionARN": Match.anyValue() },
        { "EventType": "viewer-response", "FunctionARN": Match.anyValue() }
      ]
    })
  })
}, 1);

测试验证了四项关键事实:

  1. 恰好创建 1 个 S3 Bucket;
  2. 恰好创建 2 个 CloudFront Function(RequestFunction 与 ResponseFunction 各一个);
  3. Distribution 的默认缓存行为中,viewer-request 与 viewer-response 两个事件类型都绑定了函数。

运行方式:

$ npm test

这类合成测试无需真实部署 AWS 资源即可校验基础设施定义,是 CDK 项目持续集成的常见手段。

销毁部署

测试完成后,销毁整个部署以清理资源:

$ cdk destroy --all

得益于栈中 RemovalPolicy.DESTROY 与 autoDeleteObjects: true 的配置,S3 Bucket 及其中的对象会在销毁时被一并清理,避免遗留费用。

小结与注意事项

本示例用约百行 CDK 代码与两个轻量 JS 函数,完整演示了"私有 S3 源站 + CloudFront CDN + 边缘函数"的经典链路:viewer-request 阶段负责查询串清理、308 重定向、非法路径拦截、请求头与 Cookie 改写;viewer-response 阶段负责对象级缓存控制与自定义响应头;合成测试则保证了基础设施定义的可验证性。

需要特别强调的是:该示例明确声明仅用于演示,不应直接用于生产环境。若要在生产中使用,从源码结构看至少需要考虑:统一 OAI/OAC 单一回源授权方式、补充自定义域名与证书(当前仅使用默认的 *.cloudfront.net 域名)、细化缓存与安全策略、为边缘函数增加版本管理与监控告警等。但作为理解 CloudFront Functions 两种事件类型与 CDK 编排方式的入门范例,demo-cloudfront-functions 是一个结构清晰、可一键部署、可逐步验证的绝佳起点。

登录后查看全文
aws-cdk-examples