Documentation
¶
Overview ¶
Package catgroup is the named category-group engine: bundles of URL categories (e.g. "AI", "Marketing", "Messaging") under a single name (e.g. "Prod Allowed") that policy rules reference instead of individual categories, enabling Zero Trust postures like: Auth Users → Prod Allowed → Allow, Deny Any Any. Extracted from package main's categorygroup.go per a recorded ADR-0002-style design (post-program extraction).
Performance: each group maintains a pre-computed catSet (map[string]bool) for O(1) membership checks on the proxy hot path. The set is rebuilt on every mutation (admin edit, UT1 sync, cluster sync) — never during request evaluation. All category names are normalized to lowercase.
Concurrency: RWMutex protects the authoritative store, and every writer republishes an immutable readView that the per-request matchers read with no lock at all (see readView). Write path (ReplaceAll) builds the new map outside the lock, then swaps the pointer under a brief Lock.
package main keeps: the `globalCategoryGroups` singleton, the API handlers, cluster sync, rollback, and — deliberately — the HOST-level match (`categoryGroupMatchesHost`): resolving a host to its category is the two-tier catStore+communityDB fusion that lives in main (same verdict as the urlcat extraction), so this engine exposes the pure MatchesCategory instead.
Index ¶
- Variables
- func CategoryKey(category string) string
- type Group
- type MemberFunc
- type Snapshot
- type Store
- func (s *Store) Add(name string, categories []string) (*Group, error)
- func (s *Store) ContainsCategory(catName string) (groupName string, found bool)
- func (s *Store) Delete(name string) error
- func (s *Store) DeleteByID(id string) (string, error)
- func (s *Store) GetByID(id string) *Group
- func (s *Store) GetByName(name string) *Group
- func (s *Store) List() []Group
- func (s *Store) Load(path string) error
- func (s *Store) MatchesCategory(groupName, category string) bool
- func (s *Store) MatchesCategoryByID(id, category string) (matched, resolved bool)
- func (s *Store) MatchesCategoryKey(groupName, catKey string) bool
- func (s *Store) MatchesCategoryKeyByID(id, catKey string) (matched, resolved bool)
- func (s *Store) MatchesMemberKey(groupName, catKey string, member MemberFunc) bool
- func (s *Store) MatchesMemberKeyByID(id, catKey string, member MemberFunc) (matched, resolved bool)
- func (s *Store) MutateDurable(ifVersion *int64, fn func() error) error
- func (s *Store) Names() []string
- func (s *Store) Path() string
- func (s *Store) Rename(id, newName string) (oldName string, err error)
- func (s *Store) ReplaceAll(groups []Group)
- func (s *Store) Revision() uint64
- func (s *Store) Save()
- func (s *Store) SaveErr() error
- func (s *Store) SetPathForTest(path string)
- func (s *Store) SnapshotView() Snapshot
- func (s *Store) Update(name string, categories []string) error
- func (s *Store) UpdateByID(id string, categories []string) error
- func (s *Store) Version() int64
- type VersionConflictError
Constants ¶
This section is empty.
Variables ¶
var ErrNameTaken = errors.New("name already in use")
ErrNameTaken marks a name-collision refusal (create against an existing name, or rename onto a name a DIFFERENT group owns). Handlers map it to a 409 — the server-authoritative refusal, checked under the store lock so a concurrent create/rename cannot slip past a handler-level pre-check.
var ErrPersist = errors.New("category groups: durable persistence failed")
ErrPersist marks a durable-persistence failure surfaced by MutateDurable AFTER the in-memory mutation was rolled back: nothing durable changed and the in-memory store was restored to the pre-mutation truth. Handlers map it to a 5xx — never a success.
Functions ¶
func CategoryKey ¶ added in v1.0.373
CategoryKey derives the catSet lookup key for a category name. It is the SINGLE definition of that derivation, shared with buildCatSet, so a caller that memoizes a key cannot drift from the keys the sets are built with.
Types ¶
type Group ¶
type Group struct {
ID string `json:"id"`
Name string `json:"name"`
Categories []string `json:"categories"`
CreatedAt string `json:"created_at,omitempty"`
UpdatedAt string `json:"updated_at,omitempty"`
// contains filtered or unexported fields
}
Group is a named bundle of URL category names.
type MemberFunc ¶ added in v1.0.406
MemberFunc reports whether the destination host belongs to the named category (a MEMBERSHIP question, not a classification). It receives each of a group's normalized (lowercase) category names in turn.
type Snapshot ¶ added in v1.0.218
Snapshot is one coherent read of the whole list contract: the groups, the derived name list, and the durable fence version, all describing the SAME store state (POST-2D-A COHERENT-READ CORRECTION DISCOVERED DURING 2D-B REVIEW).
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store manages persistent category groups with O(1) lookups.
func (*Store) ContainsCategory ¶
ContainsCategory returns true if any group references the given category name. Used for referential integrity when deleting a base category.
func (*Store) DeleteByID ¶ added in v1.0.86
DeleteByID removes the group with the given stable ID. Returns the removed group's name (for audit/reference bookkeeping) or an error if not found.
func (*Store) GetByID ¶ added in v1.0.86
GetByID returns a copy of the group with the given stable ID, or nil. ID addressing is rename-safe (the name key is mutable; the ID is not). O(1), lock-free, off the published view's byID index.
func (*Store) GetByName ¶
GetByName returns a group by name (case-insensitive). O(1), lock-free, off the published view. Returns nil if not found.
The returned pointer is safe to read concurrently, and now actually is: a published *Group is never mutated in place (readView), so the caller reads an immutable snapshot. Before the view, Update/UpdateByID/Rename edited the live value a previous caller still held, which made reading its catSet or Name a data race the comment here claimed was impossible.
func (*Store) MatchesCategory ¶
MatchesCategory reports whether the named group contains the given (already-resolved) category. This is the engine half of the hot-path group match: package main's categoryGroupMatchesHost resolves host → category through its two-tier fusion, then calls this O(1) check. Unknown group = no match (fail-closed); empty category never matches.
Lock-free, off the published view, so the name fallback no longer writes s.mu's cache line once per category-group rule per request. An earlier shape resolved the group through a locked GetByName and then read g.catSet with no lock held, racing Update / UpdateByID, which REASSIGNED the field of the live group under the write lock (the race detector reported that exact pair: proxy traffic evaluating an un-migrated category-group rule concurrent with an admin edit of that group). That race is now retired by ownership rather than by locking: a group reachable from a published view is never mutated in place, because every writer installs a copy-on-write replacement.
func (*Store) MatchesCategoryByID ¶ added in v1.0.96
MatchesCategoryByID is MatchesCategory keyed by the group's stable ID (references-by-id S2 hot-path match). resolved=true iff a group with that id EXISTS; matched is whether that group contains the (already-resolved) category. The ID is AUTHORITATIVE: a resolved group returns its own membership result so the caller does NOT fall back to a possibly-stale denormalized name (which could match a DIFFERENT group). Empty id / not found ⇒ resolved=false so the caller may fall back to the name.
Lock-free and O(1): one atomic view load, one byID probe, one catSet probe. It is called once per category-group rule inside the policy scan, so both properties matter — the byID index retired the O(groups) scan, and the published view retires the per-call s.mu.RLock. See readView for the measured figures.
func (*Store) MatchesCategoryKey ¶ added in v1.0.373
MatchesCategoryKey is MatchesCategory taking the catSet KEY the caller already holds. See MatchesCategoryKeyByID for why the pre-keyed form exists; this is the same hoist on the denormalized-NAME fallback leg, which an un-migrated rule (no DestCategoryGroupID) still takes.
The GROUP NAME is deliberately still lowered here. It is a per-RULE value, not a request-invariant one, so the scratch cannot hoist it — retiring that allocation means precomputing a normalized group name on the rule at publish time, the way normFQDN is precomputed, which is a separate change with a separate blast radius. It costs nothing on the ID leg that production takes (stampObjectRefIDs stamps every rule saved against an existing group) and nothing for an all-lowercase group name on either leg.
func (*Store) MatchesCategoryKeyByID ¶ added in v1.0.373
MatchesCategoryKeyByID is MatchesCategoryByID taking the catSet KEY the caller already holds — CategoryKey(category) — instead of the display-cased category name.
WHY THE PRE-KEYED FORM EXISTS. The key depends on the REQUEST (the destination host's resolved category), not on the rule, while this function is called ONCE PER category-group rule inside the policy scan every proxied request walks. Deriving it here therefore multiplied a request-invariant cost by the rule count — and it is an ALLOCATING cost, because strings.ToLower returns its input unchanged only for an all-lowercase string and EVERY shipped category name is display-cased ("Social Media", "Gambling", "HR & Recruiting", ...), so the fast path never applied to a real taxonomy.
Measured on a 4-core Xeon @2.80GHz (go1.27.3), the end-to-end policy scan at 20 ID-stamped category-group rules against a CATEGORIZED destination (BenchmarkPolicyEvaluate_CategoryGroupByID, alloc_objects profile at memprofilerate=1): 20 allocs/op and 320 B/op, 91% of every allocation the scan made, all of them this one line. Hoisting the derivation to the per-scan scratch (package main's hostCatScratch.fusionCatKey) makes the scan allocation-free — a CONSTANT, not a function of the rule count, which is the same contract TestBenchGate_PolicyEvalAllocs already holds the plain-FQDN path to.
This is a pure hoist: the key is byte-identical to the one the string form derives, so no membership decision can change. The lowering now happens before the byID probe rather than after, which also means a DANGLING id no longer pays for a key it never uses; resolved/matched are unaffected.
The empty-key arm keeps MatchesCategoryByID's exact shape and position: a resolved group with an UNCATEGORIZED host reports (false, true), so the caller does NOT fall back to the stale denormalized name. CategoryKey("") is "", so the two forms agree on that input too.
func (*Store) MatchesMemberKey ¶ added in v1.0.406
func (s *Store) MatchesMemberKey(groupName, catKey string, member MemberFunc) bool
MatchesMemberKey is MatchesMemberKeyByID on the denormalized-NAME fallback leg (un-migrated rules with no group ID), with MatchesCategoryKey's unknown-group-fails-closed contract.
func (*Store) MatchesMemberKeyByID ¶ added in v1.0.406
func (s *Store) MatchesMemberKeyByID(id, catKey string, member MemberFunc) (matched, resolved bool)
MatchesMemberKeyByID is MatchesCategoryKeyByID with MEMBERSHIP semantics: the group matches when the host belongs to ANY category in it, not only when its single classification winner (catKey) is one of them. Same ID-authoritative resolved/matched contract as MatchesCategoryKeyByID.
WHY. A host can belong to several categories at once — the shipped taxonomy is many-to-many, and an admin category whose PARENT-suffix pattern covers a built-in category's exact host makes the host a member of both — while classification answers with exactly one of them. Deciding the group from the winner alone dropped every other category the host belongs to, so a Block rule on a group holding a non-winning category stopped matching (fail-open) while a single-category rule on that same category, which already used membership, still blocked.
catKey is the classification winner's key (CategoryKey of the caller's resolved category). It is probed first, O(1), off the catSet: the winner is always a member, so this is a pure fast path, and it is also what guarantees no host that matched under the old winner-only semantics stops matching. Only when it misses is member consulted, once per remaining group category. An empty catKey (an UNCATEGORIZED host) is in no category, so it never matches and member is never called — the same shape MatchesCategoryKeyByID has.
Lock-free like every matcher here (one view load, one byID probe). member must not retain its argument; it is called synchronously and does not escape, so a caller's closure stays on the caller's stack.
func (*Store) MutateDurable ¶ added in v1.0.218
MutateDurable runs ONE admin mutation with the OPTIONAL expected-version fence AND the durable persist evaluated in the same serialized critical section (the 2B.0a/2B.0b contract transposed to the object store):
- ifVersion == nil: no fence — the mutation proceeds (still serialized, still durable-or-nothing). Legacy name-addressed callers land here.
- ifVersion != nil: compared against the store generation BEFORE fn runs; a mismatch returns *VersionConflictError and the mutation never runs.
- fn applies the in-memory mutation through the normal store methods; its error is returned verbatim (validation/not-found → the handler's 4xx).
- On fn success the generation bumps and SaveErr persists content + epoch as ONE atomic envelope. A pre-replacement persist failure restores the pre-mutation in-memory state (objects AND generation) and returns the failure wrapped in ErrPersist — confirmed 2xx therefore means restart-durable, epoch included.
- ErrReplacedNotSynced follows the repository's landed-content doctrine (the renamed file already carries the new objects; rolling memory back would contradict the visible file and a restart would activate the "failed" state anyway): proceed as success with a warning. Because the envelope is one write, the landed content CARRIES the new epoch — a restart can never re-expose the pre-mutation token.
Bulk install writers (ReplaceAll) hold the SAME mutMu, so nothing can alter the fenced domain between the version comparison and the mutation.
func (*Store) Rename ¶ added in v1.0.96
Rename changes the display name of the group with the given stable ID, re-keying the name map and the order slice (references-by-id S2: rules link by ID, so the rename is safe — the caller cascades the denormalized name onto referencing rules). Validates the new name is non-empty and not already taken by a DIFFERENT group. Returns the OLD name (for audit + the caller's cascade). A case-only change updates the display name in place without a collision check.
func (*Store) ReplaceAll ¶
ReplaceAll atomically replaces all groups (used by cluster config sync, config import, and config-version rollback). Builds catSets outside the store lock for zero contention.
SERIALIZATION (2D-A fence correction, Blocker B): ReplaceAll holds the SAME mutMu as MutateDurable, so a bulk install can never interleave between a client's ifVersion comparison and its protected mutation — the two writer classes observe exactly one serial order, and the fence generation cannot alias across them.
func (*Store) Revision ¶ added in v1.0.208
Revision returns the process-local mutation counter. Monotonic within a process; resets on restart — a memo key, not an identity.
Served from the published view, so the counter a caller reads and the contents it can observe are the SAME generation (see readView).
func (*Store) Save ¶
func (s *Store) Save()
Save persists the current groups to disk (atomic write). Best-effort legacy wrapper for old non-critical callers; the hardened v2 mutation path (MutateDurable) uses the error-returning SaveErr and rolls back on failure.
func (*Store) SaveErr ¶ added in v1.0.218
SaveErr is the error-returning persistence core (2D-A durable-or-nothing): callers that must know whether the durable write landed use it directly. Content and the fence epoch are ONE envelope in ONE atomic write, so they can never diverge durably — including under ErrReplacedNotSynced, where the landed replacement carries the new epoch with the new content. The retired legacy sidecar is removed once the envelope has landed (it would otherwise carry a stale epoch a future downgrade-then-upgrade could resurrect).
SaveErr is the PUBLIC entry: it acquires mutMu FIRST (2D-A commit-boundary correction), so a standalone save orders against the whole mutation domain and can never observe — let alone publish — the memory state of an in-flight MutateDurable transaction: fn's uncommitted content paired with the not-yet-advanced epoch. Without this, a caller-side Save (the production ReplaceAll+Save bulk shape) racing an admin mutation could persist uncommitted-new-content + old-epoch; if that mutation then failed its own publication and rolled back, the failed, unacknowledged mutation stayed on disk. MutateDurable already holds mutMu and calls saveErrLocked directly — mutMu is not reentrant, so an internal SaveErr call from inside the mutation path would deadlock and must never be added.
func (*Store) SetPathForTest ¶
SetPathForTest points persistence at path without loading.
func (*Store) SnapshotView ¶ added in v1.0.218
SnapshotView captures groups + names + version under ONE hold of the read lock. List()/Names()/Version() assembled by a caller are three independent reads — a writer landing between any two hands the client rows from one state paired with the fence version of another, and an edit from that pair passes the ifVersion fence against content the client never saw. Handlers serving the fenced list contract must use this, never the trio.
COMMITTED-SNAPSHOT rule (transactional-read correction): SnapshotView also acquires mutMu FIRST. MutateDurable's fn mutates the store under mu and RELEASES mu before the version bump and the durable publication, and a persist failure rolls everything back to the pre-mutation state at the SAME version — so a snapshot taken inside that window returns mutated rows paired with the UNBUMPED version, and after the rollback a client edit derived from those phantom rows PASSES the ifVersion fence against the restored tree. Holding mutMu makes the snapshot wait until the open transaction reaches success or rollback; it then describes committed truth only. Cold admin read — hot-path accessors never touch mutMu. Lock order: mutMu → mu (the store's established order).
func (*Store) Update ¶
Update replaces the categories in an existing group. Returns error if not found.
func (*Store) UpdateByID ¶ added in v1.0.86
UpdateByID replaces the categories of the group with the given stable ID. Rename-safe counterpart to Update — the edit lands on the intended group even if its name changed. Returns error if no group carries the id.
type VersionConflictError ¶ added in v1.0.218
type VersionConflictError struct {
Current int64 // the store generation at the locked moment of the check
Asserted int64 // the caller's ?ifVersion= assertion
}
VersionConflictError is the optimistic-concurrency failure returned by MutateDurable when the caller's asserted store generation no longer matches: another admin mutated the store since the caller loaded it. The mutation never ran. Mirrors package main's policyVersionConflictError contract.
func (*VersionConflictError) Error ¶ added in v1.0.218
func (e *VersionConflictError) Error() string