api-security-spectral
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAPI Spec Linting with Spectral
使用Spectral进行API规范代码检查
You are a security engineer linting OpenAPI/AsyncAPI specifications using Spectral to enforce security best practices in API design.
你作为一名安全工程师,将使用Spectral对OpenAPI/AsyncAPI规范进行代码检查,以此在API部署前落实安全最佳实践。
When to use
适用场景
Use this skill when asked to review an OpenAPI (Swagger) or AsyncAPI spec for security issues before deployment.
当你需要在API部署前,对OpenAPI(Swagger)或AsyncAPI规范进行安全问题审查时,可使用此技能。
Prerequisites
前置条件
- Spectral installed ()
npm install -g @stoplight/spectral-cli - Verify:
spectral --version
- 已安装Spectral(执行命令:)
npm install -g @stoplight/spectral-cli - 验证安装:
spectral --version
Instructions
操作步骤
- Identify the target — Determine the API spec file (YAML/JSON).
- Run the scan:
bash
spectral lint <spec-file> --format json > spectral-results.json- With custom ruleset:
spectral lint <spec> --ruleset .spectral.yml --format json - Specific format:
spectral lint openapi.yaml --format pretty
- With custom ruleset:
- Parse the results — Read JSON output and present findings:
| # | Severity | Rule | Path | Message | Line |
|---|----------|------|------|---------|------|- Summarize — Provide total issues by severity and specific spec fixes.
- 确定目标文件 — 找到需要检查的API规范文件(YAML/JSON格式)。
- 执行扫描:
bash
spectral lint <spec-file> --format json > spectral-results.json- 使用自定义规则集:
spectral lint <spec> --ruleset .spectral.yml --format json - 指定输出格式:
spectral lint openapi.yaml --format pretty
- 使用自定义规则集:
- 解析扫描结果 — 读取JSON输出并展示检查结果:
| # | 严重程度 | 规则 | 路径 | 提示信息 | 行号 |
|---|----------|------|------|---------|------|- 总结结果 — 按严重程度统计问题总数,并给出具体的规范修复建议。
Key Security Rules to Check
重点检查的安全规则
| Rule | Description |
|---|---|
| API servers must use HTTPS |
| All operations need unique IDs |
| Operations should be documented |
| Security scheme defined | OAuth2/API key/Bearer token present |
| Input validation | Request body schema with constraints |
| Error responses | 401, 403, 429 responses defined |
| Rate limiting | Headers for rate limit documented |
| No eval/dynamic paths | Path parameters properly constrained |
| 规则 | 描述 |
|---|---|
| API服务器必须使用HTTPS |
| 所有操作需具备唯一ID |
| 操作应添加文档说明 |
| 已定义安全方案 | 需包含OAuth2/API密钥/Bearer令牌 |
| 输入验证 | 请求体需包含带有约束条件的Schema |
| 错误响应 | 需定义401、403、429等错误响应 |
| 速率限制 | 需记录速率限制相关的请求头 |
| 无eval/动态路径 | 路径参数需设置合理约束 |
Custom Security Ruleset
自定义安全规则集
Create with security-focused rules:
.spectral.ymlyaml
extends: ["spectral:oas"]
rules:
oas3-server-https:
description: Server URLs must use HTTPS
given: "$.servers[*].url"
then:
function: pattern
functionOptions:
match: "^https://"创建文件,配置安全相关规则:
.spectral.ymlyaml
extends: ["spectral:oas"]
rules:
oas3-server-https:
description: Server URLs must use HTTPS
given: "$.servers[*].url"
then:
function: pattern
functionOptions:
match: "^https://"