secrets

package
v0.169.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 30, 2026 License: MIT Imports: 15 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package secrets provides built-in secret-pattern scanning for gk push.

Index

Constants

View Source
const (
	ProviderAWS   = "aws"
	ProviderSlack = "slack"
	ProviderGCP   = "gcp"
	ProviderOCI   = "oci"
)

Provider names the issuer that can check a Credential.

View Source
const (
	OCIProfileInvalid          = "invalid_profile"
	OCIProfileUnsupportedRealm = "unsupported_realm"
	OCIProfileNoRegion         = "region_not_found"
)

Reasons a profile cannot be sent to OCI.

View Source
const ArchiveSeparator = "!"

ArchiveSeparator joins an archive path and the path of a file inside it, as in app.jar!BOOT-INF/classes/application.yml. Gitleaks reports archive entries the same way, so a path allowlist written for it matches here too.

View Source
const BinarySniff = 8000

BinarySniff is how far git looks for a NUL byte to call a file binary.

View Source
const (

	// OCIMaxSendable bounds the profiles that can be sent for one key, and
	// so the requests a verifier spends on it.
	OCIMaxSendable = 3
)

Variables

View Source
var BuiltinPatterns = []Pattern{
	literalPattern("aws-access-key", `\bAKIA[0-9A-Z]{16}\b`, true, false, "AKIA"),
	literalPattern("aws-secret-key", `(?i)aws[_-]?(?:secret|sk)[^"']{0,5}["']?([A-Za-z0-9/+=]{40})`, false, true, "aws"),
	literalPattern("github-token", `\bghp_[A-Za-z0-9]{36}\b`, true, false, "ghp_"),
	literalPattern("github-fine", `\bgithub_pat_[A-Za-z0-9_]{82}\b`, true, false, "github_pat_"),
	literalPattern("slack-token", `\bxox[abpr]-[A-Za-z0-9-]{10,}\b`, true, false, "xox"),
	literalPattern("openai-key", `\bsk-[A-Za-z0-9]{20,}\b`, true, false, "sk-"),
	{Kind: "private-key", Regex: regexp.MustCompile(`-----BEGIN (RSA |EC |OPENSSH |DSA |ENCRYPTED |PGP )?PRIVATE KEY-----`)},
	literalPattern("generic-secret", `(?i)(api[_-]?key|secret|token|password)\s*[:=]\s*["']([A-Za-z0-9/_\-+=]{24,})["']`, false, true, "api", "secret", "token", "password"),
}

BuiltinPatterns is the default scan set. Keep it small and high-signal. Each entry must be broadly unambiguous (avoid matching normal code).

View Source
var PayloadFileHeaderRE = regexp.MustCompile(`^>>> gk-file (.+) <<<$`)

PayloadFileHeaderRE matches a single header line. Anchored on both ends so a stray ">>> gk-file foo <<<" appearing inside real content (e.g. quoted in a doc) cannot trigger a false boundary.

View Source
var ZipArchiveExts = []string{".jar", ".war", ".ear", ".zip"}

ZipArchiveExts are the lowercase file extensions that IsZipArchive accepts.

Functions

func CompilePatterns

func CompilePatterns(raw []string) (compiled []*regexp.Regexp, bad []string)

CompilePatterns compiles user-supplied regex strings. Returns compiled list and the list of raw patterns that failed to compile.

func IsLFSPointer added in v0.156.0

func IsLFSPointer(data []byte) bool

IsLFSPointer reports whether data is a Git LFS pointer, which names a file kept outside the repository.

func IsLowEntropySecret

func IsLowEntropySecret(value string) bool

isLowEntropySecret reports whether a matched value is too monotonous to be a real credential. Genuine tokens are near-random over a large alphabet (base62 for github-token/openai-key); fixtures repeat a tiny one — "ghp_0000…0000", "sk-aaaa…aaaa", "1234…". Only values of 20+ characters are judged, so the distinct-rune floor never trips a real key: any real base62 token that long clears 8 distinct characters with overwhelming probability, while reproduction-by-hand fakes do not.

func IsPlaceholderLine

func IsPlaceholderLine(line string) bool

IsPlaceholderLine returns true when the line contains an example/placeholder value (example/dummy/test/changeme/…). Applied to every kind except private-key.

Judged on the whole LINE, not the value alone, because the giveaway usually sits beside the credential — a comment, a variable name, an assert. That breadth is why callers that BLOCK on a hit (the push/ship scanner) drop the finding outright, while callers that merely REDACT (the aicommit privacy gate) keep redacting and only exempt the value from their abort threshold.

func IsZipArchive added in v0.156.0

func IsZipArchive(p string) bool

IsZipArchive reports whether path names an archive in the zip format that the secret scan opens. Gitleaks identifies archives by name and does not treat .jar, .war, or .ear as zip files, so it never reads the configuration packed into a Java build.

func LooksBinary added in v0.156.0

func LooksBinary(data []byte) bool

LooksBinary reports whether data is binary by the test git uses: a NUL byte in the first 8000 bytes.

func MaskLine

func MaskLine(line string) string

MaskLine returns line with every built-in secret match masked in place. The credential value is replaced by its mask() form while the surrounding code (variable names, comments) stays intact, so verbose context output around a hit reads naturally yet never exposes an adjacent secret. For keyword=value kinds (generic-secret) only the value is masked, not the keyword.

func OpensAsZip added in v0.157.0

func OpensAsZip(data []byte) bool

OpensAsZip reports whether archive/zip can open data as a zip file.

func PayloadFileHeader

func PayloadFileHeader(path string) string

PayloadFileHeader formats the file boundary marker that the secret-scan pipeline emits between files in its aggregated blob. The marker uses ">>> gk-file <path> <<<" so it cannot collide with markdown H3 headers (`### foo`) — an earlier `### <path>` convention caused README section titles like "### 첫 호출" to be mistaken for filenames in finding output.

PayloadFileHeaderRE is the matching parser. Both must stay in sync; callers should never hand-roll either.

func SecretValue

func SecretValue(sm []string) string

SecretValue returns the substring worth masking for display. Patterns like generic-secret (group 1 = keyword, group 2 = value) or aws-secret-key (group 1 = value) capture the credential separately from surrounding boilerplate; we mask the last non-empty capture group so the sample shows the value's prefix (e.g. "dev-****") instead of the keyword ("secr****"), which is what a reader needs to judge a false positive. Patterns with no capture groups fall back to the full match.

Exported so the aicommit privacy gate identifies the credential inside its own (differently-grouped) patterns the same way, rather than weighing the whole `key = "value"` match as if it were the secret.

func WalkZip added in v0.156.0

func WalkZip(data []byte, limits ZipLimits, fn func(name, content string)) (unread int, err error)

WalkZip calls fn for each regular file in the zip archive data, in archive order, and returns how many files it could not read. Content is "" for a binary file, so only path rules apply to it. A file that is larger than limits.EntryBytes or than what is left of limits.TotalBytes, that uses a compression method Go cannot read, or whose data is corrupt is not passed to fn. Archives inside the archive are not opened: content scanned there is the archive's own configuration, and a nested jar is a dependency.

Types

type Credential added in v0.156.0

type Credential struct {
	// contains filtered or unexported fields
}

Credential is a raw credential a scan found, kept for live verification: an AWS access key ID with the secret candidates and session token next to it, a Slack token, a GCP API key, or an OCI API signing key with the profiles that name its fingerprint. Every formatter and encoder sees only the masked value, so a finding that carries one can be printed or marshaled without leaking.

A private-key finding carries a candidate: the PEM text with no provider. It is not verifiable until BindOCI pairs it with a profile.

The scanner constructors copy their values: a credential outlives the scanned text, and a substring of it would keep all of it in memory.

func BindOCI added in v0.156.0

func BindOCI(candidate *Credential, profiles []OCIProfile) *Credential

BindOCI pairs a private-key candidate with the profiles that name its fingerprint and returns the OCI credential, or nil when the PEM is not an unencrypted RSA key of an accepted size or no profile names it. The fingerprint is computed from the key, so the pairing does not depend on where the profile and the key sit: they can be in different files or commits. The profiles are kept in the order given, bounded as AppendOCIProfile describes.

func KeyCandidate added in v0.156.0

func KeyCandidate(pemText string) *Credential

KeyCandidate wraps the PEM text of a private-key finding so a later pass can test whether it is an OCI API signing key. It returns nil for a block too large to be one.

func NewAWSCredential added in v0.155.0

func NewAWSCredential(keyID string, secretCandidates []string, token string) *Credential

NewAWSCredential builds an AWS credential directly; scanners use PairAWS.

func NewOCICredential added in v0.156.0

func NewOCICredential(key *rsa.PrivateKey, profiles []OCIProfile) *Credential

NewOCICredential builds an OCI credential directly; scanners use BindOCI.

func NewTokenCredential added in v0.156.0

func NewTokenCredential(provider, kind, value string) *Credential

NewTokenCredential builds a single-value credential directly; scanners use TokenCredential.

func PairAWS added in v0.155.0

func PairAWS(lines []string, idx int, keyID string) *Credential

PairAWS collects the secret access key candidates and the session token around lines[idx], which holds keyID. It searches the raw lines instead of other findings because the generic-api-key finding for a secret on the key ID's own line is dropped as shadowed. Candidates on lines that mention "secret" come first, then nearer lines.

func TokenCredential added in v0.156.0

func TokenCredential(ruleID, line string, col int, match string) *Credential

TokenCredential returns the credential for a finding of a token rule, or nil for any other rule. Several Slack rules bound the length of the token tail, so the match can stop inside a longer token, and a truncated token would read as invalid. The value is therefore extended to the end of the token's character run on the raw line. col is where match starts in line: two tokens on one line can share the same truncated match, so the match text alone does not say which token a finding belongs to. If line does not hold match at col, the value is match as is.

func (*Credential) GoString added in v0.156.0

func (c *Credential) GoString() string

func (*Credential) ID added in v0.156.0

func (c *Credential) ID() string

ID identifies the credential across findings: the same value found in several files or commits has one ID. It contains the raw value.

func (*Credential) Kind added in v0.156.0

func (c *Credential) Kind() string

Kind returns the scanner rule ID that found the credential.

func (*Credential) MarshalJSON added in v0.156.0

func (c *Credential) MarshalJSON() ([]byte, error)

MarshalJSON keeps raw values out of any encoded finding.

func (*Credential) Masked added in v0.156.0

func (c *Credential) Masked() string

Masked shows the value's first and last four characters.

func (*Credential) OCIKey added in v0.156.0

func (c *Credential) OCIKey() *rsa.PrivateKey

OCIKey returns the parsed private key of an OCI credential, or nil.

func (*Credential) OCIProfiles added in v0.156.0

func (c *Credential) OCIProfiles() []OCIProfile

OCIProfiles returns the profile candidates of an OCI credential, nearest first.

func (*Credential) Provider added in v0.156.0

func (c *Credential) Provider() string

Provider returns one of the Provider constants.

func (*Credential) SecretCandidates added in v0.156.0

func (c *Credential) SecretCandidates() []string

SecretCandidates returns the raw AWS secret access key candidates, nearest first.

func (*Credential) SessionToken added in v0.156.0

func (c *Credential) SessionToken() string

SessionToken returns the raw AWS session token, or "" when none was found.

func (*Credential) String added in v0.156.0

func (c *Credential) String() string

func (*Credential) Value added in v0.156.0

func (c *Credential) Value() string

Value returns the raw AWS access key ID, Slack token, or GCP API key. For an OCI key it is the key fingerprint, which is not a secret, and for a private-key candidate it is empty: the PEM is never part of Value or ID.

func (*Credential) Verifiable added in v0.156.0

func (c *Credential) Verifiable() bool

Verifiable reports whether an issuer can check the credential. A private-key candidate that no OCI profile names is not verifiable.

type Finding

type Finding struct {
	Kind string // short label: "aws-access-key", "github-token", "private-key", ...
	Line int    // 1-based line number within the input blob (kept verbatim for
	// callers — e.g. aicommit — that remap blob lines themselves)
	File     string // owning file path, recovered from PayloadFileHeader markers; "" when none present
	FileLine int    // 1-based line within File; equals Line when no file header precedes the hit
	// Commit is the introducing git commit when the input is `git log -p` output.
	Commit string `json:"commit,omitempty"`
	Sample string // a masked sample suitable for display
	// Secret is the value that Sample masks. It formats masked too; only
	// Secret.Reveal returns the value.
	Secret Secret `json:"-"`
	// LineText, ContextBefore, and ContextAfter back verbose ("show the
	// surrounding source") output. They are populated only by diff-aware
	// callers (the push/ship scanner) and are all secret-masked, so printing
	// them never leaks an adjacent credential. Empty when not collected or at
	// a hunk edge.
	LineText      string `json:"line_text,omitempty"`
	ContextBefore string `json:"context_before,omitempty"`
	ContextAfter  string `json:"context_after,omitempty"`
	// Credential is set on an embedded-engine finding that
	// `gk guard check --verify` can test (AWS, Slack, GCP); it formats masked.
	Credential *Credential `json:"-"`
}

Finding is a single secret-pattern hit.

func Scan

func Scan(blob string, extra []*regexp.Regexp) []Finding

Scan scans blob for secret findings. extra lets callers append user-provided compiled regexes from config. Returns findings in line order; multiple findings per line are included.

func (Finding) Location

func (f Finding) Location() string

Location renders the finding's position for display: "file:line" when the owning file is known (the scan input carried PayloadFileHeader markers), otherwise "line N" using the raw blob position. Keeps push/ship output in sync from a single source.

type OCIProfile added in v0.156.0

type OCIProfile struct {
	Fingerprint string
	User        string
	Tenancy     string
	Region      string
}

OCIProfile is the identity half of an OCI API signing key: the values an OCI config, Terraform variable file, or environment file keeps next to the key fingerprint. None of them is a secret. Region is "" when none was found near the fingerprint.

func AppendOCIProfile added in v0.156.0

func AppendOCIProfile(list []OCIProfile, p OCIProfile) []OCIProfile

AppendOCIProfile adds p to the candidates for one key and keeps the list bounded: at most OCIMaxSendable profiles that can be sent, and at most one that cannot. Only sendable profiles count toward the limit, because a profile that cannot be sent would otherwise push out one that can. The one unsendable profile stays for two reasons: it carries the reason when nothing can be sent, and it keeps a key that has other candidates from looking like a key with a single profile.

func FindOCIProfiles added in v0.156.0

func FindOCIProfiles(text string) []OCIProfile

FindOCIProfiles returns the OCI profile candidates in text, which is a file's content or a raw diff. A fingerprint anchors each profile; the user OCID, tenancy OCID, and region come from the lines around it. When several values are in range, the nearest combinations come first, bounded for each fingerprint occurrence as AppendOCIProfile describes. A region counts only on a line that mentions "region", so another hyphenated word is not taken for one.

In a diff, removed lines count too. The pair is made by fingerprint, so a profile that a commit deleted still names its key.

func (OCIProfile) Problem added in v0.156.0

func (p OCIProfile) Problem() string

Problem returns the reason the profile cannot be sent to OCI, or "". The values come from repository text and become the request host, path, and key ID, so the patterns here are anchored. A verifier must call Problem on each profile right before it builds the request, whatever filtered the list before.

type Pattern

type Pattern struct {
	Kind  string
	Regex *regexp.Regexp
	// contains filtered or unexported fields
}

Pattern is a named regex.

type Secret added in v0.167.0

type Secret struct {
	// contains filtered or unexported fields
}

Secret holds a secret value that a finding matched. A Finding or a Violation carries it, and it must not leak through them into logs, errors, or agent output: only Reveal returns the value.

Where fmt can call its methods, it prints masked in every verb: formatted directly, through a pointer, or in an exported field. fmt cannot call them for %p, for a verb that it rejects for the value, or for a field that is not exported; there it prints what the struct holds. So the value is behind a pointer, which fmt prints as an address and does not follow. JSON gets the masked text.

func NewSecret added in v0.167.0

func NewSecret(v string) Secret

NewSecret wraps a matched value. No value gives the zero Secret.

func (Secret) Format added in v0.167.0

func (s Secret) Format(f fmt.State, verb rune)

Format prints the masked text for every verb. The verbs for a string (%s, %q, %x, %X) apply to it. Any other verb prints it as %s does: without this method fmt uses String for %v only, and prints the fields of the struct for a verb such as %d.

func (Secret) GoString added in v0.167.0

func (s Secret) GoString() string

func (Secret) MarshalJSON added in v0.167.0

func (s Secret) MarshalJSON() ([]byte, error)

MarshalJSON keeps the value out of any encoded finding.

func (Secret) Reveal added in v0.167.0

func (s Secret) Reveal() string

Reveal returns the value. Callers print it only when the user asked to see it.

func (Secret) String added in v0.167.0

func (s Secret) String() string

type ZipLimits added in v0.156.0

type ZipLimits struct {
	// Entries is the most entries an archive may list.
	Entries int
	// EntryBytes is the largest decompressed size of one entry.
	EntryBytes int64
	// TotalBytes is the most that the entries of one archive may
	// decompress to together.
	TotalBytes int64
}

ZipLimits bound what WalkZip reads from one archive. A repository can hold any blob, including one built to expand without end.

Directories

Path Synopsis
Package gitleaksrules scans unified diffs with the gitleaks default ruleset embedded in the gk binary, so secret scanning works without the gitleaks binary installed.
Package gitleaksrules scans unified diffs with the gitleaks default ruleset embedded in the gk binary, so secret scanning works without the gitleaks binary installed.
codec
Package codec decodes base64, hex, percent, and unicode escapes in place so the rules can run on the decoded text, and maps decoded matches back to their location in the original text.
Package codec decodes base64, hex, percent, and unicode escapes in place so the rules can run on the decoded text, and maps decoded matches back to their location in the original text.
Package verify checks whether credentials found by a secret scan are live, with one read-only identity call to the issuer:
Package verify checks whether credentials found by a secret scan are live, with one read-only identity call to the issuer:

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL