threatfeed

package
v1.0.310 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: MIT Imports: 18 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 threatfeed is the local threat-feed manager: it downloads, persists, and provides instant offline lookups for known-malicious URL/domain lists. Zero external API dependency — all feeds are freely available without registration or rate limits.

Feeds:

The feed data is stored in a JSON file so the proxy survives restarts without waiting for a fresh download. A background goroutine re-syncs on the configured interval (default: 6 hours).

Extracted from package main per ADR-0002. The package is a pure leaf: the SSRF private-IP table comes from internal/ssrf, durable writes from internal/fileutil, and logging from the obs facade (including the new obs.Debugf for the sync-start debug line). package main keeps the globalThreatFeed singleton and the admin/cluster surfaces behind a type alias.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NormaliseURL

func NormaliseURL(raw string) (norm, host string)

NormaliseURL parses a raw URL string into a canonical lookup key (scheme + host + path, no query or fragment) and the bare hostname. Returns ("", "") for invalid, private-IP, or non-HTTP(S) entries.

func SetSyncObserver added in v1.0.220

func SetSyncObserver(fn func(SyncOutcome))

SetSyncObserver publishes the sync observer. A nil fn clears it.

Types

type Feed

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

Feed manages local copies of public threat intelligence lists. All methods are safe for concurrent use.

func New

func New() *Feed

New returns an idle Feed with the same shape as the pre-extraction package-main literal: initialised maps and the 6-hour default sync interval. Init configures and enables it.

func (*Feed) AddDomainAllowlist

func (tf *Feed) AddDomainAllowlist(domain string) error

AddDomainAllowlist adds a domain to the allowlist and persists.

func (*Feed) AllowlistMaskedTotal added in v1.0.47

func (tf *Feed) AllowlistMaskedTotal() int64

AllowlistMaskedTotal returns the cumulative count of domain-level threat hits suppressed by the domain allowlist since process start. A rising value means the allowlist is actively overriding live threat intel — worth an operator's attention (the exemption may be too broad, or an allowlisted platform is now hosting malware at the domain level).

func (*Feed) CheckDomain

func (tf *Feed) CheckDomain(domain string) (malicious bool, source string)

CheckDomain looks up a bare hostname against the threat feed. Returns (isMalicious, sourceName).

func (*Feed) CheckRequestURL added in v1.0.247

func (tf *Feed) CheckRequestURL(u *url.URL) (malicious bool, source string)

CheckRequestURL is CheckURL for a URL the caller has ALREADY parsed. The verdict is identical; only the derivation of the lookup keys differs.

WHY IT EXISTS. The proxy's sole CheckURL call site (preDispatchBlocked, one per forwarded plain-HTTP request — the CONNECT and WebSocket paths are excluded by the guard above it) used to pass r.URL.String() — so a *url.URL net/http had just parsed was serialised, and this package immediately parsed it back. Measured on a 4-core Xeon against a 100k-entry feed for an ordinary destination that MISSES, which is what every ALLOWED request pays (medians of n=5, BenchmarkFeedCheckRequestURL_*):

                            serial        4x parallel   B/op   allocs/op
CheckURL(u.String())        887 ns/op     330 ns/op     336    4
CheckRequestURL(u)          376 ns/op     162 ns/op     112    2
                            2.36x         2.04x         -67%   -2

CheckDomain is the CONTROL and it is the whole argument: it does the same amount of real work — canonicalise a host, probe one map — for 109 ns and 0 allocations, so the ~8x gap between the two checks was almost entirely a round trip through a string, paid on the request goroutine before the policy engine had run. Of the 511 ns removed, url.String() was ~120 (1 alloc) and url.Parse ~370 (2 allocs).

EQUIVALENCE IS BY CONSTRUCTION, NOT BY INSPECTION. normaliseParsedURL takes the fast path only for the URL shape on which String() followed by Parse() is provably the identity for the three fields NormaliseURL reads (Scheme, Hostname, Path); every other shape — opaque, relative, a non-HTTP scheme, a bracketed IPv6 or otherwise non-plain authority — falls through to the verbatim string derivation, where the round trip IS the definition. So the fast path can only ever be an optimisation of a case it already agrees on. Pinned by TestCheckRequestURL_MatchesCheckURL (hand-picked divergence shapes) and FuzzCheckRequestURL (differential against the string path).

func (*Feed) CheckURL

func (tf *Feed) CheckURL(rawURL string) (malicious bool, source string)

CheckURL looks up a full URL against the threat feed. Returns (isMalicious, sourceName).

func (*Feed) DomainAllowlist

func (tf *Feed) DomainAllowlist() []string

DomainAllowlist returns the current allowlist entries sorted.

func (*Feed) DomainAllowlisted

func (tf *Feed) DomainAllowlisted(domain string) bool

DomainAllowlisted reports whether a domain is on the threat-feed allowlist (domain-level blocking skipped; URL-level blocking still applies).

func (*Feed) Enabled

func (tf *Feed) Enabled() bool

Enabled reports whether the feed is active. Lock-free: secscan calls it as a gate before CheckDomain/CheckURL, so it is on the same per-request path.

func (*Feed) ExportDomains

func (tf *Feed) ExportDomains() map[string]int64

ExportDomains returns a copy of the domain threat map as domain→unix-timestamp. Used by the Control Plane to include feed data in config sync.

Currently-allowlisted hosts are excluded: the ThreatFeedDomains wire field keeps its pre-masking meaning ("hosts a lookup may block") because DP nodes running an older binary have no lookup-time allowlist mask — exporting masked hosts would make a mixed-version rolling upgrade (new CP, old DPs) hard-block allowlisted platforms fleet-wide. New DPs lose nothing: their own allowlist (synced separately) masks these hosts at lookup anyway.

func (*Feed) ExportURLs

func (tf *Feed) ExportURLs() map[string]int64

ExportURLs returns a copy of the URL threat map as url→unix-timestamp. Used by the Control Plane to include feed data in config sync.

func (*Feed) Health added in v1.0.220

func (tf *Feed) Health() Health

Health returns the current sync-health snapshot.

func (*Feed) ImportFeedData

func (tf *Feed) ImportFeedData(urls map[string]int64, domains map[string]int64)

ImportFeedData replaces the in-memory URL and domain maps with data received from the Control Plane config sync. Each value is a unix timestamp (added_at). The source is set to "cluster-sync" to distinguish from direct feed downloads.

func (*Feed) Init

func (tf *Feed) Init(dbPath string, syncInterval time.Duration)

Init configures the feed manager and loads any persisted DB from disk. dbPath may be "" to disable persistence (feed data lives in-memory only).

func (*Feed) RemoveDomainAllowlist

func (tf *Feed) RemoveDomainAllowlist(domain string) error

RemoveDomainAllowlist removes a domain from the allowlist and persists.

func (*Feed) Save

func (tf *Feed) Save()

Save is the caller-facing wrapper around saveToDisk. Used by paths like applyConfigSnapshot that mutate via ImportFeedData — which does NOT auto-persist (unlike SetDomainAllowlist / AddDomainAllowlist / RemoveDomainAllowlist which call saveToDisk internally). Errors are logged, not returned, to match the void-Save convention of the other Bucket-1 snapshot stores (policyStore, globalProfileStore, etc.).

func (*Feed) SeedForTest

func (tf *Feed) SeedForTest(urls, domains map[string]string)

SeedForTest inserts URL and domain entries directly (value = source name), replacing the whitebox map pokes package main's integration tests used pre-extraction. AddedAt is stamped now; totalEntries tracks the URL count.

func (*Feed) SeedSyncFailureForTest added in v1.0.220

func (tf *Feed) SeedSyncFailureForTest(failedSources string)

SeedSyncFailureForTest records a failed sync round with the given bounded source class. Counterpart to SeedSyncSuccessForTest.

func (*Feed) SeedSyncSuccessForTest added in v1.0.220

func (tf *Feed) SeedSyncSuccessForTest(t time.Time)

SeedSyncSuccessForTest records a clean sync round at t, without performing any fetch. Test support for package main's staleness plane, which reads this feed's Health() snapshot: driving it through a real Sync would require two reachable third-party origins and a 60-second-per-feed timeout budget.

func (*Feed) SetDBPathForTest

func (tf *Feed) SetDBPathForTest(path string) (old string)

SetDBPathForTest swaps the persistence path and returns the previous one. Test support for main-side durability tests that point the process-wide feed at a temp dir; pair the restore with ImportFeedData(nil, nil) to clear seeded data.

func (*Feed) SetDomainAllowlist

func (tf *Feed) SetDomainAllowlist(domains []string) error

SetDomainAllowlist replaces the entire allowlist and persists to disk.

func (*Feed) SetEnabledForTest added in v1.0.47

func (tf *Feed) SetEnabledForTest(enabled bool) (old bool)

SetEnabledForTest toggles the feed's enabled flag and returns the previous value. Test support for main-side tests that assert CheckURL/CheckDomain verdicts on the process-wide feed: outside tests the flag is only set by Init, so a test that needs positive verdicts must enable the feed itself (and restore the old value in cleanup) instead of depending on whether an earlier test happened to run Init — that ordering dependence is exactly what the shuffle/determinism gate flags.

func (*Feed) Start

func (tf *Feed) Start(ctx context.Context)

Start launches the background sync goroutine. An immediate sync is performed when the cache is empty or has never synced.

The loop is a feedsched.Scheduler rather than a bare time.Ticker, and both halves of that change are load-bearing:

  • BACKOFF. A ticker retried a failed round only after the FULL interval (six hours by default). One transient fault on the customer's egress path — a DNS blip, a 503 from the provider, a restarted upstream proxy — therefore froze threat intelligence for six hours. The severe shape is the cold start: needSync is true when the on-disk DB is empty, so a fresh or re-imaged node whose FIRST sync fails serves with NO threat intelligence at all (not stale — none) until that tick, while /health, /ready and every metric report a completely healthy node. Retries are now 5 min doubling to 1 h, reset on the first success.
  • JITTER. A ticker fires at a fixed offset from process start, so nodes that boot together stay in phase forever. The two feed origins are public third-party endpoints shared by every Culvert deployment, and a fleet syncing in lockstep is answered with rate-limiting of the customer's egress IP — which then causes the very failure the absent backoff would hold the fleet at for six hours.

func (*Feed) Stats

func (tf *Feed) Stats() (int64, time.Time, time.Duration)

Stats returns (totalEntries, lastSync, syncInterval) for monitoring.

func (*Feed) Sync

func (tf *Feed) Sync()

Sync downloads all configured feeds and atomically replaces the in-memory lookup tables. Safe to call concurrently; calls run sequentially.

Retained as the void-returning entry point for the admin API's manual sync and for callers that do not schedule; syncRound carries the outcome the scheduler and the health plane need.

func (*Feed) SyncInterval added in v1.0.220

func (tf *Feed) SyncInterval() time.Duration

SyncInterval reports the configured cadence between successful syncs.

func (*Feed) SyncStatus added in v1.0.33

func (tf *Feed) SyncStatus() (ok bool, lastSuccess time.Time, errSummary string)

SyncStatus reports whether the most recent sync fetched every feed cleanly, the time of the last fully-successful sync (which may lag lastSync from Stats if recent attempts have been failing), and a summary of the most recent failure (empty when the last sync succeeded). lastSync updates on every attempt regardless of outcome, so relying on Stats alone lets a persistently-failing feed hide behind a perpetually-fresh timestamp.

type Health added in v1.0.220

type Health struct {
	// Configured is false until Init runs. Every surface reports "not
	// configured" rather than a zero in that case: a last-success of zero on a
	// node that never had the feed is indistinguishable from a node whose feed
	// has never once succeeded, and the two demand opposite operator actions.
	Configured  bool
	LastAttempt time.Time
	LastSuccess time.Time

	// LastRoundOK is the AUTHORITATIVE "is the feed syncing cleanly" signal:
	// it derives from the persisted lastSyncErr, so it survives a restart. Do
	// not substitute ConsecutiveFailures == 0 for it — that count is not
	// persisted, so after a restart from a failed-sync DB it reads zero while
	// the feed is known to be failing (PR #1305 review). It is the same value
	// SyncStatus() reports to the admin API, so the two surfaces agree.
	LastRoundOK bool

	ConsecutiveFailures int
	TotalFailures       int64
	FailedSources       string
	ErrSummary          string
	SyncInterval        time.Duration
	Entries             int64
}

Health is a consistent snapshot of the feed's sync state, read by package main's health plane at scrape/diagnostics time.

type SyncOutcome added in v1.0.220

type SyncOutcome struct {
	OK                  bool
	FailedSources       string
	ConsecutiveFailures int
	LastSuccess         time.Time
	SyncInterval        time.Duration
	Entries             int64
}

SyncOutcome is the result of one sync round, delivered to the observer registered by SetSyncObserver.

FailedSources is the BOUNDED reason class — never a raw error string. See Feed.failedSources for why that distinction is load-bearing for the alert plane.

Jump to

Keyboard shortcuts

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