Witness Protection for Your Environment Variables: Because Your API Keys Deserve Better Than Git History
โ€ข

Witness Protection for Your Environment Variables: Because Your API Keys Deserve Better Than Git History

๐Ÿ’ป Git Pre-commit Hook: Auto-Redact Sensitive Data

Scans staged files and replaces API keys/secrets before they hit your git history.

#!/bin/bash
# Save as .git/hooks/pre-commit (make executable)

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m' # No Color

# Files to scan (add your own patterns)
FILES_TO_SCAN="*.yml *.json *.md *.py *.js *.env.example"

# Patterns to redact (add your own)
PATTERNS=(
    "API_KEY"
    "SECRET_KEY"
    "PASSWORD"
    "TOKEN"
    "PRIVATE_KEY"
    "DATABASE_URL"
)

# Redaction flag
REDACTED_FLAG="REDACTED_BY_WITNESS_PROTECTION"

# Counter for redactions
REDACTION_COUNT=0

# Check staged files
for file in $(git diff --cached --name-only); do
    for pattern in "${PATTERNS[@]}"; do
        # Check if file contains pattern
        if grep -qi "${pattern}" "${file}" 2>/dev/null; then
            # Create backup and redact
            sed -i.bak -E "s/(${pattern}=['\"]?)[^'\"\s]*(['\"\s]?)/\1${REDACTED_FLAG}\2/gi" "${file}"
            rm -f "${file}.bak"
            
            # Stage the redacted file
            git add "${file}"
            
            REDACTION_COUNT=$((REDACTION_COUNT + 1))
            echo -e "${RED}โš ๏ธ  Redacted '${pattern}' in ${file}${NC}"
        fi
    done
done

# Summary
if [ $REDACTION_COUNT -gt 0 ]; then
    echo -e "${GREEN}โœ… Redacted ${REDACTION_COUNT} sensitive values${NC}"
    echo "Your secrets are now in witness protection!"
else
    echo "No sensitive data found in staged files."
fi

exit 0
Ever committed your AWS secret key to GitHub, then spent the next 45 minutes in a cold sweat, frantically searching Stack Overflow for 'how to rewrite git history without summoning the elder gods'? Of course you have. We all have. It's basically a developer rite of passage at this point, like your first 'sudo rm -rf /' scare or explaining to your boss why the database is 'resting.' The real tragedy isn't the security breachโ€”it's the sheer, repetitive absurdity of treating our most sensitive credentials like they're trying to sneak past airport security in a trench coat.

The Problem: Your Git History Is a Snitch

Let's be honest. The `.env` file was a beautiful lie. A promise that we, as developers, could be trusted to keep our secrets separate from our code. It was the digital equivalent of "I'll just have one chip" while holding the family-sized bag. We all nodded solemnly, added `.env` to `.gitignore`, and then proceeded to commit secrets in at least seven other creative ways.

Maybe it's in your `docker-compose.yml` because you were "just testing locally." Perhaps it's hardcoded in a `config.json` that "won't be used in production, I swear." Or my personal favorite: the API key you pasted into a `README.md` as an "example," thereby providing hackers with both the key and instructions on how to use it. We're not just leaking credentials; we're providing full-service support for our own breaches.

The aftermath is a special kind of hell. It's not just the frantic rotation of keys and the shameful Slack message to the security channel. It's the git-fu incantationsโ€”`git filter-branch`, `BFG Repo-Cleaner`โ€”that feel less like coding and more like performing an exorcism on your repository. You're not a developer anymore; you're a digital janitor mopping up your own carelessness. All while your exposed database credentials are probably already being sold on a forum for 3 Bitcoin and a funny meme.

๐Ÿ”ง Get the Tool

View on GitHub โ†’

Free & Open Source โ€ข MIT License

The Solution: Enter the Program

I got tired of being the guy who accidentally doxxed his own Stripe test keys. So I built the Env Vars Witness Protection Program. It's a pre-commit hook that acts like a paranoid bodyguard for your sensitive data. Before you can type `git commit -m "fix typo"` and inadvertently publish the keys to the kingdom, it steps in.

Here's the high-level heist: The tool scans all your staged files (the ones you're about to commit) for patterns that look like environment variables. We're talking `API_KEY=`, `PASSWORD=`, `SECRET=`, `TOKEN=`, and all their sneaky cousins. When it finds one, it doesn't just warn youโ€”that's for amateurs. It automatically replaces the exposed value with the glorious, all-caps placeholder: REDACTED_BY_WITNESS_PROTECTION.

The beauty is in the automation. You don't have to remember to run a scan. You don't have to configure a complex CI step. It hooks into Git's pre-commit lifecycle, which means the protection happens at the exact moment you're most likely to screw up: when you're trying to commit code. It's like having a friend who gently takes your car keys after your third beer, but for your repository.

And because we're dealing with matters of life and death (for your credentials), it doesn't just silently change things. It generates a dramatic "Witness Protection Certificate" for each variable it saves, logging the operation with the solemnity it deserves. Your `DATABASE_URL` isn't just hidden; it's given a new identity, a fresh start, far from the prying eyes of `git log`.

How to Use It: Your Credentials' New Identity

Getting your variables into the program is straightforward. First, clone the repo or copy the main script. The core of the operation is a Python script designed to be installed as a Git hook.

The simplest way is to copy the provided pre-commit script into your repository's `.git/hooks/` directory (make sure it's executable). The tool will then spring into action on every commit attempt. Here's a peek at the heart of the scanning logic:

import re

def scan_and_redact_file(filepath):
    """Scans a file for env var patterns and redacts their values."""
    env_pattern = re.compile(
        r'^(\s*)(\w+)(\s*[=:]\s*["\']?)([^"\'\n]+)(["\']?\s*)$',
        re.MULTILINE | re.IGNORECASE
    )
    
    with open(filepath, 'r') as f:
        content = f.read()
    
    # Check for high-risk variable names
    risky_keywords = ['KEY', 'SECRET', 'PASSWORD', 'TOKEN', 'PASS', 'PRIVATE']
    
    def redact_if_risky(match):
        prefix, key, separator, value, suffix = match.groups()
        if any(kw in key.upper() for kw in risky_keywords):
            print(f"[WITNESS PROTECTION] Relocating variable: {key}")
            return f"{prefix}{key}{separator}REDACTED_BY_WITNESS_PROTECTION{suffix}"
        return match.group(0)
    
    new_content = env_pattern.sub(redact_if_risky, content)
    
    if new_content != content:
        with open(filepath, 'w') as f:
            f.write(new_content)
        return True
    return False

Check out the full source code on GitHub for the complete setup, including the certificate generator and installation script. The repo has instructions for a one-command install that sets everything up.

Once installed, try to commit a file with `SECRET_API_KEY=sup3rS3cr3t!`. The tool will intercept it, replace the value, and your commit will contain `SECRET_API_KEY=REDACTED_BY_WITNESS_PROTECTION` instead. You can then safely store the real value in a proper secret manager or a `.env` file (that's actually in `.gitignore`, you animal).

Key Features: The Full Protection Package

  • Pre-Commit Scanning: Automatically scans all staged files before a commit is finalized. No secrets slip through on your watch.
  • Pattern Intelligence: Uses regex patterns to catch common environment variable declarations (`VAR=value`, `VAR: value`, with or without quotes).
  • Automatic Redaction: Doesn't just warnโ€”it takes action. Revalues exposed secrets with the unmistakable REDACTED_BY_WITNESS_PROTECTION flag.
  • Witness Protection Certificates: Generates a humorous but clear log entry (a "certificate") for each variable it saves, so you have a record of the intervention.
  • Git Hook Integration: Works seamlessly as a Git pre-commit hook, making it part of your standard workflow without extra steps.

Conclusion: Stop the Cycle of Shame

The Env Vars Witness Protection Program won't solve all your security problems. You still need proper secret management, encryption, and the common sense not to paste your AWS IAM credentials into a public Gist. But what it does is eliminate the most common, most embarrassing vector: the careless commit.

It turns an active, error-prone task ("remember to check for secrets") into a passive, automated safety net. It's the digital equivalent of putting a guardrail on the cliff you keep accidentally walking off. The humor is the packaging, but the utility is real. Give your environment variables the new identity they deserve, before they end up starring in someone else's breach report.

Try it out: https://github.com/BoopyCode/env-vars-witness-protection

Your API keys have been through enough. It's time they entered the program.

โšก

Quick Summary

  • What: A pre-commit hook that scans staged files for environment variable patterns and automatically redacts their values before you accidentally commit them to version control.

๐Ÿ“š Sources & Attribution

Author: Code Sensei
Published: 09.01.2026 09:39

โš ๏ธ AI-Generated Content
This article was created by our AI Writer Agent using advanced language models. The content is based on verified sources and undergoes quality review, but readers should verify critical information independently.

๐Ÿ’ฌ Discussion

Add a Comment

0/5000
Loading comments...