Reject breached passwords in Django with the Pwned Passwords range API and k-anonymity, flag existing accounts safely at login, and stop secrets leaking from your own repositories with gitleaks, detect-secrets, pre-commit and CI.
Leaked passwords and leaked secrets are two sides of the same exposure problem: something that should be known only to one party is now public. In this tutorial we build a Django password validator that checks new passwords against Have I Been Pwned's Pwned Passwords range API without ever sending the password, flag existing accounts at login, and then turn the same thinking on our own code: scanning repositories for committed secrets with gitleaks and detect-secrets, and handling a leak properly when it happens.
This is OSINT for defenders. Everything here concerns your own organisation: your users' passwords at the moment they type them into your site, and your own repositories. Two lines we do not cross:
Versions used and tested: Python 3.13 (anything from 3.12 works), Django 5.2.20 (pinned as Django>=5.2,<6.0 because 5.2 is the current LTS), requests 2.34.2, detect-secrets 1.5.0, pre-commit 4.7.0 and the gitleaks 8.30.1 binary.
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install "Django>=5.2,<6.0" "requests>=2.34,<3" \
"detect-secrets>=1.5,<2" "pre-commit>=4.7,<5"
Pwned Passwords is a corpus of hundreds of millions of passwords that have appeared in public breaches, published as SHA-1 (and NTLM) hashes with an occurrence count. The range API lets you ask "is this password in the corpus?" without revealing the password, using a technique called k-anonymity:
https://api.pwnedpasswords.com/range/{prefix}.There are 16 to the power of 5 (1,048,576) possible prefixes, and each bucket holds well over a thousand suffixes, so the service learns only that your password is one of many hashes that share a prefix. It cannot tell which one, or whether yours is in the list at all. No API key is required for this endpoint.
Here is the real exchange for the deliberately terrible test password password123:
$ python -c "import hashlib; h=hashlib.sha1(b'password123').hexdigest().upper(); print(h[:5], h[5:])"
CBFDA C6008F9CAB4083784CBD1874F76618D2A97
$ curl -s -H "Add-Padding: true" https://api.pwnedpasswords.com/range/CBFDA | head -3
000DD0BFD801860C09116B9AAD880B125F1:53
00791BB54CC9122C70C1156FD97134EB83E:5
0088D3EFF796511B3833D74664B042D531A:1
$ curl -s -H "Add-Padding: true" https://api.pwnedpasswords.com/range/CBFDA \
| grep C6008F9CAB4083784CBD1874F76618D2A97
C6008F9CAB4083784CBD1874F76618D2A97:2266677
Over two million occurrences. The response had 2,161 lines, 190 of which ended in :0.
Without padding, bucket sizes differ, so an observer who can see the encrypted response length (a proxy, a compromised network segment) could narrow down which prefix you asked for. With Add-Padding: true, the API adds random fake suffixes with a count of 0 so that responses have a similar size. Your parser must treat a count of 0 as "not breached". In practice a fake suffix will never equal your real suffix, but handling the zero explicitly costs nothing and documents the intent.
Create an app, for example accounts, in a project called myproject. First the lookup, separated from the validator so that we can reuse it at login:
# accounts/pwned.py
import hashlib
import logging
import requests
from django.core.cache import cache
logger = logging.getLogger(__name__)
RANGE_URL = "https://api.pwnedpasswords.com/range/{prefix}"
USER_AGENT = "myproject-password-check"
CACHE_SECONDS = 60 * 60 * 24
class PwnedLookupError(Exception):
"""The range API could not be reached or returned garbage."""
def _fetch_range(prefix, timeout):
key = f"pwned-range:{prefix}"
body = cache.get(key)
if body is not None:
return body
try:
resp = requests.get(
RANGE_URL.format(prefix=prefix),
headers={"Add-Padding": "true", "User-Agent": USER_AGENT},
timeout=timeout,
)
resp.raise_for_status()
except requests.RequestException as exc:
raise PwnedLookupError(str(exc)) from exc
body = resp.text
cache.set(key, body, CACHE_SECONDS)
return body
def pwned_count(password, timeout=2.0):
"""Return how often this password appears in Pwned Passwords."""
digest = hashlib.sha1(password.encode("utf-8")).hexdigest().upper()
prefix, suffix = digest[:5], digest[5:]
for line in _fetch_range(prefix, timeout).splitlines():
candidate, _, count = line.partition(":")
if candidate == suffix:
# Padding rows have count 0 and never match a real hash.
return int(count or 0)
return 0
Notice what is cached: the public range response, keyed by the 5-character prefix. We never cache the full hash, and certainly not the password. An unsalted SHA-1 of a password is effectively the password for anyone with a cracking rig, so it must not end up in Redis, logs or error trackers. The corpus is updated occasionally, so a day of caching is a reasonable trade-off. Note also that the log message on failure deliberately contains no hash or prefix.
Now the validator. Django calls validate(password, user) for every entry in AUTH_PASSWORD_VALIDATORS:
# accounts/validators.py
import logging
from django.core.exceptions import ValidationError
from django.utils.translation import gettext as _, ngettext
from .pwned import PwnedLookupError, pwned_count
logger = logging.getLogger(__name__)
class PwnedPasswordValidator:
def __init__(self, threshold=1, timeout=2.0, fail_closed=False):
self.threshold = threshold
self.timeout = timeout
self.fail_closed = fail_closed
def validate(self, password, user=None):
try:
count = pwned_count(password, timeout=self.timeout)
except PwnedLookupError:
logger.warning("Pwned Passwords lookup failed")
if self.fail_closed:
raise ValidationError(
_("We could not check this password right now. "
"Please try again in a minute."),
code="password_check_unavailable",
)
return
if count >= self.threshold:
raise ValidationError(
ngettext(
"This password has appeared in a data breach %(count)d time. "
"Please choose a different one.",
"This password has appeared in data breaches %(count)d times. "
"Please choose a different one.",
count,
),
code="password_pwned",
params={"count": count},
)
def get_help_text(self):
return _("Your password must not appear in known data breaches.")
Register it after Django's built-in validators so cheap local checks run first:
# myproject/settings.py
AUTH_PASSWORD_VALIDATORS = [
# ... Django's four default validators ...
{
"NAME": "accounts.validators.PwnedPasswordValidator",
"OPTIONS": {"threshold": 1, "timeout": 2.0, "fail_closed": False},
},
]
When the API is unreachable you must choose. Fail open (the default above) means a user can set a breached password during an outage. Fail closed means nobody can sign up or change a password during an outage. Neither is universally right:
| Situation | Reasonable choice | Why |
|---|---|---|
| Public signup, consumer site | Fail open | Availability matters; the login-time check below catches it later. |
| Admin and staff accounts | Fail closed | Few users, high impact; a retry is acceptable. |
| Regulated environment with documented control | Fail closed plus alerting | An auditor will ask why the control silently turned off. |
Whichever you choose, log the failure and alert on a sustained failure rate, so that "fail open" does not quietly become "never checked". A 2 second timeout keeps the form responsive; the cache means most popular prefixes are answered locally anyway. The threshold option lets you accept passwords seen once or twice if your policy allows it, but for most sites 1 is the right value. NIST SP 800-63B explicitly recommends comparing new passwords against lists of compromised values.
Because the validator is in AUTH_PASSWORD_VALIDATORS, Django's own forms already use it: UserCreationForm, SetPasswordForm (password reset) and PasswordChangeForm all call validate_password(). If you have custom forms, call django.contrib.auth.password_validation.validate_password(password, user) yourself; do not reimplement the check. A quick check in the shell, against the real API:
$ python manage.py shell -c "
from django.contrib.auth.password_validation import validate_password
try:
validate_password('password123')
except Exception as e:
print(e.messages)
"
['This password is too common.', 'This password has appeared in data breaches 2266677 times. Please choose a different one.']
Unit tests must not depend on a third-party API. We mock requests.get and build a fake range response from the real hash, which also lets us assert that only the prefix leaves the process:
# accounts/tests.py (excerpt)
import hashlib
from unittest import mock
import requests
from django.contrib.auth.forms import UserCreationForm
from django.core.cache import cache
from django.core.exceptions import ValidationError
from django.test import TestCase
from .validators import PwnedPasswordValidator
BREACHED = "password123"
SAFE = "correct-horse-battery-staple-7f3a91"
def fake_range(password, count):
digest = hashlib.sha1(password.encode()).hexdigest().upper()
body = f"{digest[5:]}:{count}\r\n0000000000000000000000000000000000A:0"
return mock.Mock(text=body, raise_for_status=lambda: None)
class ValidatorTests(TestCase):
def setUp(self):
cache.clear()
@mock.patch("accounts.pwned.requests.get")
def test_rejects_breached_password(self, get):
get.return_value = fake_range(BREACHED, 2266677)
with self.assertRaises(ValidationError) as ctx:
PwnedPasswordValidator().validate(BREACHED)
self.assertEqual(ctx.exception.code, "password_pwned")
url = get.call_args.args[0]
self.assertTrue(url.endswith("/range/CBFDA"))
self.assertEqual(get.call_args.kwargs["headers"]["Add-Padding"], "true")
@mock.patch("accounts.pwned.requests.get",
side_effect=requests.Timeout("timed out"))
def test_fail_open_and_fail_closed(self, get):
PwnedPasswordValidator(fail_closed=False).validate(SAFE)
with self.assertRaises(ValidationError) as ctx:
PwnedPasswordValidator(fail_closed=True).validate(SAFE)
self.assertEqual(ctx.exception.code, "password_check_unavailable")
@mock.patch("accounts.pwned.requests.get")
def test_range_is_cached(self, get):
get.return_value = fake_range(BREACHED, 5)
for _ in range(3):
with self.assertRaises(ValidationError):
PwnedPasswordValidator().validate(BREACHED)
self.assertEqual(get.call_count, 1)
@mock.patch("accounts.pwned.requests.get")
def test_signup_form_rejects_breached_password(self, get):
get.return_value = fake_range(BREACHED, 2266677)
form = UserCreationForm(data={
"username": "alice", "password1": BREACHED, "password2": BREACHED,
})
self.assertFalse(form.is_valid())
self.assertIn("data breach", str(form.errors["password2"]))
The full suite in the accompanying project (eight tests, including a PasswordChangeForm test and the login tests below) runs offline:
$ python manage.py test accounts
...
Ran 8 tests in 2.504s
OK
The validator only protects passwords set from now on. Your existing users have passwords stored as salted PBKDF2 or Argon2 hashes, and that is exactly the point: you cannot derive the SHA-1 from them, so you cannot check them in bulk. The only moment you legitimately hold the plaintext is when a user logs in successfully.
The cleanest hook is a thin subclass of ModelBackend. The check runs only after the password has been verified, never blocks the login, and records a flag rather than anything derived from the password:
# accounts/models.py
from django.conf import settings
from django.db import models
class PasswordBreachFlag(models.Model):
user = models.OneToOneField(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE,
related_name="breach_flag",
)
detected_at = models.DateTimeField(auto_now_add=True)
notified_at = models.DateTimeField(null=True, blank=True)
# accounts/backends.py
from django.contrib.auth.backends import ModelBackend
from .models import PasswordBreachFlag
from .pwned import PwnedLookupError, pwned_count
class BreachCheckingBackend(ModelBackend):
def authenticate(self, request, username=None, password=None, **kwargs):
user = super().authenticate(request, username, password, **kwargs)
if user is None or password is None:
return user
try:
breached = pwned_count(password, timeout=1.0) > 0
except PwnedLookupError:
return user
if breached:
PasswordBreachFlag.objects.get_or_create(user=user)
else:
PasswordBreachFlag.objects.filter(user=user).delete()
return user
# accounts/signals.py (imported from AccountsConfig.ready())
from django.contrib import messages
from django.contrib.auth.signals import user_logged_in
from django.dispatch import receiver
from django.utils import timezone
from .models import PasswordBreachFlag
@receiver(user_logged_in)
def warn_about_breached_password(sender, request, user, **kwargs):
flag = PasswordBreachFlag.objects.filter(user=user).first()
if flag is None:
return
messages.warning(
request,
"Your password appears in a public breach list. "
"It was not leaked by us, but please change it now.",
)
flag.notified_at = timezone.now()
flag.save(update_fields=["notified_at"])
# myproject/settings.py
AUTHENTICATION_BACKENDS = ["accounts.backends.BreachCheckingBackend"]
Points of care:
password_change.Have I Been Pwned also offers a domain search: after you verify control of a domain (DNS TXT record, e-mail to a domain address, or a file on the website), a paid API key lets you list which addresses on that domain appear in which breaches. For an organisation this is a legitimate way to find staff accounts that need a password reset and awareness training. It requires a paid subscription and the verification step, and the output concerns identifiable employees, so involve your privacy officer and works council where applicable, restrict who sees the results, and use them only to protect those accounts. The call has this shape (illustrative only; requires a paid key and a verified domain, not run for this tutorial):
# ILLUSTRATIVE ONLY: needs a paid HIBP API key and a verified domain
import os
import requests
resp = requests.get(
"https://haveibeenpwned.com/api/v3/breacheddomain/example.com",
headers={"hibp-api-key": os.environ["HIBP_API_KEY"],
"User-Agent": "myproject-security"},
timeout=10,
)
resp.raise_for_status()
# {"alias": ["BreachName", ...], ...} alias = part before the @
print(len(resp.json()), "affected addresses")
Passwords leak from users; API keys, database URLs and signing keys leak from developers. The most common path is a commit: a settings_local.py or .env added by accident, or a token pasted into a test. Two mature open-source scanners complement each other:
Since version 8.19 the subcommands are gitleaks git (history), gitleaks dir (files on disk) and gitleaks stdin. In a throwaway repository with a fake GitHub token committed to settings_local.py:
$ gitleaks git . --redact --no-banner -v
Finding: GITHUB_TOKEN = "REDACTED
Secret: REDACTED
RuleID: github-pat
Entropy: 4.615312
File: settings_local.py
Line: 3
Commit: 400875a376166a865af43b10f54f7b6a97888811
...
Fingerprint: 400875a376166a865af43b10f54f7b6a97888811:settings_local.py:github-pat:3
INF 1 commits scanned.
WRN leaks found: 1
$ echo $?
1
Always use --redact for output that lands in CI logs; otherwise the scanner republishes the secret it found. Add organisation-specific rules in .gitleaks.toml at the repository root, extending the defaults:
# .gitleaks.toml
title = "myproject gitleaks config"
[extend]
useDefault = true
[[rules]]
id = "myproject-internal-api-key"
description = "myproject internal API key"
regex = '''mp_live_[a-z0-9]{32}'''
keywords = ["mp_live_"]
[allowlist]
description = "test fixtures, docs and the detect-secrets baseline"
paths = ['''(^|/)tests/fixtures/''', '''\.md$''', '''\.secrets\.baseline$''']
The last allowlist path matters: when we ran both tools together, gitleaks flagged the hashed_secret values inside detect-secrets' baseline file as generic API keys.
For accepted historical findings (a rotated key in an old commit), prefer a .gitleaksignore file with fingerprints over a JSON baseline report. A --baseline-path report works, but it must be generated without --redact to match, which means the file contains the secret in clear text. The fingerprint file contains only commit, path, rule and line:
# .gitleaksignore
400875a376166a865af43b10f54f7b6a97888811:settings_local.py:github-pat:3
$ detect-secrets scan --exclude-files '(^|/)tests/fixtures/' > .secrets.baseline
$ detect-secrets audit .secrets.baseline # mark each finding true/false positive
The baseline stores a SHA-1 of each finding, its type and its line, never the value itself:
"settings_local.py": [
{
"type": "GitHub Token",
"filename": "settings_local.py",
"hashed_secret": "e175c6f5f2a92e8623bd9a4820edb4e8c1b0fd10",
"is_verified": false,
"line_number": 3
},
...
Commit the baseline. From then on, only secrets not in the baseline fail the hook; a reviewed false positive can also be silenced inline with a # pragma: allowlist secret comment.
# .pre-commit-config.yaml
repos:
- repo: https://github.com/gitleaks/gitleaks
rev: v8.30.1
hooks:
- id: gitleaks
- repo: https://github.com/Yelp/detect-secrets
rev: v1.5.0
hooks:
- id: detect-secrets
args: ["--baseline", ".secrets.baseline"]
exclude: '(^|/)tests/fixtures/'
After pre-commit install, staging a file containing a fake AWS-style secret blocks the commit:
$ pre-commit run
...
Detect secrets...........................................................Failed
- hook id: detect-secrets
- exit code: 1
ERROR: Potential secrets about to be committed to git repo!
Secret Type: Base64 High Entropy String
Location: leak2.py:1
Secret Type: Secret Keyword
Location: leak2.py:1
...
The gitleaks hook is a Go hook; pre-commit downloads a Go toolchain on first use, which takes a minute once. Remember that hooks run on the developer's machine and can be skipped with --no-verify. They are a convenience, not a control.
The server-side check is what you can rely on. A minimal GitHub Actions job that downloads the pinned binary and scans the full history (illustrative, adapt to your CI system):
# .github/workflows/secrets.yml
name: secret-scan
on: [push, pull_request]
jobs:
gitleaks:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0 # full history, not just the last commit
- name: Install gitleaks
run: |
curl -sSL -o gl.tgz https://github.com/gitleaks/gitleaks/releases/download/v8.30.1/gitleaks_8.30.1_linux_x64.tar.gz
tar -xzf gl.tgz gitleaks
- name: Scan
run: ./gitleaks git . --redact --no-banner --exit-code 1
Verify the checksum of the downloaded archive against the release's checksum file before trusting it, and make the job a required status check so a finding blocks the merge. Also enable your code host's own secret scanning and push protection if available; providers that take part in such programmes can revoke their tokens automatically when they are pushed to a public repository.
The order of operations is the whole lesson: rotate first, clean history second. Once a secret has been pushed anywhere others can read, assume it has been copied. Automated scrapers watch public repositories and find new keys within minutes. Rewriting history does not un-copy it.
SECRET_KEY, use SECRET_KEY_FALLBACKS so existing sessions and signed tokens survive the rotation, and remove the fallback afterwards.git filter-repo --replace-text (or BFG), coordinate a force push, and ask collaborators to re-clone. Forks, caches and pull-request refs on the code host may keep old commits; contact the host's support if the repository was public..gitignore.# replacements.txt: one literal per line, replaced with ***REMOVED***
ghp_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
$ git filter-repo --replace-text replacements.txt
$ gitleaks git . --redact --no-banner # confirm the history is clean
Keep replacements.txt out of the repository and delete it afterwards; it contains the secret.
Even with scanning in place, secrets escape through personal forks, gists, pastebins, CI logs and support tickets. Watching for your organisation's own material in public code is legitimate defensive OSINT, within these limits:
mp_live_ above) and a checksum. A prefix makes scanners precise; a checksum lets you reject random strings cheaply and reduces false positives.PwnedPasswordValidator to AUTH_PASSWORD_VALIDATORS with Add-Padding: true, a 2 second timeout and prefix-keyed caching; never log or cache the full hash.validate_password(), and keep offline tests with a mocked range response.--redact in CI on full history as a required check, and detect-secrets with a committed baseline in pre-commit..gitleaksignore fingerprints over a clear-text baseline report, and allowlist .secrets.baseline in gitleaks.Found a mistake in this tutorial? Let us know and we will fix it.