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

如何修复Veracode扫描出的fetch函数低级别CWE 201漏洞?

Veracode扫描出fetch函数低级别漏洞的修复方案

Veracode扫描显示以下fetch代码存在低级别漏洞,请问最佳修复方案是什么?

const response = await fetch(url, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },

常见低危漏洞点及修复方案

Veracode针对fetch报的低级别漏洞,通常集中在URL合法性校验、错误处理缺失、安全头不足这几个核心场景,以下是对应修复方案:

1. 校验目标URL合法性(防范SSRF/跳转攻击)

如果url是用户可控或动态生成的,必须限制其协议、域名在可信范围内,避免被恶意利用发起未授权请求:

// 定义业务可信域名列表
const allowedDomains = ['your-trusted-domain.com', 'api.your-trusted-domain.com'];
const urlObj = new URL(url);

// 强制校验协议为HTTPS,且域名在可信列表内
if (urlObj.protocol !== 'https:' || !allowedDomains.includes(urlObj.hostname)) {
  throw new Error('Invalid or untrusted request target');
}

// 校验通过后发起请求
const response = await fetch(urlObj.toString(), {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  // 补充其他必要配置(如body、credentials等)
});

2. 完善请求错误处理逻辑

fetch仅在网络层面失败时才会抛出异常,HTTP错误状态码(如400、500)不会触发reject,必须手动校验响应状态:

const response = await fetch(url, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  // 补充其他必要配置
});

// 主动校验响应状态
if (!response.ok) {
  // 可根据业务需求做日志记录、错误抛出或降级处理
  throw new Error(`Request failed with status code: ${response.status}`);
}

// 正常处理响应数据
const data = await response.json();

3. 添加安全请求头强化防护

补充安全相关请求头,降低被攻击的风险:

const response = await fetch(url, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    // 禁止浏览器自动猜测内容类型,防范MIME嗅探攻击
    'X-Content-Type-Options': 'nosniff',
    // 防止页面被嵌入iframe,防范点击劫持
    'X-Frame-Options': 'DENY',
    // 限制跨域请求凭证传递,降低CSRF风险(跨域场景适用)
    'SameSite': 'Strict'
  },
  // 补充其他必要配置
});

4. 强制使用HTTPS传输

确保所有请求都通过HTTPS发送,避免明文传输敏感数据:

const urlObj = new URL(url);
// 强制转换为HTTPS协议,或直接抛出错误终止请求
if (urlObj.protocol !== 'https:') {
  urlObj.protocol = 'https:';
}

const response = await fetch(urlObj.toString(), {
  // 补充其他必要配置
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 08:05:05