Skip to content

Add pre-commit configuration and custom hook #149

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Jul 1, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 73 additions & 0 deletions .git-hooks/detect-api-keys.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
#!/usr/bin/env python
from __future__ import print_function

import argparse
import re
import sys


def detect_aws_access_key(line):
match = re.search(r"(?<![A-Z0-9])[A-Z0-9]{20}(?![A-Z0-9])", line)
return match, "AWS access key"


def detect_aws_secret_key(line):
match = re.search(r"(?<![A-Za-z0-9/+=])[A-Za-z0-9/+=]{40}(?![A-Za-z0-9/+=])", line)
return match, "AWS secret key"


def detect_dd_api_key(line):
match = re.search(r"(?<![a-fA-F0-9])[a-fA-F0-9]{32}(?![a-fA-F0-9])", line)
return match, "Datadog API key"


def detect_dd_app_key(line):
match = re.search(r"(?<![a-fA-F0-9])[a-fA-F0-9]{40}(?![a-fA-F0-9])", line)
return match, "Datadog app key"


def key_found_message(args):
return (
"\033[91m"
"Potential {} found in {} at line {} and column {}. "
"Please remove the key before committing these changes."
"\033[0m".format(*args)
)


def main(argv=None):
parser = argparse.ArgumentParser()
parser.add_argument("filenames", nargs="*", help="Filenames to check.")
args = parser.parse_args(argv)

# add or remove functions here
functions_to_run = [
detect_aws_access_key,
detect_aws_secret_key,
detect_dd_api_key,
detect_dd_app_key,
]

files_with_key = []

for filename in args.filenames:
with open(filename, "r") as f:
content = f.readlines()
f.close()

for i, line in enumerate(content):
for func in functions_to_run:
match, name = func(line)
if match != None:
files_with_key.append((name, filename, i + 1, match.end()))

if files_with_key:
for file in files_with_key:
print(key_found_message(file))
return 1
else:
return 0


if __name__ == "__main__":
sys.exit(main())
18 changes: 18 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
repos:
- repo: [email protected]:pre-commit/pre-commit-hooks
rev: v2.1.0
hooks:
- id: check-merge-conflict
files: \.py$
- repo: [email protected]:psf/black
rev: 21.6b0
hooks:
- id: black
files: \.py$
- repo: local
hooks:
- id: detect-api-keys
name: detect-api-keys
description: Checks for AWS or Datadog API keys
entry: ".git-hooks/detect-api-keys.py"
language: python