blocklistfeed

package
v1.0.511 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: MIT Imports: 16 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 blocklistfeed is the remote blocklist syncer: it periodically downloads one or more remote blocklists (one domain per line, '#' comments allowed) and merges new entries into the live blocklist without removing manually-added entries. Extracted from package main per ADR-0002; it depends on the Blocklist hub only through the narrow Merger interface (main passes its *Blocklist) and on the internal/ssrf seam for the outbound fetch guard. package main keeps the blFeedSyncer singleton and the admin API handler (blocklist_feed.go shim).

Multi-feed: each feed has its own URL, sync interval, and status. A single scheduler goroutine (Start) wakes every TickInterval and syncs every feed that is due. The scheduler is ALWAYS started at startup — feeds added later via the admin API are picked up on the next tick without a restart.

CHAOS-108: the fourth feed loop

internal/feedsched exists to fix two named failure modes in Culvert's periodic feeds — "a failed round is not retried until the next full interval" and "a fleet stays in phase forever" — and its package doc enumerates THREE feed loops. This was the fourth, and it had both defects plus the sharper version of the first:

  • A failed sync stamped the attempt time and the due-check gated on it, so ANY transient failure (DNS blip, a 503 from the origin, a connection reset, a TLS error) pushed the next attempt a FULL interval away — DefaultInterval, 24 hours, on a stock install. Nothing retried in between. The worst shape is the boot pass: the immediate round runs because no attempt has been recorded, so a node that boots into a feed outage merges NO domains from that feed — not stale entries, none — and does not try again for a day. The blocklist is a deny control, so that window is fail-open on exactly the destinations the operator configured the feed to block.
  • The cadence carried no jitter and its phase was pinned at boot, so nodes that boot together (rolling upgrade, compose restart, a hypervisor recovering a rack) sync together against a third-party origin forever. That closes the same loop feedsched's doc describes: the herd provokes the rate-limit, and the absent retry then holds the whole fleet at that failure for the full interval.
  • The fetch was parented to context.Background(), so shutdown could not interrupt an in-flight sync.

The fix reuses the OWNER's ladder rather than growing a second one: each feed holds a feedsched.Scheduler used purely as a delay calculator (NextDelay), which brings bounded exponential backoff, the interval-aware floor/ceiling clamp that keeps retrying a strict TIGHTENING of the cadence, and a stable per-feed jitter offset. The single shared tick is kept, so a feed added through the admin API is still picked up within one tick and no goroutine is created per feed.

That open half — "this feed still has no staleness alert or health row" — was closed by CHAOS-123, in package main's blocklist_feed_health.go: the culvert_blocklist_feed_* series, the extended `blocklist_feed` diagnostics row and the `blocklist_feed_stale` alert. What this package owes that plane is in observer.go (SetSyncObserver) and in the Feed snapshot's LastAttempt / ConsecutiveFailures fields; the thresholds and the operator vocabulary are main's, beside the other health planes.

Still open, and recorded as such: a BOUNDED reason class on SyncOutcome, so the alert can say WHY rather than only what and for how long. It needs sentinel errors threaded through fetchFeedLines (whose messages embed the feed URL, which routinely embeds a token), which is a change to the fetch path, not to the observability plane. See observer.go for the full reason.

Index

Constants

View Source
const (

	// TickInterval is how often Start's scheduler checks for due feeds, and
	// so the finest cadence any feed is actually synced at: a configured
	// interval shorter than this is still synced once per tick. Exported for
	// package main's freshness plane, which must not measure staleness
	// against a cadence the scheduler cannot deliver (CHAOS-123).
	TickInterval = 60 * time.Second

	// DefaultInterval is the fallback auto-sync interval when none is
	// configured. Exported for the main-side callers (admin settings restore,
	// startup config, API handler) that pick the interval.
	DefaultInterval = 24 * time.Hour
)

Variables

This section is empty.

Functions

func MaxFeedLines added in v1.0.493

func MaxFeedLines() int

MaxFeedLines is the per-round line cap past which a feed body is truncated (see maxFeedLines). Exported for package main's freshness plane, whose truncation row tells the operator the size to split a list below.

func MaxHealthyGap added in v1.0.477

func MaxHealthyGap(interval time.Duration, autoSyncFeeds int) time.Duration

MaxHealthyGap is the longest a feed whose every round succeeds can go between two consecutive successful auto-syncs at interval, on a node with autoSyncFeeds auto-synced feeds in total.

Three things stretch the configured interval:

  • the stable jitter offset, up to jitterFrac of it;
  • tick rounding: a feed becomes due between ticks but is only fetched on the next one, which Start arms TickInterval after the previous round ENDS. A 60 s feed with +5% jitter misses the tick at 60 s (due at 63 s) and is fetched on the one after, about 120 s apart;
  • round length: a round fetches its due feeds one after another, so two successes of one feed bracket the rest of the round it last synced in and the start of the round that syncs it next. Each fetch is bounded by httpTimeout, so each of those two rounds is bounded by autoSyncFeeds fetches. Six 60 s feeds at 29 s each make a ~174 s round.

The static per-fetch bound is used rather than a measured round length so a stalled scheduler cannot widen its own freshness bound. Merging a fetched list is not bounded here; a caller measuring freshness should keep a margin for it. Exported for package main's freshness plane, which must not measure staleness against a cadence the scheduler cannot deliver (CHAOS-123).

func SetSyncObserver added in v1.0.477

func SetSyncObserver(fn func(SyncOutcome))

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

The observer MUST NOT call back into any Sync method, directly or transitively: it is invoked from inside the round, and the production observer only records state and fires an alert.

Types

type Feed

type Feed struct {
	URL           string
	Interval      time.Duration // 0 = auto-sync disabled (manual Sync Now only)
	LastSync      time.Time     // last successful sync (zero = never)
	LastError     string        // error from the most recent attempt ("" = ok)
	ImportedCount int64         // cumulative new domains merged from this feed

	// LastAttempt is the most recent round, success or failure (zero =
	// never attempted). It is what distinguishes "this feed has never been
	// tried" from "this feed was tried and failed", which LastError alone
	// cannot: a feed with auto-sync disabled (Interval == 0) is never tried
	// at all, so its LastError stays empty forever (CHAOS-123).
	LastAttempt time.Time
	// ConsecutiveFailures is the retry ladder's failure count for this feed,
	// reset by the first success. Not persisted, so it reads 0 after a
	// restart even for a feed that is known to be failing — read LastError
	// for the authoritative "is the latest round bad" signal, the same rule
	// internal/threatfeed's Health.LastRoundOK carries.
	ConsecutiveFailures int
	// Truncated reports that the latest SUCCESSFUL sync reached the
	// maxFeedLines cap, so only the first maxFeedLines entries of the body
	// were imported and anything past them is not enforced. Reaching the cap
	// is deliberately a truncation, not a failure (see maxFeedLines), which is
	// exactly why it needs its own bit: LastSync advances and LastError clears
	// for such a round, so without this the freshness plane read a deny list
	// that was silently cut short as a clean, fresh sync (2026-11-19 security
	// regression review). Set only by a successful round and reset by the next
	// successful round that is not truncated; a failed round leaves it as the
	// last success left it. Not persisted, like the other status fields.
	Truncated bool
}

Feed is a point-in-time status snapshot of one configured feed, returned by Feeds() for the admin API and settings persistence.

type Merger

type Merger interface {
	MergeFromLines(lines []string, source string) int
}

Merger is the blocklist surface the syncer needs: fold downloaded feed lines into the live blocklist and report how many were newly added. main's *Blocklist satisfies this (MergeFromLines).

type SyncOutcome added in v1.0.477

type SyncOutcome struct {
	// OK is true when the round fetched and merged cleanly.
	OK bool
	// ConsecutiveFailures is the retry ladder's count after charging this
	// round: 0 on success.
	ConsecutiveFailures int
	// LastSync is this feed's last SUCCESSFUL sync after this round (zero =
	// it has still never succeeded).
	LastSync time.Time
	// Interval is the feed's configured auto-sync interval (0 = auto-sync
	// disabled, manual "Sync Now" only).
	Interval time.Duration
}

SyncOutcome is one completed round of one feed, delivered to the observer registered by SetSyncObserver.

Fields are counts and times computed by this package. See the file comment for why no cause is carried.

type Syncer

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

Syncer downloads and merges remote domain feeds into a Merger. The zero value is safe for all methods (feeds map is lazily initialized).

func New

func New(bl Merger) *Syncer

New creates an empty syncer for bl. Feeds are added via SetFeed (startup config seed or admin API).

func (*Syncer) ClearFeeds

func (bs *Syncer) ClearFeeds()

ClearFeeds removes every configured feed. Used when restoring persisted settings, which are authoritative over the YAML/CLI startup seed. Domains already merged into the blocklist are NOT removed.

func (*Syncer) Feeds

func (bs *Syncer) Feeds() []Feed

Feeds returns a snapshot of all configured feeds, sorted by URL for deterministic API output and persistence. A nil syncer (feeds never configured/initialized) has no feeds — return empty rather than panic, so the read-only /api/blocklist/feed endpoint stays a 200 in that state. (Upstream fix ae1b1c1, ported into the extracted engine at merge time.)

func (*Syncer) RemoveFeed

func (bs *Syncer) RemoveFeed(feedURL string) bool

RemoveFeed deletes a feed by URL. Returns false when no such feed exists. Domains already merged into the blocklist are NOT removed (feed imports are merge-only by design).

func (*Syncer) SetFeed

func (bs *Syncer) SetFeed(feedURL string, interval time.Duration)

SetFeed adds or updates a feed. interval 0 disables auto-sync for that feed (it can still be synced manually). Existing sync statistics are preserved on update.

func (*Syncer) Start

func (bs *Syncer) Start(ctx context.Context)

Start launches the background scheduler. It runs an immediate pass, then wakes every TickInterval and syncs each feed whose interval has elapsed since its last attempt. Feeds with interval 0 are skipped.

func (*Syncer) SyncAll

func (bs *Syncer) SyncAll() (int, error)

SyncAll syncs every configured feed (manual "Refresh All Now"), regardless of interval. Returns the total domains added and the first error encountered.

func (*Syncer) SyncFeed

func (bs *Syncer) SyncFeed(feedURL string) (int, error)

SyncFeed fetches one feed by URL and merges new domains into the blocklist. Returns the number of new domains added and any error encountered. The feed's status fields are updated either way.

Deliberately NOT parented to the caller's request context: this is the manual "Sync Now" path, and an operator who clicks it and then navigates away must not abort the fetch. The SCHEDULER path uses SyncFeedContext so shutdown can interrupt it.

func (*Syncer) SyncFeedContext added in v1.0.385

func (bs *Syncer) SyncFeedContext(ctx context.Context, feedURL string) (int, error)

SyncFeedContext is SyncFeed with a caller-supplied context, used by the scheduler so a shutdown interrupts an in-flight fetch rather than waiting out httpTimeout (CHAOS-108).

Jump to

Keyboard shortcuts

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