Defense-in-Depth Validation

VerifiedSafe

Use when invalid data causes failures deep in execution, requiring validation at multiple system layers to make bugs structurally impossible.

Sby Skills Guide Bot
DevelopmentIntermediate
7/23/2026
Claude CodeCursorWindsurfCodex
#validation#defense-in-depth#error-handling#debugging#input-validation

Recommended for

Automated summary

This skill walks through adding validation at every layer data passes through — entry point, business logic, environment guards, and debug logging — so a bug becomes structurally impossible instead of merely patched.

Strengths

  • Offers a clear four-layer framework with concrete TypeScript examples for each layer
  • Describes a step-by-step data-flow tracing method to map every checkpoint
  • Explains how to test each layer by trying to bypass the previous one, avoiding a false sense of safety
  • Grounded in a real case (empty projectDir triggering git init in the wrong place) with all four fixes applied

Limitations

  • Examples are TypeScript/Node.js only; porting to other languages or frameworks is left to the reader
  • Does not weigh the duplication cost or say when to stop stacking validations
  • Ignores declarative validation schemas (Zod, JSON Schema) that could replace some manual checks
When to use it

Reach for it after fixing a bug caused by invalid data, when you want to prevent recurrence through other code paths rather than relying on a single check.

When not to use it

Skip it for throwaway code or internal scripts where layering validations costs more than the risk warrants.

Security analysis

Safe
Quality score88/100

The skill contains only instructional guidance and code examples about validation. It declares no tools and performs no execution, network access, file operations, or secret handling. There is no obfuscation or destructive instruction, so listing it poses no meaningful security risk.

No concerns found

How this analysis is made

Examples

Harden a fixed bug
We just fixed a bug where an empty projectDir made git init run in the repo root. Walk the data flow and add defense-in-depth validation at every layer so it can't happen again.
Validate a new API entry point
Add entry-point validation to createProject for the workingDirectory argument, and tell me which business-logic and environment guards I should also add downstream.
Prove layers can't be bypassed
Write tests that try to bypass Layer 1 validation for workspace initialization and confirm Layers 2 and 3 still catch the invalid input.

name: defense-in-depth description: Use when invalid data causes failures deep in execution, requiring validation at multiple system layers - validates at every layer data passes through to make bugs structurally impossible

Defense-in-Depth Validation

Overview

When you fix a bug caused by invalid data, adding validation at one place feels sufficient. But that single check can be bypassed by different code paths, refactoring, or mocks.

Core principle: Validate at EVERY layer data passes through. Make the bug structurally impossible.

Why Multiple Layers

Single validation: "We fixed the bug" Multiple layers: "We made the bug impossible"

Different layers catch different cases:

  • Entry validation catches most bugs
  • Business logic catches edge cases
  • Environment guards prevent context-specific dangers
  • Debug logging helps when other layers fail

The Four Layers

Layer 1: Entry Point Validation

Purpose: Reject obviously invalid input at API boundary

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
}

Layer 2: Business Logic Validation

Purpose: Ensure data makes sense for this operation

function initializeWorkspace(projectDir: string, sessionId: string) {
  if (!projectDir) {
    throw new Error('projectDir required for workspace initialization');
  }
  // ... proceed
}

Layer 3: Environment Guards

Purpose: Prevent dangerous operations in specific contexts

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
}

Layer 4: Debug Instrumentation

Purpose: Capture context for forensics

async function gitInit(directory: string) {
  const stack = new Error().stack;
  logger.debug('About to git init', {
    directory,
    cwd: process.cwd(),
    stack,
  });
  // ... proceed
}

Applying the Pattern

When you find a bug:

  1. Trace the data flow - Where does bad value originate? Where used?
  2. Map all checkpoints - List every point data passes through
  3. Add validation at each layer - Entry, business, environment, debug
  4. Test each layer - Try to bypass layer 1, verify layer 2 catches it

Example from Session

Bug: Empty projectDir caused git init in source code

Data flow:

  1. Test setup → empty string
  2. Project.create(name, '')
  3. WorkspaceManager.createWorkspace('')
  4. git init runs in process.cwd()

Four layers added:

  • Layer 1: Project.create() validates not empty/exists/writable
  • Layer 2: WorkspaceManager validates projectDir not empty
  • Layer 3: WorktreeManager refuses git init outside tmpdir in tests
  • Layer 4: Stack trace logging before git init

Result: All 1847 tests passed, bug impossible to reproduce

Key Insight

All four layers were necessary. During testing, each layer caught bugs the others missed:

  • Different code paths bypassed entry validation
  • Mocks bypassed business logic checks
  • Edge cases on different platforms needed environment guards
  • Debug logging identified structural misuse

Don't stop at one validation point. Add checks at every layer.

From the file to a first result

The download contains exactly the content displayed on this page. This copy may differ from the latest version in the source repository.

View the source and supporting files

This download contains SKILL.md only. Any scripts, references, templates and dependencies are not included. Get the required files from the source, preserving their directory structure, before continuing.

1. Download the file

Download SKILL.md

From the root of a test project, save the file as .skill-downloads/defense-in-depth-validation-mrx3xzty/SKILL.md, or use the command below. This folder is for inspecting the skill before installation.

Command for macOS/Linux or WSL: requires a POSIX shell and curl. On Windows without WSL, use the download button and create the folder manually.

mkdir -p '.skill-downloads/defense-in-depth-validation-mrx3xzty' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/defense-in-depth-validation-mrx3xzty/download' --output '.skill-downloads/defense-in-depth-validation-mrx3xzty/SKILL.md.part' && mv '.skill-downloads/defense-in-depth-validation-mrx3xzty/SKILL.md.part' '.skill-downloads/defense-in-depth-validation-mrx3xzty/SKILL.md'

2. Check prerequisites

Read SKILL.md before using it. If it references scripts or external services, inspect them and prepare the required access in your test environment.

No recognized prerequisites section in this file. This does not mean it is self-contained: libraries, tools and access requirements may be mentioned elsewhere in the content or source repository.

The platforms on this page are catalog indications. The paths below follow tool documentation; they do not prove this skill has been run in those tools. No minimum tool version is confirmed for this listing.

3. Load the skill

After inspection, copy the complete folder into your project using one of the commands below, then open a new tool session. The command stops if a folder with the same name already exists: compare the files before replacing it.

Claude Code
test -f '.skill-downloads/defense-in-depth-validation-mrx3xzty/SKILL.md' && test -s '.skill-downloads/defense-in-depth-validation-mrx3xzty/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/defense-in-depth' && cp -R '.skill-downloads/defense-in-depth-validation-mrx3xzty' '.claude/skills/defense-in-depth'

Cursor
test -f '.skill-downloads/defense-in-depth-validation-mrx3xzty/SKILL.md' && test -s '.skill-downloads/defense-in-depth-validation-mrx3xzty/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/defense-in-depth' && cp -R '.skill-downloads/defense-in-depth-validation-mrx3xzty' '.cursor/skills/defense-in-depth'

Codex
test -f '.skill-downloads/defense-in-depth-validation-mrx3xzty/SKILL.md' && test -s '.skill-downloads/defense-in-depth-validation-mrx3xzty/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/defense-in-depth' && cp -R '.skill-downloads/defense-in-depth-validation-mrx3xzty' '.agents/skills/defense-in-depth'

OpenSkills

OpenSkills must already be installed. The local install/read procedure is checked with OpenSkills 1.5.0, which requires Node.js ≥ 20.6.0. Catalog slugs are not resolved automatically.

Official OpenSkills installation
openskills install './.skill-downloads/defense-in-depth-validation-mrx3xzty'

openskills read 'defense-in-depth-validation-mrx3xzty'

Reading should display the installed file content and its base directory. It does not run the skill or install its dependencies.

For an agent that reads AGENTS.md, then sync the index. This command changes AGENTS.md: review the diff before using it.

openskills sync

Manual method or another tool: attach SKILL.md to a conversation, or open it in an agent that can read files. Include any required supporting resources. No universal folder is recognized by every tool.

4. Try a first task

Use a short, synthetic input: an API endpoint, a small document or an interface brief. In a new conversation, attach the file or give the agent its path, then adapt this request:

Read .skill-downloads/defense-in-depth-validation-mrx3xzty/SKILL.md and apply its instructions to this example: [describe a test input]. Identify any missing files, dependencies or access. Produce the result requested by the skill without inventing data or running unreviewed scripts.

Expected result: output matching the skill instructions, or a precise list of missing prerequisites. A read confirmation alone does not validate a first use. If an external resource is unavailable, that path remains untested.

Related skills