You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置AWS Serverless Image Handler仅允许指定尺寸的fit-in格式?

配置AWS Serverless Image Handler仅允许指定尺寸的fit-in请求

可以通过API Gateway路径限制 + Lambda逻辑校验的组合方式实现需求,具体配置步骤如下:

1. 限制API Gateway请求路径

API Gateway作为前端请求入口,直接拦截不符合规则的请求:

  • 创建匹配规则为 /fit-in/{size}/{imageKey} 的API资源路径
  • 对 {size} 参数设置正则验证规则:1500x750|800x400|300x150
    • 操作方式:在API Gateway的资源参数设置中,将size的"正则表达式"字段设为上述值
    • 效果:任何非指定尺寸的请求(如/fit-in/400x500/test.jpg)或其他操作路径(如/crop/300x150/test.jpg)会被API Gateway直接返回400错误,无需进入Lambda处理

2. 修改Lambda函数添加业务校验

即使API Gateway拦截了大部分非法请求,仍需在Lambda层做二次校验,防止绕过API Gateway的直接调用:

关键校验逻辑(以Node.js版本为例)

// 允许的尺寸列表
const ALLOWED_SIZES = ['1500x750', '800x400', '300x150'];

exports.handler = async (event) => {
  // 解析请求路径参数
  const pathParams = event.pathParameters || {};
  const size = pathParams.size;
  const imageKey = pathParams.imageKey;
  
  // 校验操作类型:仅允许fit-in
  const operation = event.requestContext.path.split('/')[1]; // 从路径提取操作
  if (operation !== 'fit-in') {
    return {
      statusCode: 403,
      body: JSON.stringify({ message: '仅支持fit-in操作' })
    };
  }
  
  // 校验尺寸是否在允许列表内
  if (!ALLOWED_SIZES.includes(size)) {
    return {
      statusCode: 403,
      body: JSON.stringify({ message: '不支持该尺寸,请使用1500x750、800x400或300x150' })
    };
  }
  
  // 校验是否存在非法参数(如filters、crop)
  const queryParams = event.queryStringParameters || {};
  const forbiddenParams = Object.keys(queryParams).filter(key => key.includes('filter') || key.includes('crop'));
  if (forbiddenParams.length > 0) {
    return {
      statusCode: 403,
      body: JSON.stringify({ message: '禁止使用filters、crop等操作' })
    };
  }
  
  // 执行原有的图片处理逻辑(省略原有代码)
  // ...
};
  • 说明:上述代码在原有Lambda逻辑前添加三层校验,确保只有符合要求的请求才能进入图片处理流程

3. 强化S3访问权限(可选)

为Lambda函数配置最小权限的IAM角色,仅允许访问目标S3桶的图片资源,避免非法访问其他文件:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "s3:GetObject",
      "Resource": "arn:aws:s3:::your-image-bucket/*"
    }
  ]
}

内容的提问来源于stack exchange,提问作者valeriblack

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 13:32:43