rules

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: GPL-3.0 Imports: 10 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 rules holds the persisted, per-engagement customization on top of the built-in redact detector set: which detector categories/ subcategories are disabled, and custom block/allow entries. It's a plain JSON file that a hand edit, the setup wizard, or a CLI subcommand can all write, and that the running proxy watches for changes so edits apply without a restart. JSON rather than YAML or anything else that would need a new dependency: the config surface here is small, and the CLI subcommands built on top of it are meant to be the main way it gets edited, not hand-authoring.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func WithLock

func WithLock(path string, fn func() error) error

WithLock serializes an entire Load-inspect-modify-Save cycle against path across separate OS processes, acquired via an exclusive create-only lock file (path+".lock"), retried with a short backoff up to a few seconds, released when fn returns.

Without this lock, two concurrent CLI invocations (e.g. a script bulk-adding block entries, or two operators editing the same engagement from different terminals at once) each Load a snapshot, decide what to change based on it, then Save, and Save always writes the WHOLE file, so whichever process saves last silently overwrites the other's change in full, not just the one value being added. In a redaction tool a silently-dropped block entry means under-redaction, not just an annoyance.

Every path in cmd/redactproxy that Loads, decides, and Saves rules.json (the `rules` subcommands' core functions, the wizard, and the proxy's own startup EnsureAllCategories step) must wrap that whole sequence in WithLock; locking only around Save (or only around Load) would still leave the decide-based-on-a-stale-read window open.

Types

type CategoryState

type CategoryState struct {
	Enabled     bool   `json:"enabled"`
	Description string `json:"description,omitempty"`
	Warning     string `json:"warning,omitempty"`
}

CategoryState is one category/subcategory's persisted state, keyed by "category.subcategory" (e.g. "cloud.aws") in Config.Categories. Description and Warning are informational only: EnsureAllCategories always overwrites them with current source text on every call, so a stale description from an older binary (or a hand-edited one) never lingers or drifts from what the code actually does. Only Enabled is real, persisted, behavioral state.

type Compiled

type Compiled struct {
	Disabled map[string]bool
	Block    []*regexp.Regexp
	Allow    []*regexp.Regexp

	// ForcedDomains holds the registrable domain for every non-regex
	// Block entry with IsDomain set that actually resolves to a real
	// domain (redact.DomainRegistrablePart), keyed by that registrable
	// part, not necessarily the entry's own literal Value (an entry
	// marked IsDomain with a subdomain, e.g. "admin.widgetcorp-fixture.do", still
	// resolves to and is keyed by "widgetcorp-fixture.do"). These are deliberately
	// NOT also compiled into Block: pass this to
	// redact.DefaultCategorizedDetectorsWithForcedDomains instead, so
	// the domain detector's own structure-preserving logic handles the
	// value consistently everywhere it appears (bare, subdomain, email,
	// URL) rather than the block detector's fully-opaque token, which
	// would otherwise corrupt the domain detector's own reconstruction
	// of a later subdomain occurrence of the same value (the store's
	// real-value-keyed token lookup can't tell which detector asked
	// first).
	ForcedDomains map[string]bool

	// UnresolvedDomainEntries lists the Value of every Block entry with
	// IsDomain set that DIDN'T resolve to a real domain (not domain-
	// shaped at all, or an RFC-reserved example domain) -- these fall
	// back to being an ordinary literal Block entry rather than being
	// silently dropped or excluded from anything. There's no
	// interactive channel to warn through for a hand-edited rules.json,
	// so the caller (runProxy/reload; see logRulesState) logs a
	// startup/reload WARN for each and continues; this never blocks
	// startup or fails the config.
	UnresolvedDomainEntries []string
}

Compiled is the ready-to-use runtime form of a Config: a lookup set for disabled categories, compiled regexes for block/allow, and any block entries an operator marked IsDomain (see ForcedDomains).

type Config

type Config struct {
	// Categories holds every known category/subcategory's enabled
	// state, keyed by "category.subcategory" (see
	// redact.CategorizedDetector / redact.CategoryInfo), deliberately
	// dense, not sparse: EnsureAllCategories populates every category
	// this build of the tool knows about, defaulting to Enabled: true,
	// so someone hand-editing rules.json can see every available
	// category, what it does, and its current state without running
	// `redactproxy rules show` first. An absent key is still treated as
	// enabled by Compile; density here is for the file's own
	// readability, not a behavioral requirement.
	Categories map[string]CategoryState `json:"categories,omitempty"`
	// Block entries are always redacted in addition to anything the
	// built-in detectors already catch, e.g. a customer name variant
	// the wizard collected, or a project codename added manually.
	Block []Entry `json:"block,omitempty"`
	// Allow entries are never redacted, even if a built-in detector
	// would otherwise catch them, e.g. the team's own lab domain.
	Allow []Entry `json:"allow,omitempty"`
}

Config is the full persisted ruleset for one engagement.

func Load

func Load(path string) (*Config, error)

Load reads the config at path. A missing file is NOT an error; it returns an empty Config, since a fresh engagement legitimately has no rules.json yet until the first edit.

func (*Config) Compile

func (c *Config) Compile() (*Compiled, error)

Compile turns Config into a Compiled, or returns the first invalid regex it finds (same errors Validate would report, but with the compiled result on success so callers don't have to call both).

func (*Config) EnsureAllCategories

func (c *Config) EnsureAllCategories(all []redact.CategoryInfo) (changed bool, dropped []string)

EnsureAllCategories reconciles cfg.Categories against all (typically redact.AllCategoryInfo()): every category in all gets an entry if it doesn't already have one (defaulted Enabled: true; a newly-added category, e.g. from a future binary version, must not silently start disabled just because it didn't exist when this file was first written), an existing entry's Enabled value is never touched, and Description/Warning are always overwritten with all's current text. Any key in cfg.Categories no longer present in all is dropped (a detector removed in a future version doesn't leave an orphaned entry forever).

This is the mechanism that makes rules.json forward-compatible: a file written by today's binary, later opened by a future binary that ships a new category, gets that category added automatically on the next Load+EnsureAllCategories+Save: no version field, no explicit migration step.

Returns whether anything actually changed (a category added, removed, or its Description/Warning text updated since last written; Enabled values are never touched for pre-existing keys, so they never count as a change here), so a caller deciding whether to re-Save can skip a pointless rewrite (and the mtime bump that would cause) when nothing is actually different from what's already on disk.

Also returns the keys that were dropped (present in c.Categories, not present in all), sorted. This package cannot tell a genuinely-retired category (expected, silent) apart from a hand-edited case typo on an otherwise-live category (a real, easy-to-miss trap, since the typo'd key silently reverts to the default Enabled: true instead of erroring); both look identical here. Callers that persist the result (unlike a read-only `rules show`) are expected to surface this list rather than swallow it, so a typo'd hand-edit doesn't silently vanish.

func (*Config) RemoveValue

func (c *Config) RemoveValue(value string) (removedFromBlock, removedFromAllow bool)

RemoveValue removes every entry (across both Block and Allow) whose Value case-insensitively equals value, reporting which list(s) it was actually found and removed from. Checks both lists unconditionally, not just the first match: a value can legitimately be present in both at once (e.g. a leftover contradictory pair from before the reject-on-conflict check existed), and removal should clear it everywhere in one call rather than requiring the operator to know which list(s) to target.

func (*Config) Save

func (c *Config) Save(path string) error

Save writes cfg to path as indented JSON, creating parent directories if needed. Every CLI subcommand and the wizard funnel through this; it's the only writer, so the on-disk shape stays consistent no matter which entry point produced the edit.

Writes via a temp file in the same directory, then os.Rename over the real path, rather than os.WriteFile directly to path. os.WriteFile opens with O_TRUNC: truncate and the subsequent write are two separate syscalls, so a concurrent reader (the live proxy's Watcher, polling this same file) can observe a truncated/partial file mid-write. A torn read like that fails Load's JSON parse, and since Watcher.checkOnce records the new mtime before attempting the read, a failed reload leaves the running proxy stuck on stale rules indefinitely, not just until the write finished, but until some LATER edit changes the mtime again (see TestWatcher_TornReadDuringWriteLeavesStaleRulesStuck, and the mtime handling in watcher.go's checkOnce). Same-directory rename is required for atomicity: POSIX rename() is only atomic within one filesystem, and the temp file must land on the same one as the real target.

func (*Config) Validate

func (c *Config) Validate() error

Validate compiles every regex entry (Block and Allow) without applying anything, so a typo'd pattern is caught before it's relied on rather than silently matching nothing at runtime. Also rejects an empty Value on either list -- found live: a malformed rules.json (wrong JSON key name, so Value never unmarshaled) produces an Entry with Value == "", which compileEntry below turns into the literal pattern "(?i)" for a non-regex block entry -- a zero-width match at every position in every string, silently block-listing the entire engagement's traffic rather than failing loudly. An empty Allow value is comparatively harmless (compileEntry anchors it "^$", matching only the empty string) but just as clearly not a real rule someone meant to write, so it's rejected the same way for consistency.

A regex that can match the empty string ("x*", "(?i)", "a?") is the same mistake in regex form, and worse on the allow side: patterns are unanchored, so it matches inside every real value and silently turns redaction off for the whole engagement. On the block side it makes every request fail. Both are rejected.

type Entry

type Entry struct {
	Value    string `json:"value"`
	Regex    bool   `json:"regex"`
	Note     string `json:"note,omitempty"`
	IsDomain bool   `json:"is_domain,omitempty"`
}

Entry is one block-list or allow-list rule: either an exact string (Regex: false) or a regular expression (Regex: true), plus an optional human-readable reason, recorded so a saved config stays auditable months later ("why is this here?"), not just a bare list of patterns. Regex entries are compiled with Go's standard regexp package (RE2), the same engine every built-in detector uses, so a user-authored pattern is exactly as immune to catastrophic backtracking as anything else in this codebase.

IsDomain is an explicit, operator-set request (block-list entries only, ignored on Regex entries and on Allow) that Value should get the domain detector's own structure-preserving token treatment instead of the generic opaque block token; see Compiled.ForcedDomains for why this needs to be an explicit opt-in rather than auto-detected from Value's shape. Settable via `redactproxy rules block -domain`, or by hand-editing this field directly in rules.json. There's deliberately no separate validation step for the hand-edited path: Compile() itself falls back to treating the entry as an ordinary literal block value whenever Value doesn't actually resolve to a real domain, so a bad or nonsensical IsDomain value on a hand-edited file can never silently exclude something from being redacted at all.

func FindEntry

func FindEntry(entries []Entry, value string) (Entry, bool)

FindEntry returns the entry in entries whose Value case-insensitively equals value, and whether one was found. Deliberately a shallow, literal-text comparison, not a regex-overlap analysis (which isn't generally decidable), so it catches an exact duplicate (including two regex entries with identical source text) without pretending to catch every way two rules could actually interact at runtime. Used for duplicate-add detection within one list and cross-list conflict detection between Block and Allow (see cmd/redactproxy/rules_cmd.go).

type Watcher

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

Watcher polls a rules config file's mtime and calls onChange with the newly loaded Config whenever it changes (including the file being created after the watcher starts, or removed; a removed file reloads to an empty Config, not an error, matching Load's own "missing file isn't an error" contract).

Polling instead of a filesystem-event library (fsnotify, inotify): this file changes at human-editing or CLI-subcommand speed, not a latency-sensitive hot path, so a 1-2 second poll is indistinguishable from "instant" to an operator while adding zero new dependencies.

func NewWatcher

func NewWatcher(path string, interval time.Duration, onChange func(*Config), onError func(error)) *Watcher

NewWatcher builds a Watcher for path. It seeds its "last known mtime" from the file's current state (if it exists) at construction time, so the first poll after Start doesn't spuriously fire onChange for a file that hasn't actually changed since whoever constructed this already loaded it.

func (*Watcher) Start

func (w *Watcher) Start()

Start begins polling in the background. Call Stop to end it.

func (*Watcher) Stop

func (w *Watcher) Stop()

Stop ends the polling goroutine and waits for it to exit.

Jump to

Keyboard shortcuts

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