Sub topic 12
Writing custom patterns for internal secrets
Provider patterns cover credentials issued by vendors such as cloud platforms and payment processors. They can't recognize tokens your own company issues. This chapter covers custom patterns, which teach secret scanning your internal token formats. It also covers how to write them, test them, and publish them without flooding people with false positives.
This chapter assumes you know what secret scanning alerts and push protection do, and that you can read basic regular expressions. You should also be comfortable with the repository and organization settings pages.
When a custom pattern is worth writing
Write a custom pattern when all of these are true:
- Your organization issues the credential itself, for example a service-to-service token or an internal API key.
- The credential has a recognizable shape, such as a fixed prefix, a fixed length, or a known character set.
- A leak would matter. Internal credentials often unlock systems that no outside provider can revoke for you.
Don't write one for credentials that a supported provider already issues. The provider pattern is maintained for you, and it may have validity checks, which custom patterns don't have.
Where custom patterns live
You can define a custom pattern at three levels.
| Level | Applies to | Typical use |
|---|---|---|
| Repository | That repository only | A pattern for one service's token, or a first draft you're still testing |
| Organization | Every repository in the organization where scanning is enabled | The normal home for company-wide token formats |
| Enterprise | Repositories across the enterprise's organizations | Formats shared by several organizations |
Limits on how many patterns you can define per level change over time. Check the current documentation if you plan to define many. Patterns are only evaluated where secret scanning is enabled, so a pattern published at organization level does nothing in a repository that has the feature turned off.
The parts of a custom pattern
The pattern form has several fields.
- Pattern name. This appears on every alert, so choose something a responder can act on, such as
Acme internal service token. - Secret format. A regular expression that matches the secret itself.
- Before secret. A regular expression for the characters allowed immediately before the secret. The default accepts the start of the file or a character that isn't alphanumeric.
- After secret. The same idea for the characters after the secret.
- Additional match requirements. Optional extra regular expressions that the matched secret must match, or must not match.
The before and after fields stop matches in the middle of longer strings. Without them, a 32-character pattern could fire on the first 32 characters of a 64-character hash. The defaults suit most cases, so change them only when your token is routinely written next to other alphanumeric characters.
Regex flavor
Secret scanning uses the Hyperscan regular expression library. It supports most common syntax: character classes, bounded repetition, alternation, and groups. It doesn't support constructs that need backtracking, such as lookahead, lookbehind, and backreferences. If you test a pattern in a tool that accepts those constructs, remove them before you paste the pattern into GitHub.
A worked example
Suppose your company issues tokens that look like acme_ followed by 32 letters and digits. The secret format is:
acme_[A-Za-z0-9]{32}Documentation and test code often contain obviously fake tokens such as acme_ followed by 32 zeros. Add an additional match requirement of type "must not match":
acme_(0{32}|x{32}|EXAMPLE[A-Za-z0-9]{25})Before you paste a pattern into GitHub, run it against real and fake samples locally. The script below uses Python's re module, which is close enough for simple patterns like this one. It doesn't reproduce Hyperscan's exact behavior, so the GitHub test step still has the final word.
import re
secret_format = re.compile(r"acme_[A-Za-z0-9]{32}")
must_not_match = re.compile(r"acme_(0{32}|x{32}|EXAMPLE[A-Za-z0-9]{25})")
samples = {
"real-looking token": "token = acme_Qp7ZkL2mR9vXw4TnB8cY1dHs6JfGa3Ue",
"all zeros placeholder": "token = acme_00000000000000000000000000000000",
"too short": "token = acme_abc123",
}
for label, text in samples.items():
for match in secret_format.finditer(text):
found = match.group(0)
if must_not_match.fullmatch(found):
result = "excluded by must-not-match"
else:
result = "would alert"
print(f"{label}: {found} -> {result}")
else:
if not secret_format.search(text):
print(f"{label}: no match")Running it prints one line per sample. The first would alert, the second is excluded, and the third doesn't match at all.
From draft to published
GitHub gives you a staged workflow. Use every stage, because a bad pattern is noisy and the noise lands on other teams.
- Open the pattern form from the repository or organization security settings and enter the name and the secret format.
- Add before, after, and additional match requirements as needed.
- Paste sample text into the test field. Include at least one string that should match and one that shouldn't. Confirm that GitHub highlights only what you expect.
- Run a dry run. For a repository-level pattern, the dry run scans that repository. For an organization-level pattern, you choose a set of repositories to scan. The result is a list of matches, and nothing is published or alerted.
- Read the dry run results. Check for false positives, then adjust the pattern and rerun until the matches are almost all real.
- Publish the pattern. From then on, new matches in scanned repositories raise alerts, and existing content is scanned as well.
Push protection for custom patterns
Publishing a pattern creates alerts. It doesn't block pushes by default. Push protection for a custom pattern is a separate switch that you turn on after publishing. Enable it only when the dry run showed that the pattern rarely fires on harmless content. A noisy pattern with push protection on means developers hit blocks they can't reasonably fix, and they will start using the bypass option out of habit. That undermines the bypass reasons you rely on during triage.
A reasonable sequence is:
- Publish with alerts only.
- Watch the alerts for a week or two and close false positives. Tighten the pattern if they recur.
- Enable push protection once the alerts are overwhelmingly real.
Editing and maintaining patterns
Changing a published pattern causes GitHub to rescan, so you can expect alerts to appear or, for false positives, to stop appearing. Tighten a pattern gradually and use the dry run again after significant edits, because a small change to a character class can change the match count a great deal.
Keep these habits:
- Record what the pattern is for and who owns the credential in the pattern name or in your internal documentation, so a responder knows who can revoke a matching token.
- Prefer a distinctive prefix when you design new internal tokens. A prefix like
acme_makes detection precise. Tokens that are plain 40-character hex strings are close to indistinguishable from commit hashes and checksums. - Review alert volume per pattern from time to time. A pattern that produces mostly closed false positives needs a tighter format.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Pattern saves but never matches | Lookahead, lookbehind, or a backreference that Hyperscan doesn't support, or a typo in the format | Rewrite without those constructs and retest with sample text |
| Hundreds of matches on hashes or IDs | Format is too generic, such as `[A-Za-z0-9]{40}` | Add a prefix, add a must-not-match requirement, or constrain the surrounding characters |
| Real tokens are missed | Before or after fields reject the characters next to the token, such as a quote or an underscore | Adjust the before and after expressions |
| No alerts in some repositories | Secret scanning is disabled there, or the organization pattern wasn't in the dry run scope you assumed | Enable scanning on those repositories |
| Alerts appear but pushes aren't blocked | Push protection for the custom pattern wasn't enabled | Enable it for the published pattern |
A custom pattern alert also lacks a validity status, since GitHub can't ask your internal system whether a token is still active. During triage you have to check that yourself with the owning team, then revoke and rotate as described in the remediation chapter.
Exercises
Exercise
Your internal tokens look like svc- followed by 40 lowercase hexadecimal characters. A dry run of the pattern [a-f0-9]{40} returns thousands of matches, mostly Git commit hashes. Rewrite the secret format so it targets your tokens, and name the stage of the workflow that exposed the problem.
Show answer
Use svc-[a-f0-9]{40}. The fixed prefix svc- separates real tokens from commit hashes, which have no such prefix. The dry run stage exposed the problem, because it shows real matches in your repositories without publishing the pattern or creating alerts.
Exercise
You published a custom pattern and enabled push protection for it on the same day. Developers now report blocked pushes containing obvious placeholder values like acme_ followed by 32 zeros. What two changes would you make, and what should you have done differently?
Show answer
Add an additional match requirement of type "must not match" for the placeholder values, or tighten the format, and consider turning off push protection for the pattern until the false positives stop. You should have published with alerts only first, watched the alert volume and closed false positives, and enabled push protection after the matches were almost all real.