Feedback

Chat Icon

DevSecOps in Practice

A Hands-On Guide to Operationalizing DevSecOps at Scale

Detecting & Preventing Leaked Secrets
32%

Pre-Commit Hooks: A Proactive Approach to Secrets Detection

Pre-commit hooks are scripts that run before a commit to a repository. They enforce coding standards, run tests, and perform other checks to ensure code quality before the commit. Pre-commit hooks also prevent secrets from being committed to the repository. A secrets scan before a commit allows developers to identify and remove exposed credentials, API keys, or other sensitive information unsuitable for repository storage.

Implementing pre-commit hooks for secret scans provides proactive security. This helps prevent accidental leaks that could lead to security breaches, unauthorized access, or compliance violations. When secrets like API tokens, private keys, or passwords are mistakenly committed, they become part of the version history, making complete removal difficult. Attackers frequently scan public repositories for exposed secrets, making it crucial to catch these issues before they are pushed.

Using pre-commit hooks to detect secrets also fosters a culture of security awareness among developers. Immediate feedback during the commit process encourages developers to follow best practices for handling sensitive information. This includes storing secrets in environment variables, using secrets management tools, and ensuring sensitive data is never hardcoded into source code files.

To understand how pre-commit hooks work, let's use the pre-commit framework to create a hook that runs a basic example using some predefined rules. Start by installing the pre-commit package:

pip3 install pre-commit==4.1.0 \
  --break-system-packages

Create a file named .pre-commit-config.yaml in the root of your Git repository:

cat <$HOME/RestQR/.pre-commit-config.yaml
repos:
-   repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v2.3.0
    hooks:
    -   id: check-yaml
    -   id: end-of-file-fixer
    -   id: trailing-whitespace
    -   id: check-added-large-files
EOF

Add the file to the repository:

cd $HOME/RestQR
git add .pre-commit-config.yaml
git commit -m "Adding pre-commit configuration file"

In the above file, we define a list of hooks that will run before each commit. The hooks are defined in the repos section, which specifies the repository URL and the revision to use. Each hook is identified by its id, which corresponds to a specific check:

  • check-yaml: Checks YAML files for syntax errors.
  • end-of-file-fixer: Fixes missing end-of-file markers.
  • trailing-whitespace: Removes trailing whitespace from lines in files.
  • check-added-large-files: Prevents large files from being added to the repository.

DevSecOps in Practice

A Hands-On Guide to Operationalizing DevSecOps at Scale

Enroll now to unlock all content and receive all future updates for free.