mcpField
D
Defense-in-Depth Validation

Defense-in-Depth Validation

github.com/obra开发756516 次安装54 周前更新
代码仓库

关于 Defense-in-Depth Validation

Defense-in-Depth Validation 是帮助开发者处理无效数据错误的软件开发技能。它在入口、业务逻辑和环境边界设置检查,并辅以调试记录,降低验证被绕过的风险。

主要功能

  1. 01在入口验证输入
  2. 02检查业务逻辑约束
  3. 03防护特定环境中的操作
  4. 04记录调试上下文
  5. 05逐层测试验证机制

适用场景

  1. 01防止空路径传入 git init
  2. 02增强数据流对绕过的防护
  3. 03通过调试上下文诊断误用

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/obra/superpowers-skills --skill defense-in-depth-validation

安装后在 Claude Code 中输入/defense-in-depth-validation确认已加载。

详细介绍

纵深验证

概述

修复由无效数据引发的 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. 列出所有检查点 - 列出数据经过的每一个位置
  3. 在每一层添加验证 - 入口、业务逻辑、环境、调试
  4. 测试每一层 - 尝试绕过第 1 层,确认第 2 层能捕获问题

会话中的示例

Bug:空的 projectDir 导致在源代码目录中执行 git init

数据流:

  1. 测试设置 → 空字符串
  2. Project.create(name, '')
  3. WorkspaceManager.createWorkspace('')
  4. git init 在 process.cwd() 中运行

添加的四层验证:

  • 第 1 层:Project.create() 验证非空、路径存在且可写
  • 第 2 层:WorkspaceManager 验证 projectDir 非空
  • 第 3 层:WorktreeManager 在测试中禁止在 tmpdir 之外执行 git init
  • 第 4 层:在 git init 之前记录堆栈跟踪

结果: 所有 1847 项测试均通过,无法复现该 bug

关键见解

四层验证缺一不可。测试期间,每一层都捕获了其他层遗漏的 bug:

  • 不同的代码路径绕过了入口验证
  • 模拟绕过了业务逻辑检查
  • 不同平台上的边缘情况需要环境防护
  • 调试日志发现了结构性误用

不要只停留在一个验证点。 在每一层都添加检查。

评论

支持 Markdown