leakgate

package
v0.209.1 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: Apache-2.0 Imports: 21 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 leakgate is the pure scanner behind the H-55 leak gate.

The repository is public, so the names of the operator's machines, people and brands must never reach the tracked tree. The gate scans the tracked files (and their names) for a list of denied entries and fails on any hit. The list itself is a secret: the committed form of it is a file of keyed digests (HMAC-SHA256), so the gate can say "this file contains a denied name" without the repository ever holding the name.

This package is the whole matcher and nothing else. It reads no environment variable and starts no process: the key is passed in, the file system is a small interface (so an unreadable file, a deleted file or a 17 MiB file is a unit test, not a disk experiment), and the git plumbing lives in the command that calls it. The pieces:

  • entries and the list file (this file), the matcher and tokenizer (match.go);
  • the fold that makes encoded spellings visible (fold.go, foldtable.go);
  • the PNG chunk walk (png.go) and the tree scan with its fail-closed rules (scan.go);
  • the keyless shape rules (shape.go);
  • the digest file, its MAC and key selection (digest.go) and key resolution (key.go).

Index

Constants

View Source
const (
	DigestVersion = 2
	DigestAlgo    = "hmac-sha256"
)

Version and algorithm of the digest file format.

View Source
const (
	WhyBinary    = "binary"
	WhyOversize  = "oversize"
	WhyLongRun   = "longrun"
	WhySymlink   = "symlink"
	WhySubmodule = "submodule"
)

The reasons an exempt row may give.

View Source
const (
	EnvKey      = "OFFLOAD_LEAK_GATE_KEY"
	EnvKeyPrev  = "OFFLOAD_LEAK_GATE_KEY_PREV"
	EnvKeyFile  = "OFFLOAD_LEAK_GATE_KEY_FILE"
	EnvRequired = "OFFLOAD_LEAK_GATE_REQUIRED"
)

Environment variable names the gate reads (the caller reads them; this package never touches the environment).

Variables

View Source
var (
	ErrMalformedKey     = errors.New("malformed gate key")
	ErrMalformedPrevKey = errors.New("malformed previous gate key")
	ErrKeyFile          = errors.New("gate key file")
	ErrKeyMissing       = errors.New("key missing where secrets exist")
	ErrBadRequired      = errors.New("unrecognized " + EnvRequired + " value")
	ErrMACMismatch      = errors.New("digest file does not match this key")
	ErrBlind            = errors.New("gate went blind")
)

The messages are part of the contract: the behaviour matrix and the operator documentation quote them.

View Source
var (
	ErrPNGSignature = errors.New("png: bad signature")
	ErrPNGOverflow  = errors.New("png: chunk length overflows the file")
	ErrPNGNoIEND    = errors.New("png: missing IEND")
	ErrPNGInflate   = errors.New("png: compressed text over the 16 MiB cap")
	ErrPNGCorrupt   = errors.New("png: corrupt compressed text chunk")
)

The walk's fatal conditions.

Functions

func AllowDigest

func AllowDigest(key []byte, chunk string) string

AllowDigest is the keyed digest of an allow-row chunk (lower case).

func BlankEscapes

func BlankEscapes(b []byte) ([]byte, bool)

BlankEscapes is pass B. It returns b itself and false when there is no escape to blank, and otherwise a copy with every escape replaced in place by spaces of the same length (so every column equals pass A's).

func CanaryText

func CanaryText() string

CanaryText is the entry the generator always appends (mode sub).

func DecodeKey

func DecodeKey(s string) ([]byte, error)

DecodeKey reads a key: exactly 64 hex characters (either case), 32 bytes.

func Fold

func Fold(b []byte) []byte

Fold is pass A. Callers check NeedsFold first; on text with nothing to fold it returns an equal copy.

func IsPNG

func IsPNG(data []byte) bool

IsPNG reports whether data starts with the PNG signature.

func NeedsFold

func NeedsFold(b []byte) bool

NeedsFold reports whether b holds a byte at or above 0x80 or the two bytes \u, the only inputs the fold changes.

func ParseRequired

func ParseRequired(v string) (bool, error)

ParseRequired reads OFFLOAD_LEAK_GATE_REQUIRED: empty is off, exactly "1" is on, anything else is an error (a typo must not silently switch the gate off).

func PatternBlock

func PatternBlock(es []Entry) string

PatternBlock is the pattern lines bracketed by BEGIN and END marker comments, so a re-run replaces the block (ReplaceBlock).

func Patterns

func Patterns(es []Entry) []string

Patterns returns the ERE lines for the list, in list order.

func ReplaceBlock

func ReplaceBlock(existing, block string) string

ReplaceBlock puts block into existing: in place of the previous BEGIN to END block when there is one, at the end of the text otherwise. block uses LF; a text that uses CRLF gets the block with CRLF.

func ResolveFileList

func ResolveFileList(specs []FileSpec, tracked map[string]bool) (map[string]bool, error)

ResolveFileList turns a parsed list into the set of tracked paths to scan. A path that is listed (not optional) and not tracked is an error, and so is a rename with both sides or neither side tracked.

func SelectKey

func SelectKey(df *DigestFile, k Keys) ([]byte, error)

SelectKey picks the key that verifies the file: the current key, else the previous one (a rotation in flight). No key is ErrKeyMissing; neither verifying is ErrMACMismatch (the message says nothing about either key).

func ValidateEntries

func ValidateEntries(es []Entry) error

ValidateEntries applies the generator's validation to a list (entries are normalized first): at least four characters for sub, subcs and word, three for exact, two or three words for a phrase, ASCII letters and digits only (spaces only between phrase words), no duplicate within a mode.

Types

type AllowRow

type AllowRow struct {
	Where string `json:"where"`
	Path  string `json:"path"`
	D     string `json:"d"`
}

AllowRow allows one finding: Where is "name" or "body", D the keyed digest (AllowDigest) of the lower-case chunk of [A-Za-z0-9_.-] around the finding. No row ships today.

type Classes

type Classes struct {
	Runs96        int // runs over 96 characters
	Binaries      int // unknown binary files (name scanned only)
	PNGNonStd     int // PNG files with a chunk other than IHDR, tEXt, IDAT, IEND
	PNGAfterIEND  int // PNG files with bytes after IEND
	PNGCompressed int // PNG files with compressed text
	PNGNoIEND     int // PNG files that could not be walked to IEND
	Oversize      int
	Symlink       int
	Submodule     int
}

Classes count the inputs where the specified scanner and the reference oracle differ; each is a precondition of the parity check (zero, or the result is "not comparable").

type Decision

type Decision struct {
	Enforce    bool   // run the gate
	SkipReason string // when not enforcing: the visible reason to log
}

Decision is what the tree gate does with the resolved keys.

func Decide

func Decide(k Keys, required bool) (Decision, error)

Decide covers the key rows of the behaviour matrix: with a key the gate enforces; without one it is fatal where secrets exist (required) and a visible skip elsewhere (a fork's pull request, a contributor's machine, a source tarball). A previous key alone never counts as the key.

type DigestEntry

type DigestEntry struct {
	D    string `json:"d"`
	Mode string `json:"mode"`
	Len  int    `json:"len,omitempty"`
	N    int    `json:"n,omitempty"`
	F    string `json:"f,omitempty"`
}

DigestEntry is one hashed entry. Len is the entry length (window modes), N the word count and F the first-word prefilter (phrases).

func EntryDigest

func EntryDigest(key []byte, e Entry) DigestEntry

EntryDigest hashes one normalized entry.

type DigestFile

type DigestFile struct {
	Version int           `json:"version"`
	Algo    string        `json:"algo"`
	MAC     string        `json:"mac"`
	Entries []DigestEntry `json:"entries"`
	Allow   []AllowRow    `json:"allow"`
	Exempt  []ExemptRow   `json:"exempt"`
}

DigestFile is the parsed digest file.

func BuildDigest

func BuildDigest(key []byte, es []Entry, allow []AllowRow, exempt []ExemptRow) (*DigestFile, error)

BuildDigest hashes a plaintext list (plus the canary, which it always appends) under key and returns the signed digest file. The list is validated; allow and exempt rows are copied, sorted and validated.

func ParseDigest

func ParseDigest(b []byte) (*DigestFile, error)

ParseDigest reads a digest file strictly (unknown fields, trailing data and every structural defect are errors). It does not verify the mac: that needs the key (SelectKey).

func (*DigestFile) ComputeMAC

func (df *DigestFile) ComputeMAC(key []byte) string

ComputeMAC is HMAC-SHA256(key, "leakgate/2" + the canonical text of the entries, allow rows and exempt rows), as hex.

func (*DigestFile) Marshal

func (df *DigestFile) Marshal() ([]byte, error)

Marshal is the committed form: LF line endings, one row per line, one trailing newline, byte-for-byte reproducible.

func (*DigestFile) Validate

func (df *DigestFile) Validate() error

Validate checks the structure of the file without a key: version and algorithm, hex lengths, entries sorted by digest and unique, per-mode field rules, and sorted unique allow and exempt rows with known places and reasons.

func (*DigestFile) VerifyMAC

func (df *DigestFile) VerifyMAC(key []byte) bool

VerifyMAC reports whether the file's mac is the one key computes.

type DirFS

type DirFS struct{ Root string }

DirFS reads tracked paths (slash-separated, relative) from a work tree.

func (DirFS) Read

func (d DirFS) Read(path string, max int64) ([]byte, int64, error)

Read implements FS. A path that is absolute, contains "..", or uses a backslash is refused, and so is anything but a regular file.

type Entry

type Entry struct {
	Mode Mode
	Text string
}

Entry is one denied name. Text is normalized: lower case (case preserved for subcs) and, for a phrase, words joined by one space.

func ParseList

func ParseList(b []byte) ([]Entry, error)

ParseList reads the plaintext list: one entry per line, `mode<TAB>text`, a line whose first non-blank character is `#` is a comment. Entries are normalized and validated; an error names the line and never the entry text (the text may be a real name and error messages travel).

func WithCanary

func WithCanary(es []Entry) []Entry

WithCanary returns a copy of es with the canary appended.

type ExemptRow

type ExemptRow struct {
	Path string `json:"path"`
	Blob string `json:"blob"`
	Why  string `json:"why"`
}

ExemptRow exempts one file from one fail-closed rule, bound to the file's git blob id so editing the file un-exempts it.

type FS

type FS interface {
	Read(path string, max int64) (data []byte, size int64, err error)
}

FS is how the scan reaches file contents: the work tree, the blobs of a commit, or memory in a test.

Read returns the file's size and, when size <= max, its bytes. A larger file is not read (data is nil and size says how large it is). A missing file is an error satisfying errors.Is(err, fs.ErrNotExist).

type Fatal

type Fatal struct {
	Path   string
	Line   int
	Reason string
}

Fatal is a fail-closed record: a path (empty for a whole-scan condition), a line for a run over the limit, and a reason that never carries matched text.

type FileSpec

type FileSpec struct {
	Path     string
	Old, New string
	Optional bool
}

FileSpec is one parsed entry: either Path (Optional or not), or Old and New.

func ParseFileList

func ParseFileList(text string) ([]FileSpec, error)

ParseFileList parses a -files list.

type Finding

type Finding struct {
	Path string
	Line int
	Col  int
	Mode string
	ID   string
	Text string
	Name bool
}

Finding is one hit. Path is the tracked path; a name finding (Name) is a hit in the path itself. Line is 1-based; Col is the 1-based byte offset in the folded line. A plaintext matcher fills Text with the entry text; a digest matcher fills ID with the first four bytes of the entry digest (hex) and leaves Text empty, so its output never carries matched text. Shape findings carry the rule name in Text.

func ShapeFindings

func ShapeFindings(path string, data []byte) []Finding

ShapeFindings applies both rules to one text body (the bytes as read, after UTF-16 decoding or PNG text extraction, before the fold). The column is the 1-based byte offset of the match in its line.

func (Finding) DisplayPath

func (f Finding) DisplayPath() string

DisplayPath is Path, with " (name)" appended for a name finding.

func (Finding) Label

func (f Finding) Label() string

Label is the entry part of a finding line: "mode:text" for a plaintext matcher (the oracle's form), "id=<8 hex> mode" for a digest matcher, and "shape:<rule>" for a shape rule.

func (Finding) String

func (f Finding) String() string

String is the output form: path:line:col label.

type Keys

type Keys struct {
	Key  []byte
	Prev []byte
}

Keys are the resolved keys: Key is the current key and Prev the previous one (rotation), each nil when unset.

func ResolveKey

func ResolveKey(getenv func(string) string, readFile func(string) ([]byte, error), defaultFile string) (Keys, error)

ResolveKey resolves the gate key and the previous key.

  1. OFFLOAD_LEAK_GATE_KEY, when non-empty, must be 64 hex characters, else ErrMalformedKey; the key file is then never read.
  2. Else OFFLOAD_LEAK_GATE_KEY_FILE, when non-empty: the file must exist, be readable and hold 64 hex characters, else ErrKeyFile (the operator asked for that file).
  3. Else defaultFile, when given and the file exists (present but unreadable or malformed is ErrKeyFile; absent is unset).

OFFLOAD_LEAK_GATE_KEY_PREV is read only when a key was found: empty is ignored, non-empty must be 64 hex characters (else ErrMalformedPrevKey), and it never counts as the key by itself. With no key, a previous key (valid or not) is ignored: the gate is keyless and the rows for a missing key apply.

type Matcher

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

Matcher is the compiled entry list, either plaintext (NewPlainMatcher) or keyed (NewDigestMatcher). It is read-only after construction and safe for concurrent use; the mutable scan state lives in a Scanner.

func NewDigestMatcher

func NewDigestMatcher(df *DigestFile, key []byte) (*Matcher, error)

NewDigestMatcher compiles a digest file with its key. The caller has already chosen the key that verifies the file's MAC (SelectKey); this checks the file's structure and builds the tables from the digests alone.

func NewPlainMatcher

func NewPlainMatcher(es []Entry) (*Matcher, error)

NewPlainMatcher compiles a plaintext list (used by the local scanner, the parity check and the tests). Entries are normalized and validated.

func (*Matcher) NewScanner

func (m *Matcher) NewScanner() *Scanner

NewScanner returns a scanner of m. A Scanner is not safe for concurrent use.

func (*Matcher) ScanName

func (m *Matcher) ScanName(path string) []Finding

ScanName scans a tracked path as one line; the findings are name findings.

func (*Matcher) ScanText

func (m *Matcher) ScanText(path string, data []byte) ([]Finding, []int)

ScanText scans one text body (UTF-8; the caller has already decoded UTF-16 or extracted PNG text) and returns the findings under path and the line of every run over 96 characters.

func (*Matcher) SelfTest

func (m *Matcher) SelfTest() error

SelfTest scans a synthetic buffer holding the canary and fails when the matcher does not flag it: a blind matcher must fail loudly wherever a scan runs, even where the tree gate skips.

type Mode

type Mode string

Mode is how an entry matches. See the package documentation of the design:

sub     any window of one alphanumeric run (lower case)
word    a sub window with letter boundaries (a camel cut, a digit or a
        non-letter ends a word; a plural or a longer word does not match)
exact   the whole run equals the entry (no camel splitting)
subcs   a sub window compared as written, case preserved
phrase  two or three consecutive runs on one line
const (
	ModeSub    Mode = "sub"
	ModeWord   Mode = "word"
	ModeExact  Mode = "exact"
	ModeSubCS  Mode = "subcs"
	ModePhrase Mode = "phrase"
)

The five entry modes.

type PNGInfo

type PNGInfo struct {
	Segments       [][]byte
	NonStd         bool // a chunk other than IHDR, tEXt, IDAT and IEND
	AfterIEND      bool // bytes after IEND
	CompressedText bool // a zTXt chunk or a compressed iTXt chunk
	NoIEND         bool // no IEND reached: truncated, or a length that overflows the file
}

PNGInfo is what the walk found. Segments are the byte ranges to scan, in a fixed order: the text chunks first (tEXt, zTXt and iTXt, in file order; the keyword is kept and a compressed body is inflated), so that the line numbers of a text finding equal those of a scan of the text chunks alone; then the bodies of every other chunk but IDAT; then the bytes after IEND. A scan joins them with a newline.

func ParsePNG

func ParsePNG(data []byte) (PNGInfo, error)

ParsePNG walks the chunks of a PNG. It returns what could be extracted even when it also returns an error, so a scan can still read what is there before it fails.

type Report

type Report struct {
	Findings []Finding
	Fatals   []Fatal
	Scanned  int // files scanned (after the filter)
	Total    int // tracked files
	Missing  int // tracked paths missing from the work tree (name scanned only)
	Classes  Classes
}

Report is the result of a tree scan.

func ScanTree

func ScanTree(m *Matcher, files []TrackedFile, fsys FS, opts ScanOptions) Report

ScanTree scans a set of tracked files. m may be nil: with Shapes set that is the keyless mode (shape rules and the fail-closed rows only, no name scan).

type ScanOptions

type ScanOptions struct {
	// Required: a tracked path missing from the work tree, and an empty file
	// set, are fatal (a clean checkout is expected).
	Required bool
	// Shapes also applies the keyless shape rules.
	Shapes bool
	// Exempt rows exempt a file from one fail-closed rule.
	Exempt []ExemptRow
	// Allow rows allow one finding each (a keyed matcher only).
	Allow []AllowRow
	// Workers is the number of scanning goroutines (default: the CPU count).
	Workers int
	// MaxFile is the size limit in bytes (default 16 MiB).
	MaxFile int64
	// Filter, when set, restricts the scan to the paths it accepts; the rest are
	// not scanned and not reported (they still count in Report.Total).
	Filter func(path string) bool
}

ScanOptions configure ScanTree.

type Scanner

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

Scanner is the per-goroutine scan state of a Matcher.

type TrackedFile

type TrackedFile struct {
	Mode string
	Blob string
	Path string
}

TrackedFile is one row of `git ls-files -z -s`: the mode, the object id and the path. The library needs the mode to see symlinks and submodules.

func ParseLsFiles

func ParseLsFiles(b []byte) ([]TrackedFile, error)

ParseLsFiles parses the output of `git ls-files -z -s`: "<mode> <object> <stage><TAB><path>" records, each ending in a NUL. A non-zero stage (an unmerged path) is an error.

Jump to

Keyboard shortcuts

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