关于 defense-in-depth
面向软件开发者的多层数据校验实践技能,强调在入口、业务逻辑、环境防护和调试记录各层检查数据。通过覆盖不同代码路径来降低无效数据触发错误操作的风险。
主要功能
- 01入口参数校验
- 02业务逻辑校验
- 03环境条件防护
- 04调试上下文记录
- 05逐层测试校验
适用场景
- 01防止空目录触发 git init
- 02检查多个代码路径中的输入
- 03限制测试环境中的危险操作
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ jackspace/ claudeskillz --skill defense-in-depth安装后在 Claude Code 中输入/defense-in-depth确认已加载。
附带文件SKILL.json
详细介绍
纵深验证
概述
修复由无效数据引发的 bug 时,在一个地方添加验证似乎就足够了。但这项单一检查可能会被不同的代码路径、重构或模拟绕过。
核心原则: 在数据经过的每一层都进行验证,让 bug 在结构上无法发生。
为什么需要多层验证
单一验证:“我们修复了 bug” 多层验证:“我们让 bug 不可能发生”
不同层可以捕获不同情况:
- 入口验证可捕获大多数 bug
- 业务逻辑可捕获边缘情况
- 环境防护可防止特定上下文中的危险操作
- 调试日志有助于在其他层失效时排查问题
四个层级
第 1 层:入口验证
目的: 在 API 边界拒绝明显无效的输入
function createProject(name: string, workingDirectory: string) {
if (!workingDirectory || workingDirectory.trim() === '') {
throw new Error('workingDirectory cannot be empty');
}
if (!existsSync(workingDirectory)) {
throw new Error(`workingDirectory does not exist: ${workingDirectory}`);
}
if (!statSync(workingDirectory).isDirectory()) {
throw new Error(`workingDirectory is not a directory: ${workingDirectory}`);
}
// ... proceed
}
第 2 层:业务逻辑验证
目的: 确保数据符合当前操作的要求
function initializeWorkspace(projectDir: string, sessionId: string) {
if (!projectDir) {
throw new Error('projectDir required for workspace initialization');
}
// ... proceed
}
第 3 层:环境防护
目的: 防止在特定上下文中执行危险操作
async function gitInit(directory: string) {
// In tests, refuse git init outside temp directories
if (process.env.NODE_ENV === 'test') {
const normalized = normalize(resolve(directory));
const tmpDir = normalize(resolve(tmpdir()));
if (!normalized.startsWith(tmpDir)) {
throw new Error(
`Refusing git init outside temp dir during tests: ${directory}`
);
}
}
// ... proceed
}
第 4 层:调试埋点
目的: 记录上下文以供取证分析
async function gitInit(directory: string) {
const stack = new Error().stack;
logger.debug('About to git init', {
directory,
cwd: process.cwd(),
stack,
});
// ... proceed
}
应用此模式
发现 bug 时:
- 追踪数据流 - 错误值从何而来?在哪里使用?
- 列出所有检查点 - 列出数据经过的每一个位置
- 在每一层添加验证 - 入口、业务逻辑、环境、调试
- 测试每一层 - 尝试绕过第 1 层,确认第 2 层能捕获问题
会话中的示例
Bug:空的 projectDir 导致在源代码目录中执行 git init
数据流:
- 测试设置 → 空字符串
Project.create(name, '')WorkspaceManager.createWorkspace('')git init在process.cwd()中运行
添加的四层验证:
- 第 1 层:
Project.create()验证非空、路径存在且可写 - 第 2 层:
WorkspaceManager验证projectDir非空 - 第 3 层:
WorktreeManager在测试中禁止在 tmpdir 之外执行 git init - 第 4 层:在 git init 之前记录堆栈跟踪
结果: 所有 1847 项测试均通过,无法复现该 bug
关键见解
四层验证缺一不可。测试期间,每一层都捕获了其他层遗漏的 bug:
- 不同的代码路径绕过了入口验证
- 模拟绕过了业务逻辑检查
- 不同平台上的边缘情况需要环境防护
- 调试日志发现了结构性误用
不要只停留在一个验证点。 在每一层都添加检查。
评论
支持 Markdown