blindindex

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Sep 24, 2026 License: MIT Imports: 17 Imported by: ? 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.

README

blindindex

Keyword lookup over content you cannot read.

blindindex turns a document into a keyed Bloom filter of HMAC digests. Store the filter next to your encrypted content and you can still ask "which documents might contain this term?", without ever storing the terms. Hold the filter without the key and it tells you nothing about the vocabulary that produced it.

ix, _ := blindindex.New(
    blindindex.NewTextAnalyzer(blindindex.StemEnglish),
    blindindex.Policy{MinRunes: 2, MaxTokens: 512},
    blindindex.DefaultOptions(),
)

key, _ := blindindex.NewKey(1, keyMaterialFromYourKMS)

// At write time, alongside encrypting the document.
filter, _ := ix.Build(docID, plaintext, key)
blob, _ := filter.MarshalBinary()   // store this; 1 KiB per document

// At read time.
f, _ := blindindex.UnmarshalFilter(blob)
hit, err := f.MayContainAll(ix.Query("Zorbulax", key))

Why this exists

If content is encrypted at rest, a plaintext keyword index hands back what the encryption was protecting. The usual answers are to give up keyword search, or to adopt a searchable encryption product. This is the small middle option: approximate lookup, keyed, with the leakage written down.

What it promises, and what it does not

It promises that an adversary holding the stored filters, and not the key, does not learn the vocabulary of any document.

It does not promise:

  • Exact recall. Bloom filters produce false positives by construction, and the vocabulary policy discards tokens deliberately. Results are candidates to confirm, not answers. If you need exact membership, use something else.
  • Protection from an observer of live queries. Which documents a query matched, and whether two queries were the same, are visible to anyone watching the system run. This targets an adversary who obtains stored data, not one who observes traffic. If your threat model includes sustained live observation, this design is not adequate and you want ORAM-class defences or confidential computing.
  • Protection from chosen-document attacks. Anyone who can insert content and observe the resulting filter learns the mapping for the terms they inserted. Use one key per tenant so that knowledge cannot cross a boundary.
Leakage, stated plainly
Property Leaked?
Document vocabulary No, not without the key
Document length No. Every filter is padded to a fixed density
Term frequency No. Membership only, no counts, no positions
Co-occurrence across documents Not stored. There is no inverted index
Similarity between documents Yes. Two documents with overlapping vocabulary have correlated bit patterns
Which documents matched a query Yes, to anyone watching queries

Padding to a fixed density is the reason length does not leak. Without it, a filter that is five percent set obviously came from a shorter document than one that is forty percent set. The cost is that short documents pay the same false-positive rate as long ones. Choose TargetDensity from the rate you can tolerate at MaxTokens.

Design

  • Digests are HMAC-SHA256(key, domain || token), truncated to 16 bytes. Domain separation means a key used here cannot collide with the same key used elsewhere.
  • Every filter is the same size. MaxTokens bounds the densest possible document, which is what makes one fixed geometry viable. Long documents are truncated, never given a bigger filter.
  • Padding is key-derived from the document ID and a counter, so it is indistinguishable from real bits, deterministic across rebuilds, and different for two documents with identical text.
  • Key versions travel with both filters and query digests. Testing across versions is an error, never a silent false, because during a rotation a silent false is indistinguishable from an honest miss and would lose recall invisibly.
  • Keys never print. String and GoString redact, so a key caught in a log line or a struct dump does not leak.
  • Stateless. No corpus statistics are computed, so an Indexer cannot develop a hidden dependency on a datastore. Supply term-dropping through Policy.Drop.

Measured

On an M-series laptop, default geometry (8192 bits, k=7, 35% density):

Serialised filter 1035 bytes per document (1024 raw + 11 header)
Build, 400-token document 311 µs
Query and test 1000 filters 29.5 µs
False-positive rate, measured 0.00095 against a theoretical 0.00065

The false-positive measurement is a test, not a claim: TestFalsePositiveRateIsWithinTolerance runs 20,000 absent-term queries and compares against density^k.

Pushing the test into your datastore

A Bloom test is k bit lookups at known offsets, so it does not have to happen in your process. Positions gives you those offsets, and the bit layout is a documented part of the format: bit i lives in byte i/8 at shift i%8, which is exactly PostgreSQL's get_bit(bytea, i).

var preds []string
for _, d := range ix.Query("Zorbulax", key).Digests {
    for _, p := range blindindex.Positions(d, opts.Bits, opts.HashCount) {
        preds = append(preds, fmt.Sprintf("get_bit(blind_filter, %d) = 1", p))
    }
}
// SELECT id FROM chunks WHERE key_version = $1 AND <preds joined by AND>

No filter ever leaves the database. TestPositions is the in-process equivalent, so you can prove both paths agree; TestPositions_PushedDownPredicateAgreesWithInProcess does exactly that, because a layout mismatch would make the WHERE clause match nothing while looking like an honest miss.

Testing a thousand filters in-process takes about 30 microseconds, so scanning is also fine at small scale. That is why there is no two-level or union index here.

Choosing parameters

DefaultOptions() is 8192 bits, 7 hashes, 35% density: roughly 0.06% false positives at 512 tokens per document, 1 KiB each. Measure against your own corpus before treating it as final.

Raising TargetDensity raises the false-positive rate and increases the noise an attacker must work through. Lowering MaxTokens lets you shrink the filter. Adding tokens to Policy.Drop removes terms whose frequency an attacker could otherwise exploit; very common terms are worth dropping on both grounds, since they help recall least and help an attacker most.

Analysis

TextAnalyzer uses Unicode text segmentation (UAX #29) via blevesearch/segment, with optional Snowball stemmers from blevesearch/snowballstem.

Segmentation is delegated rather than approximated with a character-class check, because a naive "split on non-letters" tokenizer mangles exactly the terms a blind index is most useful for. Łukasz loses its first letter, Škoda becomes koda, and Cyrillic or CJK can vanish entirely. There are tests for each.

Diacritics are folded by default, so someone typing Muller reaches a document containing Müller. Do not leave this to a stemmer: Snowball folds only the diacritics of its own language, so a Dutch stemmer handles ü and ignores š and ł, and that asymmetry is worse than no folding because one spelling works while a neighbouring one silently misses. Folding covers NFD-decomposable accents plus an explicit table for stroke letters such as ł, ø and đ, which Unicode does not decompose. Non-Latin scripts pass through untouched.

Known limitation: Unicode text segmentation treats each CJK ideograph as its own word, so 東京 becomes two tokens rather than one. That is the standard's behaviour without dictionary-based segmentation, and it weakens recall for CJK. Supply your own Analyzer if that matters to you.

Analyzer is an interface. Supply your own if your corpus needs different handling. Use the same one for building and querying, or the digests will not match and you will silently find nothing.

Dependencies

Licence
blevesearch/segment Apache-2.0
blevesearch/snowballstem BSD-3-Clause
golang.org/x/text BSD-3-Clause

Hashing is crypto/hmac and crypto/sha256 from the standard library. No cryptographic primitive is implemented here; this package only composes standard ones.

Status

Tested, benchmarked, fuzzed, and race-clean, but young. The construction is a keyed Bloom filter, which is well understood, and the leakage table above is the honest account of what it gives up. If your data is regulated or high-value, have someone review the leakage properties against your threat model before relying on it.

Licence

MIT

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

View Source
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

View Source
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

func Positions(d Digest, nbits, hashCount uint) []uint

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

type Analyzer interface {
	Tokens(text string) []string
}

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

func FilterFromBytes(data []byte, nbits, hashCount uint, keyVersion uint32) (Filter, error)

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

func UnmarshalFilter(b []byte) (Filter, error)

UnmarshalFilter reads a filter produced by MarshalBinary.

func (Filter) Bits

func (f Filter) Bits() uint

Bits reports the filter size m.

func (Filter) Bytes added in v0.3.0

func (f Filter) Bytes() []byte

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) HashCount

func (f Filter) HashCount() uint

HashCount reports k, the number of positions set per token.

func (Filter) MarshalBinary

func (f Filter) MarshalBinary() ([]byte, error)

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

func (f Filter) Positions(d Digest) []uint

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

func (f Filter) SetBits() uint

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

func (f Filter) TestPositions(positions []uint) bool

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 New

func New(a Analyzer, p Policy, o Options) (*Indexer, error)

New returns an Indexer, or an error if the geometry is unusable.

func (*Indexer) Build

func (ix *Indexer) Build(docID, text string, k Key) (Filter, error)

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.

func NewKey

func NewKey(version uint32, material []byte) (Key, error)

NewKey returns a Key. Material must be at least MinKeyBytes long.

func (Key) GoString

func (k Key) GoString() string

GoString has the same guarantee as String, covering the %#v verb.

func (Key) String

func (k Key) String() string

String deliberately never renders the key material, so that a Key caught in a log line, an error, or a struct dump cannot leak the one secret this package depends on.

func (Key) Version

func (k Key) Version() uint32

Version reports which key this is, for storing alongside a filter.

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

type QueryDigests struct {
	KeyVersion uint32
	Digests    []Digest
}

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

type Stemmer func(string) string

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.

Jump to

Keyboard shortcuts

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