announcements

package
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Dec 5, 2026 License: Apache-2.0 Imports: 24 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 announcements verifies, validates and caches the signed announcement feed (security notices, product news, newsletter). The feature accepts only items signed by the trusted public keys embedded in keys.go, and every check fails closed: an item is shown only when signed by keys allowed for its tier.

Index

Constants

View Source
const (
	TierCritical    = "critical"
	TierAdvisory    = "advisory"
	TierMaintenance = "maintenance"
	TierFeature     = "feature"
	TierInfo        = "info"
	TierNewsletter  = "newsletter"
)

Tiers, from most to least urgent.

View Source
const (
	KindAnnouncement = "announcement"
	KindRevokeKey    = "revoke_key"
)

Item kinds. A revoke_key item names a signing key id to stop trusting.

View Source
const (
	CTAUpdates  = "updates"
	CTASettings = "settings"
)

Allowed call-to-action routes, never URLs.

View Source
const (
	ModeOff      = "off"
	ModeSecurity = "security"
	ModeAll      = "all"
)

Modes of updates.announcements.

View Source
const (
	DropNotSigned = "tier_not_signed"
	DropExpired   = "expired"
	DropContent   = "content"
)

Item drop codes, shared with the announce tool's verifier.

View Source
const DefaultFetchTimeout = 15 * time.Second

DefaultFetchTimeout bounds one feed request.

View Source
const SchemaVersion = 1

SchemaVersion is the only feed schema this build reads; a breaking change ships as a parallel feed file, so old instances keep reading v1.

View Source
const UserAgent = "levelrail-announcements"

UserAgent is the only identifying header a fetch sends. It carries no version, edition or instance id; the request has no query string or cookie.

Variables

View Source
var (
	ErrTooLarge    = errors.New("announcements: feed exceeds the size cap")
	ErrTooManyItem = errors.New("announcements: feed exceeds the item cap")
	ErrSchema      = errors.New("announcements: unsupported feed schema")
)

Parse errors.

View Source
var (
	ErrFetch       = errors.New("announcements: feed request failed")
	ErrFetchStatus = errors.New("announcements: feed server answered with an error status")
)

ErrFetch and ErrFetchStatus are the stable failure classes of a feed request; their text never carries a host, address or port.

View Source
var (
	ErrNoTrustedKeys = errors.New("announcements: no trusted keys configured")
	ErrBadSignature  = errors.New("announcements: a signature from a trusted key does not verify")
	ErrNoSignature   = errors.New("announcements: no signature from a trusted key")
	ErrReplay        = errors.New("announcements: feed sequence is older than the last accepted one")
	ErrUnchanged     = errors.New("announcements: feed sequence already accepted")
	ErrFeedExpired   = errors.New("announcements: feed has expired")
	ErrFeedLifetime  = errors.New("announcements: feed claims a lifetime beyond the allowed maximum")
	ErrSequenceJump  = errors.New("announcements: feed sequence jumps further than allowed")
)

Verification errors. Callers keep the cached feed on any of them.

View Source
var ErrContent = errors.New("announcements: invalid content")

ErrContent is wrapped by every validation failure.

View Source
var ErrNotHTTPS = errors.New("announcements: feed URL must be https")

ErrNotHTTPS is returned for a non-https source URL.

Functions

func ErrorCode

func ErrorCode(err error) string

ErrorCode maps a whole-feed failure to the code the announce tool uses, so both sides report the same outcome for the same bytes.

func IsSecurity

func IsSecurity(tier string) bool

IsSecurity reports whether a tier is a security notice, visible to root only.

func Mode

func Mode(ctx context.Context, s Settings) string

Mode returns the validated updates.announcements value; anything else is off.

func RequiredSignatures

func RequiredSignatures(tier string) int

RequiredSignatures is how many distinct trusted keys must sign a tier. Critical needs two, so one leaked security key cannot raise a critical alarm.

func SafeErrorCode

func SafeErrorCode(stored string) string

SafeErrorCode returns stored as-is when it is one of the stable codes, and "fetch_failed" for anything else, such as a raw error an older version stored.

func ValidateItem

func ValidateItem(it Item, lim Limits) error

ValidateItem checks one item's content and targeting fields.

func ValidateLink(raw string) error

ValidateLink accepts only https links to the allowlisted hosts, without credentials, port, query or fragment.

Types

type Feed

type Feed struct {
	Schema    int       `json:"schema"`
	Sequence  int64     `json:"sequence"`
	IssuedAt  time.Time `json:"issued_at"`
	ExpiresAt time.Time `json:"expires_at"`
	Items     []Item    `json:"-"`
	Dropped   int       `json:"-"`
}

Feed is the parsed envelope. Dropped counts items skipped as malformed or of an unknown tier or kind; the rest of the feed is kept.

func ParseFeed

func ParseFeed(data []byte, lim Limits) (Feed, error)

ParseFeed decodes feed bytes tolerantly: unknown fields are ignored and a malformed or unknown-tier item is dropped without failing the feed.

type Fetcher

type Fetcher struct {
	Client *http.Client
	// LoopbackHTTP allows plain http to a loopback host, for dev instances only.
	LoopbackHTTP bool
}

Fetcher does conditional GETs. A nil Client uses the guarded client, which refuses private, loopback and link-local addresses at connect time.

func (Fetcher) Get

func (f Fetcher) Get(ctx context.Context, rawURL, etag string, limit int64) (Result, error)

Get fetches rawURL with If-None-Match when etag is set. The body is capped at limit bytes before any parsing; redirects are not followed.

type Item

type Item struct {
	ID        string    `json:"id"`
	Tier      string    `json:"tier"`
	Kind      string    `json:"kind"`
	Title     string    `json:"title"`
	Body      string    `json:"body"`
	AppliesTo string    `json:"applies_to,omitempty"`
	Channels  []string  `json:"channels,omitempty"`
	CTA       string    `json:"cta,omitempty"`
	Links     []Link    `json:"links,omitempty"`
	KeyID     string    `json:"key_id,omitempty"`
	IssuedAt  time.Time `json:"issued_at"`
	ExpiresAt time.Time `json:"expires_at"`
}

Item is one announcement. Unknown JSON fields are ignored so a newer feed still parses on an older binary.

func Decode

func Decode(r store.AnnouncementRow) (Item, error)

Decode parses a cached row back into an Item.

func Visible

func Visible(rows []store.AnnouncementRow, v Viewer) []Item

Visible filters cached items for one viewer: the mode, audience ability, expiry, release channel and the applies_to range against the running version.

type Key

type Key struct {
	ID     string
	Public ed25519.PublicKey
	Tiers  []string
}

Key is one trusted announcement signing key. Tiers limits what it may sign: a signature from a key counts only for items whose tier it lists.

func EffectiveKeys

func EffectiveKeys(devMode bool, extra []string) (keys []Key, ignoredExtra bool, err error)

EffectiveKeys returns the keys to trust. Extra keys from the runtime setting are honoured only in dev mode; in production mode they are ignored and the second result reports that, so a stray setting can never widen trust.

func ParseDevKeys

func ParseDevKeys(entries []string) ([]Key, error)

ParseDevKeys decodes "id:base64pubkey:tier|tier" entries. It is used only for test and dev instances, see EffectiveKeys.

func ProductionKeys

func ProductionKeys() []Key

ProductionKeys returns a copy of the embedded trusted keys.

func (Key) CanSign

func (k Key) CanSign(tier string) bool

CanSign reports whether the key may sign the tier.

type Limits

type Limits struct {
	MaxBytes  int64
	MaxItems  int
	MaxTitle  int
	MaxBody   int
	MaxAge    time.Duration
	ClockSkew time.Duration
}

Limits caps feed size and field lengths. Values come from runtime settings.

func LimitsFromSettings

func LimitsFromSettings(ctx context.Context, s Settings) Limits

LimitsFromSettings reads the feed caps from runtime settings.

type Link struct {
	Text string `json:"text"`
	URL  string `json:"url"`
}

Link is one outbound link, validated against the host allowlist.

type Manager

type Manager struct {
	Store    Store
	Settings Settings
	Fetcher  Fetcher
	// DevMode allows extra trusted keys from settings; never true in a release build.
	DevMode bool
	Logger  *slog.Logger
	Now     func() time.Time
	// contains filtered or unexported fields
}

Manager polls, verifies and caches the feed. Poll is safe to call on every scheduler tick: it decides itself whether a fetch is due.

func (*Manager) Poll

func (m *Manager) Poll(ctx context.Context) error

Poll fetches and verifies the feed when one is due. It never fetches while the mode is off or no trusted key exists, and offline errors are silent.

type Rejection

type Rejection struct {
	ID     string
	Code   string
	Reason string
}

Rejection records why one item was not accepted. Code is the shared drop code; Reason is the human detail.

type Result

type Result struct {
	Body        []byte
	ETag        string
	NotModified bool
}

Result is one response. NotModified means the ETag still matches.

type Settings

type Settings interface {
	String(ctx context.Context, key string) string
	Bool(ctx context.Context, key string) bool
	Int(ctx context.Context, key string) int
	Duration(ctx context.Context, key string) time.Duration
	List(ctx context.Context, key string) []string
}

Settings reads live runtime settings; *runtimesettings.Service satisfies it.

type Signature

type Signature struct {
	KeyID string `json:"key_id"`
	Sig   string `json:"sig"`
}

Signature is one detached signature entry in the .sig file.

func ParseSignatures

func ParseSignatures(b []byte) ([]Signature, error)

ParseSignatures decodes the detached signature list.

type Store

type Store interface {
	GetAnnouncementFeedState(ctx context.Context) (store.AnnouncementFeedState, error)
	RecordAnnouncementFetch(ctx context.Context, etag, fetchedAt, lastError string) error
	SaveAnnouncementFeed(ctx context.Context, st store.AnnouncementFeedState, rows []store.AnnouncementRow, revoked []string) error
	ListAnnouncements(ctx context.Context) ([]store.AnnouncementRow, error)
	ListRevokedAnnouncementKeys(ctx context.Context) ([]string, error)
}

Store is the narrow store surface the Manager needs; *store.DB satisfies it.

type Verified

type Verified struct {
	Feed    Feed
	Signers []string
	// SecuritySigned is true when a signer allowed to sign advisory or critical
	// items verified the whole file.
	SecuritySigned bool
	Items          []Item
	Revoked        []string
	Rejected       []Rejection
}

Verified is an authenticated feed: Items passed the signature tier rules and the content rules, Revoked lists keys a critical revoke_key item named.

func VerifyFeed

func VerifyFeed(in VerifyInput) (Verified, error)

VerifyFeed authenticates feed bytes against trusted keys, then applies sequence, expiry, tier and content rules. Any whole-feed failure returns an error; per-item failures only drop that item.

type VerifyInput

type VerifyInput struct {
	Data         []byte
	SigData      []byte
	Keys         []Key
	Revoked      map[string]bool
	LastSequence int64
	// LastSecuritySequence is the replay counter for feeds carrying a signer that
	// may sign advisory or critical items; a low-tier-only feed never touches it.
	LastSecuritySequence int64
	// MaxSequenceJump caps how far one feed may move its counter; 0 means no cap.
	MaxSequenceJump int64
	Now             time.Time
	Limits          Limits
}

VerifyInput is everything VerifyFeed needs; it does no I/O.

type VersionRange

type VersionRange []comparator

VersionRange is an AND of comparators such as ">=1.5.0,<1.5.14".

func ParseRange

func ParseRange(s string) (VersionRange, error)

ParseRange parses a comma or space separated list of comparators. An empty range or a bare wildcard is an error, so a targeted item cannot hit everyone.

func (VersionRange) Match

func (r VersionRange) Match(version string) bool

Match reports whether version satisfies every comparator.

type Viewer

type Viewer struct {
	IsRoot  bool
	CanRead bool
	Version string
	Channel string
	Mode    string
	// Newsletter is the updates.announcements_newsletter setting.
	Newsletter bool
	Now        time.Time
}

Viewer describes who is asking and which build they run.

Jump to

Keyboard shortcuts

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