Documentation
¶
Overview ¶
Package blindindex builds searchable, keyed representations of documents so that a datastore can answer "which documents might contain this term?" without ever storing the terms themselves.
Each document becomes a Bloom filter of HMAC digests, one filter per document. Holding a filter without the key tells you nothing about which terms produced it. Holding the key lets you test any term against it.
What it is for ¶
The intended use is keyword lookup over content that is encrypted at rest. A plaintext keyword index would defeat the encryption; this gives approximate lookup while keeping the vocabulary secret from anyone holding only the data.
What it deliberately does not promise ¶
- Exact recall. Bloom filters produce false positives by design, and the vocabulary policy discards tokens on purpose. Callers must treat results as candidates to be confirmed, not as answers. If you need exact membership, this is the wrong tool.
- Protection from an observer watching queries over time. Which documents a query matched, and whether two queries were the same, are visible to anyone who can watch the system run. This design targets an adversary who obtains stored data, not one who observes live traffic.
- Protection from an adversary who can choose documents. Anyone able to insert content and observe the resulting filter learns the mapping for the terms they inserted. Use a separate key per tenant so that knowledge cannot cross a boundary.
Threat model in one line ¶
An adversary who obtains the stored filters, and not the key, should not learn the vocabulary of any document.
Index ¶
- Constants
- Variables
- func Positions(d Digest, nbits, hashCount uint) []uint
- type Analyzer
- type Digest
- type Filter
- func (f Filter) Bits() uint
- func (f Filter) Bytes() []byte
- func (f Filter) HashCount() uint
- func (f Filter) MarshalBinary() ([]byte, error)
- func (f Filter) MayContainAll(qd QueryDigests) (bool, error)
- func (f Filter) MayContainAtLeast(qd QueryDigests, n int) (bool, error)
- func (f Filter) Positions(d Digest) []uint
- func (f Filter) SetBits() uint
- func (f Filter) TestPositions(positions []uint) bool
- type Indexer
- type Key
- type Options
- type Policy
- type QueryDigests
- type Stemmer
- type TextAnalyzer
Constants ¶
const MinKeyBytes = 32
MinKeyBytes is the shortest key material accepted. The key is the only thing standing between an attacker with the stored filters and the document vocabulary, so a short key is refused rather than warned about.
Variables ¶
var ( ErrKeyVersionMismatch = errors.New("blindindex: key version mismatch") ErrShortKey = errors.New("blindindex: key material too short") ErrBadOptions = errors.New("blindindex: invalid options") ErrBadFilter = errors.New("blindindex: malformed filter") )
Errors returned by this package.
Functions ¶
func Positions ¶ added in v0.3.0
Positions returns the bit positions a digest sets, in ascending order.
This is the whole reason a caller can push membership testing into a datastore rather than loading filters out of it. A Bloom test is k bit lookups at known offsets, and most stores can express that directly. In PostgreSQL:
WHERE get_bit(blind_filter, 91) = 1 AND get_bit(blind_filter, 2207) = 1 AND ...
At a few thousand documents, shipping every filter to the application per query costs far more than the test itself does.
Positions derive from the digest alone, so they are stable across processes and safe to embed in a query. They reveal nothing without the key, because the digest does not.
Pass the geometry the filters were built with. Positions computed for a different m or k test the wrong bits.
Types ¶
type Analyzer ¶
Analyzer turns text into tokens. Supplying this as an interface keeps language handling out of the core and lets a caller use whatever tokenizer their corpus needs.
The same Analyzer must be used when building and when querying. Different tokenization on the two paths produces different digests and silently finds nothing.
type Digest ¶
type Digest [digestBytes]byte
Digest is a keyed token representation. It reveals nothing about its token without the key.
type Filter ¶
type Filter struct {
KeyVersion uint32
// contains filtered or unexported fields
}
Filter is one document's searchable representation.
It carries the key version it was built under so that a mismatched test fails loudly instead of returning a false negative that looks like an honest miss.
Bit layout ¶
Bits are packed so that bit i lives in byte i/8 at shift i%8, which is exactly PostgreSQL's `get_bit(bytea, i)` convention. That is deliberate: it lets a caller push membership testing into the database as a WHERE clause instead of transferring every filter out of it. Changing this layout breaks that, so it is part of the format contract, not an implementation detail.
func FilterFromBytes ¶ added in v0.4.0
FilterFromBytes rebuilds a filter from a raw bit array plus its geometry.
This is the counterpart to Bytes, for callers that store the bit array on its own rather than the self-describing MarshalBinary form. Storing raw is what makes a pushed-down predicate possible: Positions are offsets into the bit array, so if the stored column carries a header the database reads the wrong bits while an in-process check, which parses the header first, reads the right ones. The two then disagree in a way that looks like an honest miss.
The caller supplies the geometry and key version because a raw array does not describe itself. Use the same values the filter was built with; there is no way to detect a mismatch here, which is the cost of dropping the header.
func UnmarshalFilter ¶
UnmarshalFilter reads a filter produced by MarshalBinary.
func (Filter) Bytes ¶ added in v0.3.0
Bytes returns the raw bit array, for storing in a datastore column that the pushed-down predicate will read. The slice is a copy; mutating it does not affect the filter.
func (Filter) MarshalBinary ¶
MarshalBinary renders the filter for storage. Output is deterministic: the same document, key and geometry always produce identical bytes, which makes rebuilds diffable and makes "did this change?" answerable without decrypting anything.
func (Filter) MayContainAll ¶
func (f Filter) MayContainAll(qd QueryDigests) (bool, error)
MayContainAll reports whether every queried digest is present.
"May" is the operative word. False positives are inherent to the structure, so a true result means the document is a candidate worth confirming, never that it definitely contains the terms. A false result is definitive: the document does not contain them, unless the vocabulary policy discarded them at index time.
func (Filter) MayContainAtLeast ¶
func (f Filter) MayContainAtLeast(qd QueryDigests, n int) (bool, error)
MayContainAtLeast reports whether at least n of the queried digests are present.
This exists because requiring every term is strict, and a caller whose goal is finding more candidates rather than exact matches may prefer a partial match. Loosening n costs only additional false positives.
n <= 0 is treated as 1. An empty query matches nothing, because treating "no terms" as "matches everything" would turn an analysis failure into a silent full-corpus scan.
func (Filter) Positions ¶ added in v0.3.0
Positions returns the bit positions this filter tests for a digest, using its own geometry. Prefer this over the package-level function when you already hold a filter.
func (Filter) SetBits ¶
SetBits reports how many bits are set. After Build this is the configured target density for every document regardless of length, which is the property that stops the filter leaking document size.
func (Filter) TestPositions ¶ added in v0.3.0
TestPositions reports whether every given bit position is set.
It is the in-process equivalent of a pushed-down predicate, so a caller with both paths can prove they agree on the same input rather than hoping.
type Indexer ¶
type Indexer struct {
// contains filtered or unexported fields
}
Indexer builds and queries filters under a fixed geometry and policy. It holds no mutable state and is safe for concurrent use.
func (*Indexer) Build ¶
Build returns the filter for one document.
docID is mixed into the padding so that two documents with identical text still produce different padding bits. It is not secret and need not be unpredictable; a primary key is fine.
func (*Indexer) Query ¶
func (ix *Indexer) Query(text string, k Key) QueryDigests
Query returns the digests for a query under one key version.
Call it once per key version in play. During a rotation an organisation legitimately holds filters under two versions, and that is the normal path rather than an edge case.
type Key ¶
type Key struct {
// contains filtered or unexported fields
}
Key is secret key material plus the version that identifies it.
Version exists so that key rotation is expressible. A filter records the version it was built under, and testing a filter with digests from a different version is an error rather than a silent non-match, because during a rotation a silent non-match is indistinguishable from "nothing found" and would lose recall invisibly.
type Options ¶
type Options struct {
// Bits is the filter size m, in bits. Fixed for every document.
Bits uint
// HashCount is the number of bit positions k set per token.
HashCount uint
// TargetDensity is the fraction of bits set after padding, between 0 and 1.
//
// Padding to a fixed density is what stops the filter leaking document length. Without
// it, a filter that is five percent set plainly came from a shorter document than one
// that is forty percent set, and that is a length oracle over supposedly opaque data.
//
// The cost is real and is the caller's to accept: every document pays the false positive
// rate implied by this density, including short ones that would otherwise have had a
// much lower rate. Choose it from the rate that is tolerable at MaxTokens.
TargetDensity float64
}
Options configure the filter geometry. Every document in a deployment must use identical values, which is why they are set once on an Indexer rather than per call.
func DefaultOptions ¶
func DefaultOptions() Options
DefaultOptions is a reasonable starting geometry: 8192 bits, 7 positions per token, padded to 35 percent. At 512 tokens per document that is roughly a 0.1 percent false positive rate and 1 KiB per document. Measure against a real corpus before treating it as final.
type Policy ¶
type Policy struct {
// MinRunes drops very short tokens, which carry little signal and are common.
MinRunes int
// MaxTokens bounds how many distinct tokens a single document contributes. This is a
// security parameter as much as a performance one: it bounds the densest possible filter,
// which is what makes a single fixed filter size viable for every document. Documents
// with more tokens are truncated, never given a larger filter.
MaxTokens int
// Drop is an optional set of tokens to discard, applied after analysis. Typical use is a
// stopword list, or terms so common in a corpus that indexing them helps nobody and
// gives frequency analysis something to work with.
Drop map[string]struct{}
}
Policy decides which tokens are worth indexing. It is supplied by the caller and this package computes no corpus statistics of its own, so an Indexer stays stateless and cannot develop a hidden dependency on a datastore.
type QueryDigests ¶
QueryDigests are the digests for one query under one key version.
The version travels with the digests so that a caller holding filters from several key versions, which is the normal state during a rotation, cannot accidentally test digests against a filter they do not match.
type Stemmer ¶
Stemmer reduces a token to its stem. Supplying it as a function keeps language choice in the caller's hands and keeps this package from guessing.
var ( StemEnglish Stemmer = wrapSnowball(english.Stem) StemDutch Stemmer = wrapSnowball(dutch.Stem) StemGerman Stemmer = wrapSnowball(german.Stem) StemFrench Stemmer = wrapSnowball(french.Stem) StemSpanish Stemmer = wrapSnowball(spanish.Stem) )
Stemmers for the languages wired up here. Add more by wrapping any snowballstem package; the list is short because each one should be justified by a real corpus, not added speculatively.
type TextAnalyzer ¶
type TextAnalyzer struct {
// Stemmers are applied in order until one changes the token. Leave empty for no stemming,
// which is the right choice when the corpus is dominated by proper nouns and identifiers.
Stemmers []Stemmer
// Lowercase folds case before stemming. Almost always wanted; exposed because identifier
// corpora sometimes need case preserved.
Lowercase bool
// FoldDiacritics maps accented characters to their base letter, so that someone typing
// "Muller" reaches a document containing "Müller".
//
// Do not rely on a stemmer for this. Snowball stemmers fold only the diacritics their own
// language uses, so a Dutch stemmer turns "ü" into "u" and leaves "š" and "ł" untouched.
// That asymmetry is worse than no folding, because the unaccented spelling silently misses
// while a nearby one works.
//
// Coverage is decomposition-based: anything that NFD splits into a base letter plus a
// combining mark is folded, which covers most European accents. Letters with a stroke or
// bar, such as ł, ø and đ, do not decompose and are handled by an explicit table below.
// Non-Latin scripts are left alone.
FoldDiacritics bool
}
TextAnalyzer tokenises with Unicode text segmentation (UAX #29) and optionally folds diacritics and stems.
Segmentation is delegated rather than approximated with a character-class check. A naive "split on non-letters" tokenizer mangles exactly the terms a blind index is most useful for: names carrying diacritics lose their first letter, and scripts outside the tested range disappear entirely.
func NewTextAnalyzer ¶
func NewTextAnalyzer(stemmers ...Stemmer) *TextAnalyzer
NewTextAnalyzer returns an analyzer that lowercases, folds diacritics and applies the given stemmers. Folding is on by default because asymmetric matching is a subtle and expensive bug; turn it off explicitly if your corpus needs accents preserved.
func (*TextAnalyzer) Tokens ¶
func (a *TextAnalyzer) Tokens(text string) []string
Tokens implements Analyzer.