Documentation
¶
Overview ¶
Package tokenstore provides a persistent, process-local, bidirectional mapping between real sensitive values (domains, IPs, emails, phone numbers) and fake token values, backed by bbolt with a full in-memory mirror for zero-disk-I/O lookups on the hot path.
Index ¶
- Constants
- func IsIPv4PlaceholderAddr(addr netip.Addr) bool
- func IsLockTimeout(err error) bool
- type EntityType
- type Entry
- type Span
- type Store
- func (s *Store) AlreadyTokenizedSpans(text string) []Span
- func (s *Store) Close() error
- func (s *Store) Delete(real string) (bool, error)
- func (s *Store) DeleteCount() uint64
- func (s *Store) GetOrCreateToken(real string, et EntityType) (string, error)
- func (s *Store) LabelOnlyValues() (map[string]EntityType, uint64)
- func (s *Store) LabelOnlyVersion() uint64
- func (s *Store) List() ([]Entry, error)
- func (s *Store) LookupReal(token string) (string, bool)
- func (s *Store) LookupToken(real string) (string, bool)
- func (s *Store) MintAndRegisterSpan(reals []string, types []EntityType, buildSpan func(tokens []string) string) ([]string, error)
- func (s *Store) RegisterSpan(span string) error
- func (s *Store) SafeFlushPoint(buf []byte) int
- func (s *Store) SetExtendedIPv4Pool(on bool)
Constants ¶
const ( // TokenDomainPrefix begins every generated domain (org-identifying) // token: "tok" + 16 hex chars, e.g. "tok1a2b3c4d5e6f70". Prefix-based // rather than the previous suffix-based ".tok.internal" specifically // so a REAL public suffix can follow the token in the visible text // (preserving country/sector context for Claude) while the token // itself stays unambiguously recognizable for the detokenize // direction; see redact.Engine's detokenizeDomainTokens. TokenDomainPrefix = "tok" // TokenEmailLocalPrefix begins every generated email-local-part // token: "user-" + 12 hex chars. TokenEmailLocalPrefix = "user-" // TokenIPNetworkPrefix begins every generated IPv4 /24-network token: // "198.18." + one octet (0-255), e.g. "198.18.42"; the last octet of // the visible address is the REAL host octet, preserved by the // caller, not part of this token. Base is 198.18.0.0/15 (RFC 2544, // reserved for network interconnect device benchmark testing) rather // than an RFC 1918 block like 10.0.0.0/8: internal pentest // engagements routinely target real 10.x/172.16-31.x/192.168.x // addresses, so this tool's own token space deliberately avoids // living in a range real targets are likely to use, to keep "is this // address real or ours" unambiguous. TokenIPNetworkPrefix = "198.18." // TokenIPNetworkPrefix2 is the second half of the same RFC 2544 // block, used for networks 257-512 of an engagement. TokenIPNetworkPrefix2 = "198.19." // TokenIPNetworkOverflowPrefix begins the tokens minted once both // halves of 198.18.0.0/15 are used up: "240." + two octets, e.g. // "240.3.17". 240.0.0.0/4 is the reserved "class E" block, never // routed and not used for real hosts, so like 198.18.0.0/15 it // cannot be mistaken for a target. It is the fallback rather than // the default because tools and readers recognise it less readily // as an ordinary address. TokenIPNetworkOverflowPrefix = "240." // TokenIPv6NetworkPrefix begins every generated IPv6 /64-network // token: "fd00:c0de:" + two hex groups (32 bits), e.g. // "fd00:c0de:1a2b:3c4d"; the last four groups (64-bit interface ID) // of the visible address are preserved from the real one. fd00::/8 // is RFC 4193 Unique Local Address space, reserved for private use, // never a real global address. TokenIPv6NetworkPrefix = "fd00:c0de:" // TokenPhonePrefix is the NANP N11/reserved 555-01XX exchange, which // carriers never assign to real subscribers. Every generated NANP // phone token embeds this as a fragment ("<area code>-" + this + // two digits, e.g. "415-555-0142"), not as the token's own literal // start; see nanpFakeAreaCodes' doc comment for why. TokenPhonePrefix = "555-01" // TokenIntlPhonePrefix begins every generated international-phone // subscriber token: "555-" + 4 digits. The real country calling code // is NOT part of this token; it's a real, preserved value appended // by the caller (see redact.intlPhoneDetector), the same way a real // domain suffix is appended outside the domain org-token. TokenIntlPhonePrefix = "555-" // TokenJWTPrefix begins every generated JWT token's first ("header") // segment, not valid base64url of real JSON, just a fixed marker // that can never appear in a real JWT (which always starts "eyJ" but // is never followed by the literal word "redacted"). TokenJWTPrefix = "eyJredacted" // TokenBearerPrefix begins every generated opaque bearer/API token. TokenBearerPrefix = "tok-bearer-" // TokenAWSKeyPrefix begins every generated fake AWS access key ID. It // keeps the real "AKIA" prefix (so it's still recognizable as an AWS // key shape) but is never a real, issuable key since AWS never // allocates "FAKE" as the next 4 characters. TokenAWSKeyPrefix = "AKIAFAKE" // TokenAWSSecretKeyPrefix begins every generated fake AWS secret // access key. Unlike the key ID, AWS secret keys have no documented // never-allocated prefix to anchor a "structurally guaranteed // non-issuable" fake on (they're free-form random base64, not a // fixed-prefix identifier scheme), so this follows // TokenBearerPrefix's approach instead: a plainly human-readable // "this is a placeholder" marker rather than an attempt at visual // realism. TokenAWSSecretKeyPrefix = "tok-aws-secret-" // TokenPEMKeyBeginMarker/TokenPEMKeyEndMarker wrap every generated // fake PEM private-key block body. TokenPEMKeyBeginMarker = "-----BEGIN REDACTED PRIVATE KEY-----\n" TokenPEMKeyEndMarker = "\n-----END REDACTED PRIVATE KEY-----" // TokenMACPrefix begins every generated fake MAC address: "02" as // the first octet sets IEEE 802's locally-administered bit, which by // definition can never be a real, globally-assigned vendor OUI. TokenMACPrefix = "02:00:00:" // TokenAadhaarPrefix begins every generated fake Aadhaar token: "0000" // + 8 more digits. Real Aadhaar numbers are structurally guaranteed // (by UIDAI's own numbering rule) to never begin with 0 or 1, so this // can never collide with or be mistaken for a real one, while still // keeping the familiar 12-digit shape. TokenAadhaarPrefix = "0000 " // TokenPANPrefix begins every generated fake PAN: "FAKEP" + 4 digits // + 1 letter. Position 4 of a real PAN (the "E" here) is a // holder-type code from a fixed set (P/C/H/A/B/G/J/L/F/T), and "E" isn't // in it, so this is structurally guaranteed non-issuable, not just // visually distinct. TokenPANPrefix = "FAKEP" // TokenPasswordHashPrefix begins every generated fake password-hash // token. "K", "H", and "S" aren't valid hex digits, so this can never // appear as a prefix of (or be confused with) a real hex-only hash; // same "FAKE"-as-a-non-hex-anchor idea as TokenAWSKeyPrefix. TokenPasswordHashPrefix = "FAKEHASH" // The prefixes below all begin fully-opaque vendor-credential tokens // (see the EntityGitHubToken family's doc comment in store.go). Each // embeds the real vendor prefix (so the credential TYPE stays // recognizable, genuinely useful context, not sensitive on its own) // followed by a "FAKE" marker before the random suffix, the same // "AKIAFAKE" idea used for AWS keys: 'K' isn't a valid hex digit, so // "FAKE" can never appear inside a real random-hex secret, making it // a safe, unambiguous anchor for the detokenize direction. TokenGitHubPrefix = "ghp_FAKE" TokenGitLabPrefix = "glpat-FAKE" TokenSlackTokenPrefix = "xoxb-9999999999-9999999999-FAKE" TokenSlackWebhookMarker = "REDACTED-WEBHOOK-" TokenStripePrefix = "sk_live_FAKE" TokenGoogleAPIKeyPrefix = "AIzaSyFAKE" TokenNPMPrefix = "npm_FAKE" TokenTwilioSIDPrefix = "ACFAKE" TokenSendGridPrefix = "SG.FAKE" // TokenConnStringMarker begins the opaque replacement for BOTH // connection-string credential shapes this tool detects: a URL-style // "user:pass@host" span (the real scheme stays visible outside the // token, e.g. "mongodb://") and an ADO.NET/ODBC-style bare password // value (see redact.connStringDetector for both). TokenConnStringMarker = "REDACTED-CREDS-" TokenDigitalOceanPrefix = "dop_v1_FAKE" TokenCloudflarePrefix = "cfat_FAKE" TokenAzureStorageKeyPrefix = "REDACTED-AZUREKEY-" TokenArtifactoryPrefix = "AKCpFAKE" TokenDockerHubPrefix = "dckr_pat_FAKE" TokenCircleCIPrefix = "CCIPAT_FAKE" TokenTerraformPrefix = "FAKE00000000.atlasv1.FAKE" TokenSnykPrefix = "deadfake-dead-fake-snyk-" TokenBitbucketPrefix = "ATBBFAKE" TokenVaultPrefix = "hvs.FAKE" TokenOpenAIPrefix = "sk-FAKE" TokenOpenAIMarker = "T3BlbkFJ" TokenAnthropicPrefix = "sk-ant-api03-FAKE" TokenRazorpayPrefix = "rzp_live_FAKE" TokenItsdangerousPrefix = "tok-signed-" TokenCustomBlockPrefix = "tok-blocked-" // TokenADMachineAccountPrefix begins every generated fake AD // machine-account name. The minted token itself always ends in a // literal "$" (baked in by the generator, not reconstructed via a // Format function), the same "preserve the structural marker, // opaque-ify the rest" idea as an AWS key token preserving its real // vendor prefix, and it keeps this a fully self-contained, // fixed-shape token (detokenize needs no custom per-entity logic, // just a plain tokenPatterns regex, unlike the domain/email/IP // cases that genuinely do have variable-length real structure to // carry through). TokenADMachineAccountPrefix = "FAKEHOST" // TokenGPPCPasswordPrefix begins every generated fake GPP cpassword // value, deliberately NOT valid base64 (contains "-", which never // appears in base64's alphabet), so it can never be mistaken for a // real decryptable cpassword value if it somehow ended up somewhere // this tool doesn't control. TokenGPPCPasswordPrefix = "FAKE-CPASSWORD-" // TokenPasswordPrefix begins every generated fake plaintext password. // Same "FAKE-" anchor as the cpassword token, so it reads as a // placeholder at a glance and can't collide with a random secret. TokenPasswordPrefix = "FAKE-PASSWORD-" )
Token namespaces are deliberately distinct from any real value shape, so a token can never be mistaken for (or collide with) a real one, and so the detokenize direction can find tokens with a single fixed-format regex instead of a lookup table scan. Exported so the redact package can build its detokenize detectors from the same constants.
const ( DefaultIPNetworks uint32 = 512 ExtendedIPNetworks uint32 = DefaultIPNetworks + 65536 )
How many distinct IPv4 /24 networks one engagement can hold.
DefaultIPNetworks is the whole of 198.18.0.0/15: 256 under 198.18. and 256 under 198.19. Past that a store fails closed unless its extended pool is switched on (Store.SetExtendedIPv4Pool, the proxy's --extended-ipv4-pool flag), which adds 65,536 under 240.x.y. The class E range is opt-in because it is a less ordinary-looking address than the benchmark block, and an operator should choose to see it rather than have it appear once a scan grows large enough.
Variables ¶
This section is empty.
Functions ¶
func IsIPv4PlaceholderAddr ¶ added in v0.2.0
IsIPv4PlaceholderAddr reports whether addr lies in a range this package mints IPv4 tokens from: 198.18.0.0/15 or 240.0.0.0/8. The detector must leave such an address alone, since it is (or is indistinguishable from) one of this tool's own placeholders. That holds for 240.0.0.0/8 whether or not the extended pool is on for this run: a token minted there by an earlier run must still be recognised.
func IsLockTimeout ¶
IsLockTimeout reports whether err is Open failing because another process already holds this same tokens.db open. bbolt allows only one writer at a time, so Open blocks for its configured Timeout (5s) then returns this specific error, distinct from every other way Open can fail (a corrupted/invalid file, a permission error, a bad path, ...). Callers use this to show "the proxy is already running for this engagement" only when that's actually the diagnosis; that hint is actively misleading for a genuinely corrupted tokens.db, which needs a completely different fix.
Types ¶
type EntityType ¶
type EntityType string
EntityType identifies the category of a real value, which determines how its token is generated and formatted.
const ( // EntityDomain tokens identify an organization (a registrable // domain, effective TLD+1). Shared across every subdomain and every // email address at that organization, so "ns1.", "portal.", and // "admin@" all resolve to the same org-token; see the redact // package's domain-splitting logic for why. EntityDomain EntityType = "domain" // EntityIPNetwork tokens identify an IPv4 /24 network (the first // three octets), NOT a whole address. Shared across every host in // that network, so two real addresses in the same /24 also share the // same fake /24: their tokens differ only in the last octet, which // is preserved from the real address, exactly like an IPv4 analogue // of subdomain-label preservation; see the redact package's IPv4 // detector for why. EntityIPNetwork EntityType = "ip_network" // EntityIPv6Network tokens identify an IPv6 /64 network (the first // four groups / 64 bits); the interface ID (last 64 bits) is // preserved from the real address the same way. EntityIPv6Network EntityType = "ipv6_network" // EntityEmailLocal tokens identify one mailbox's local part alone // (the piece before "@"), independent of EntityDomain. An email // address is redacted as (local-part token) + "@" + (shared // org-token) + "." + (real, preserved suffix). EntityEmailLocal EntityType = "email_local" // EntityPhone tokens identify a NANP-shaped (US/Canada) phone number. EntityPhone EntityType = "phone" // EntityIntlPhone tokens identify a non-NANP international phone // number's subscriber portion. The real country calling code is NOT // part of the stored real value's identity; it's preserved // literally in the output text (see redact.intlPhoneDetector), // exactly like a domain's public suffix, so Claude retains the // number's country/region context. EntityIntlPhone EntityType = "intl_phone" // EntityJWT tokens identify a whole JSON Web Token (all three // dot-separated segments) found in text: fully opaque, no internal // structure preserved, since a JWT's payload is exactly the kind of // thing that must never reach the model. EntityJWT EntityType = "jwt" // EntityBearerToken tokens identify an opaque bearer/API token // following an "Authorization: Bearer " (or similar) header; the // literal word "Bearer" is left untouched; only the token value // itself is redacted. JWT-shaped bearer tokens are claimed by // EntityJWT instead (see redact.bearerDetector), so this is only for // non-JWT opaque tokens. EntityBearerToken EntityType = "bearer_token" // EntityAWSKey tokens identify an AWS access key ID // (AKIA/ASIA-prefixed, 20 chars total). EntityAWSKey EntityType = "aws_key" // EntityAWSSecretKey tokens identify an AWS secret access key (40 // base64-alphabet characters, keyword-anchored the same way password // hashes are (see redact.awsSecretKeyRe's doc comment), since the // value itself has no fixed prefix to detect on its own, unlike the // key ID it's always paired with. The actual authentication material // for an AWS credential pair, not just an identifier. EntityAWSSecretKey EntityType = "aws_secret_key" // EntityPEMKey tokens identify a whole PEM-armored private key block // (BEGIN...END), replaced wholesale with a fake PEM-shaped block; // there's no internal structure worth preserving, just enough shape // to remain visually recognizable as "a private key was here". EntityPEMKey EntityType = "pem_key" // EntityMAC tokens identify a colon-separated MAC address, replaced // with another locally-administered-range address (the "02" leading // octet, IEEE 802's bit for "not a real, globally-assigned OUI") so // it can never collide with or be mistaken for a real vendor OUI. EntityMAC EntityType = "mac" // EntityAadhaar tokens identify an Indian Aadhaar number (12 digits, // Verhoeff-checksum validated). EntityAadhaar EntityType = "aadhaar" // EntityPAN tokens identify an Indian PAN (Permanent Account Number, // 10-character alphanumeric with a constrained holder-type letter). EntityPAN EntityType = "pan" // The entity types below all identify a vendor-specific credential: // fully opaque, whole-secret tokens rather than structure-preserving // ones, since there's no substructure in any of these worth exposing // to Claude the way a domain suffix or IP network prefix is. EntityGitHubToken EntityType = "github_token" EntityGitLabToken EntityType = "gitlab_token" EntitySlackToken EntityType = "slack_token" EntitySlackWebhook EntityType = "slack_webhook" EntityStripeKey EntityType = "stripe_key" EntityGoogleAPIKey EntityType = "google_api_key" EntityNPMToken EntityType = "npm_token" EntityConnString EntityType = "conn_string" EntityTwilioSID EntityType = "twilio_sid" EntitySendGridKey EntityType = "sendgrid_key" EntityDigitalOcean EntityType = "digitalocean_token" EntityCloudflare EntityType = "cloudflare_token" EntityAzureStorageKey EntityType = "azure_storage_key" EntityArtifactory EntityType = "artifactory_token" EntityDockerHub EntityType = "dockerhub_token" EntityCircleCI EntityType = "circleci_token" EntityTerraform EntityType = "terraform_token" EntitySnyk EntityType = "snyk_token" EntityBitbucket EntityType = "bitbucket_password" EntityVault EntityType = "vault_token" EntityOpenAI EntityType = "openai_key" EntityAnthropicKey EntityType = "anthropic_key" EntityRazorpay EntityType = "razorpay_key" // EntityItsdangerousToken tokens identify a Flask itsdangerous-signed // token (payload.timestamp.signature, 3 dot-separated base64url // segments, same shape as a JWT but without the "eyJ" JSON-header // prefix, since itsdangerous's payload isn't JSON). Only claimed when // a nearby keyword (csrf_token=, session=, itsdangerous) provides // real evidence this is actually a signed token; see // redact.itsdangerousDetector for why a keyword-anchored gate was // chosen over broadening JWT-shape matching itself. EntityItsdangerousToken EntityType = "itsdangerous_token" // EntityPasswordHash tokens identify a bare cryptographic password // hash (MD5/NTLM/SHA-1/SHA-256, or an Impacket secretsdump-style // LM:NT pair): fully opaque, no structure preserved, same as a JWT // or PEM key. Deliberately narrow: a bare hex string this length is // exactly the shape of an ordinary git commit SHA (40 chars) or file // checksum, both of which appear constantly in unremarkable tool // output, so redact.hashDetector only claims one either via a // hash-type keyword nearby (ntlm, md5, sha1, sha256, "nt hash", ...) // or the secretsdump "LMHASH:NTHASH:::" triple-colon line shape, // never a bare hex string with no such context. EntityPasswordHash EntityType = "password_hash" // EntityCustomBlock tokens identify a value matched by a user- // supplied block-list entry (exact string or regex) rather than any // built-in detector, e.g. a customer name variant added via the // setup wizard, or a project codename an operator adds manually. // Fully opaque, same as any other secret-shaped entity: there's no // structure worth preserving since the value could be anything. EntityCustomBlock EntityType = "custom_block" // EntityADMachineAccount tokens identify a $-suffixed Active // Directory machine/computer account name (e.g. "WORKSTATION01$") // found in the same secretsdump.py/pwdump line shape as a password // hash pair; see redact.machineAccountSecretsdumpRe. Deliberately // scoped to ONLY $-suffixed names, never ordinary human usernames on // the same line: a trailing "$" is a hard, unambiguous AD naming // convention, while a bare username is prose-shaped free text (the // same deferred general-NER problem as any other name). EntityADMachineAccount EntityType = "ad_machine_account" // EntityGPPCPassword tokens identify a Group Policy Preferences // "cpassword" XML attribute value: a base64, AES-256-CBC // "encrypted" password that is, in practice, exactly as sensitive as // a plaintext password: Microsoft published the fixed AES key used // for every GPP cpassword value in MS14-025, so any real-world // GPP-password-cracking tool decrypts it directly with that same // published key. Fully opaque, same as any other secret-shaped // entity. EntityGPPCPassword EntityType = "gpp_cpassword" // EntityPassword tokens identify a plaintext password labeled by a // password-like key in config, JSON, env or tool output // (DB_PASSWORD=..., "password": "...", login: x password: y). Fully // opaque: a password has no structure worth preserving. EntityPassword EntityType = "password" )
func AllEntityTypes ¶
func AllEntityTypes() []EntityType
AllEntityTypes returns every entity type this package can mint a token for, sorted so callers get a stable order.
Derived from the generator's own tables (randomTokenShapes, plus the two counter-based network types nextToken switches on separately) rather than a hand-maintained list: a list would silently stop covering the day someone adds an entity type and doesn't know to also edit it, which is the failure mode where a missing check looks exactly like a passing one. Exported for the cross-package invariants that have to hold for EVERY type at once, not just the ones a given test happened to name: that each minted token still round-trips through redact.Engine.Detokenize, and that none of them outgrows the streaming flush window (see proxyserver's maxHeldTokenRunBytes).
type Entry ¶
type Entry struct {
Real string
Token string
EntityType EntityType
FirstSeen time.Time
}
Entry describes one real<->token mapping and its metadata: the unit List returns and Delete removes, for admin/CLI-path inspection of an engagement's token store (see `redactproxy tokens show`/`remove`).
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store is the bidirectional real<->token mapping. A Store owns its bbolt file exclusively (single-writer) and is safe for concurrent use from multiple goroutines within the owning process.
func Open ¶
Open opens (creating if necessary) the token store at path and loads its full contents into memory.
func (*Store) AlreadyTokenizedSpans ¶
AlreadyTokenizedSpans is the query used by redact.Engine.filterAlreadyTokenized; see spanTrie.findFullSpans.
func (*Store) Delete ¶
Delete removes real's mapping entirely (from disk and the in-memory mirror) so a false-positive tokenization can be undone. Reports false if real had no mapping to remove. The next time the same real value is seen, GetOrCreateToken mints a FRESH token for it rather than reusing the deleted one, since a stale token left resolvable while everything that already saw the old one is out in the world would only cause confusion.
func (*Store) DeleteCount ¶ added in v0.2.0
DeleteCount reports how many mappings have been deleted from this store since it was opened. It only ever grows. Anything that caches tokenized text has to treat a change here as invalidating its cache: a cached output can still contain the deleted token, which no longer detokenizes, so the model's reply would reach the operator with a placeholder in it.
func (*Store) GetOrCreateToken ¶
func (s *Store) GetOrCreateToken(real string, et EntityType) (string, error)
GetOrCreateToken returns the token for real, minting and persisting a new one if this is the first time real has been seen. Safe for concurrent use.
func (*Store) LabelOnlyValues ¶ added in v0.2.0
func (s *Store) LabelOnlyValues() (map[string]EntityType, uint64)
LabelOnlyValues returns every stored value of a label-only type (see labelOnlyTypes) with its type, and a version that changes whenever the set does, so a caller can cache whatever it builds from the set.
func (*Store) LabelOnlyVersion ¶ added in v0.2.0
LabelOnlyVersion is LabelOnlyValues' version alone, without copying the set.
func (*Store) List ¶
List returns every mapping currently in the store, oldest first. This is an admin/CLI-path operation, not part of the request hot path, and it reads directly from bbolt rather than the in-memory mirror, since FirstSeen (kept only in the meta bucket) is needed alongside the value and token.
func (*Store) LookupReal ¶
LookupReal returns the real value behind a token, if known. It never creates one; an unrecognized token is passed through unchanged by callers.
func (*Store) LookupToken ¶
LookupToken returns the existing token for a real value, if one has already been minted. It never creates one.
func (*Store) MintAndRegisterSpan ¶
func (s *Store) MintAndRegisterSpan(reals []string, types []EntityType, buildSpan func(tokens []string) string) ([]string, error)
MintAndRegisterSpan resolves the token for each (real, entityType) pair in reals/types, minting and persisting any not already known, exactly like GetOrCreateToken, then computes the composite wire span via buildSpan(tokens) (called with the resolved tokens in the same order as reals/types) and registers it too.
When anything actually needs writing (a new token, a new span, or both), it all happens in ONE bbolt transaction rather than one transaction per new token plus a separate one for the span, roughly halving the fsync cost of minting a brand-new value. This also makes the token and its span consistent by construction: if the process died mid-write, a partial commit can't leave a token persisted with no streaming-safety coverage for it, since both are in the same transaction.
The already-fully-known common case (every real value AND the resulting span already registered, the overwhelming majority of calls once an engagement has been running a while) costs exactly what a LookupToken call per real value would: no transaction, no write lock.
Lock ordering is deliberate and load-bearing: the bbolt write transaction below never touches the span trie's lock (directly or via RegisterSpan) while it's open. RegisterSpan's own ordering is the trie's lock, then its own bbolt transaction; if this method's transaction also reached for the trie lock while holding bbolt's internal write lock, that would be two different lock orderings across the same two locks from two call paths: a deadlock under concurrent callers resolving different real values at once, not just added contention. The transaction below never consults the trie to decide whether to skip its write; it always writes the span (bbolt's Put is idempotent, so a redundant write in the rare already-known case is harmless), and the trie insert happens strictly after both s.mu and the transaction have been released. See TestMintAndRegisterSpan_ManyDifferentConcurrentValuesNoDeadlock.
mu is held only across the transaction and the real2token/token2real mirror update, exactly as long as GetOrCreateToken alone would hold it, and released before the trie insert below, which uses its own separate lock, so a concurrent LookupToken/GetOrCreateToken call from another goroutine only ever waits for one write, not two.
func (*Store) RegisterSpan ¶
RegisterSpan records span as a wire span that could legitimately come back in a streamed response; see spanTrie's doc comment. Persisted (best-effort, like GetOrCreateToken) so a proxy restart mid-engagement doesn't lose coverage for spans minted in an earlier process lifetime; skips the write entirely for a span already known, the common case once a value's been seen once.
The "already known" check reads the SAME structure the insert writes (the trie), not a separate membership set alongside it. With two structures, a caller that had updated the set but not yet the trie left a window where this returned nil, i.e. "registered, safe to put on the wire", for a span safeFlushPoint/findFullSpans couldn't see yet. Two concurrent callers can now both reach the write for one span, but bbolt's Put is idempotent, so the worst case is one redundant write rather than a gap in streaming-safety coverage.
func (*Store) SafeFlushPoint ¶
SafeFlushPoint is the streaming-safety query used by redact.Engine.SafeFlushPoint; see spanTrie.safeFlushPoint.
func (*Store) SetExtendedIPv4Pool ¶ added in v0.2.0
SetExtendedIPv4Pool chooses what happens when an engagement has used all 512 network tokens in 198.18.0.0/15: off (the default), the next new network fails closed; on, tokens continue in 240.x.y. It only governs minting. Tokens already stored, from either range, keep resolving in both directions whatever this is set to.
Directories
¶
| Path | Synopsis |
|---|---|
|
crashtest is a test helper, not a shipped binary: it continuously mints tokens for a known sequence of real values, printing each one to stdout immediately after it commits, so a driver (see internal/tokenstore/crash_test.go) can SIGKILL it at an arbitrary point and verify every value printed before the kill survives with the same token after a fresh Open, proving the token store is genuinely crash- consistent, not just safe across a clean Close.
|
crashtest is a test helper, not a shipped binary: it continuously mints tokens for a known sequence of real values, printing each one to stdout immediately after it commits, so a driver (see internal/tokenstore/crash_test.go) can SIGKILL it at an arbitrary point and verify every value printed before the kill survives with the same token after a fresh Open, proving the token store is genuinely crash- consistent, not just safe across a clean Close. |