server

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 11, 2026 License: Apache-2.0 Imports: 57 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 server is the upgradescope continuous-mode server: snapshot ingest, persisted evaluations, a read API, and on-demand what-if re-evaluation. Storage is behind store.Store; the CLI owns flag parsing and store construction (DB path never reaches this package).

Index

Examples

Constants

View Source
const DefaultMaxGateBytes = 10 << 20 // 10 MiB

DefaultMaxGateBytes caps the /gate manifest stream when Config.MaxGateBytes is unset. Lower than the snapshot cap: the gate body is buffered whole and is reachable with only the read token (or none).

View Source
const DefaultMaxSnapshotBytes = 20 << 20 // 20 MiB

DefaultMaxSnapshotBytes caps the snapshot push body when Config.MaxSnapshotBytes is unset — enforced on the wire bytes AND on the decompressed stream (gzip-bomb guard).

View Source
const DefaultStaleAfter = 2 * time.Hour

DefaultStaleAfter is how long a cluster may go without a push before the API and /metrics call it stale. An agent pushes on every change and at least every --force-sync-every (1h), on its next tick (10m by default), so an unchanged, healthy cluster pushes about every 70 minutes; 2h leaves room for that and one missed push. It matches the chart's UpgradescopeClusterStale alert (7200s).

View Source
const ExtraTargetsCost = "each one adds a report of up to --max-snapshot-bytes to every push and to the re-evaluation pass, " +
	"and the server's memory bound is measured at that many (see Memory and request limits in the operations guide)"

ExtraTargetsCost says why MaxExtraTargets exists, for its refusals.

View Source
const MaxExtraTargets = 4

MaxExtraTargets is how many distinct Config.ExtraTargets (serve --targets) New accepts. Each one adds a report of up to --max-snapshot-bytes to every ingest and to the re-evaluation pass, so the server's memory bound (docs/operations.md, make test-heap) is measured at this many.

View Source
const StarTeam = "(*)"

StarTeam is what a --team-map team called "*" is read as. "*" is the scope of a fleet-wide read token, so no token could name a team called that; this name a team-scoped token can.

Variables

This section is empty.

Functions

func ComputeDelta

func ComputeDelta(prev *engine.Report, curr engine.Report) []notify.Change

ComputeDelta implements the notification delta rules for one target:

  • prev == nil (first-ever evaluation of this cluster+target) → nothing.
  • Blocker findings added since prev (diff by stable finding key) → one new-blocker change each.
  • Blocker count went >0 → 0 AND curr.Verdict is ready → one became-ready change. Zero blockers with verdict unknown (a required check was not assessed, e.g. a transient collector failure) is not readiness, and neither is a pass that could not see a blocker of prev (computeDelta).
  • eol-approaching warnings added since prev (by key) → one change each.

Identity is Finding.Key — deliberately count-free, so a title-only change ("3 objects" → "2 objects") never re-alerts the same blocker. Findings with an empty Key (reports stored before Key existed) fall back to Title. Duplicate keys within one report give one change (first occurrence wins).

Every change lists curr's target; buildNotification merges and caps the changes of one pass across targets. Order is deterministic: new-blockers in report order, became-ready, eol-approaching in report order.

func ParseAllowedHost added in v0.2.0

func ParseAllowedHost(raw string) (string, error)

ParseAllowedHost checks one --allowed-host entry and returns it as the guard compares it: a DNS name or an IP address, without a port, scheme or path (any port matches), lowercased and without a trailing dot.

Example
for _, raw := range []string{"Upgradescope.Example.com.", "[fd00::1]", "upgradescope.example.com:443"} {
	h, err := ParseAllowedHost(raw)
	fmt.Println(h, err != nil)
}
Output:
upgradescope.example.com false
fd00::1 false
 true

func WhatIf

func WhatIf(ctx context.Context, st store.Store, k kb.KB, tm TeamMap, clusterID int64, target inventory.Version, now time.Time) (engine.Report, error)

WhatIf re-evaluates a cluster's latest stored snapshot against an arbitrary target using the server's KB. Nothing is stored. now is injected by the caller (the server passes s.now()) so EOL-window math stays deterministic and testable. tm (nil = no-op) applies the server's namespace→team override, and the objects' ignore annotations are applied (suppressAnnotated), matching what ingest stores. Returns store.ErrNotFound (wrapped) when the cluster has no snapshots.

Types

type Config

type Config struct {
	Listen       string          // listen address for Start, e.g. ":8080"
	Store        store.Store     // required
	KB           kb.KB           // evaluation knowledge base
	ExtraTargets []string        // minors evaluated for every snapshot, e.g. ["1.37"]
	Notifier     notify.Notifier // nil = notifications disabled
	IngestToken  string          // optional shared bearer for POST /api/v1/snapshots (any cluster); "" = per-cluster tokens only
	ReadToken    string          // optional bearer for the read API; "" = open on loopback only, unless AllowAnonymousRead
	// AllowAnonymousRead serves an open read API (ReadToken "") on an
	// address that is not loopback. Without it Start refuses one.
	AllowAnonymousRead bool
	// RequireReadCredential keeps the read API closed whatever the store
	// holds: it is never open (readOpen is false), so a read with no
	// credential, or with a bearer nothing knows, is 401 even when no read
	// token has been minted yet or the database was lost and replaced by an
	// empty one. Without it the closed state lives only in the read_tokens
	// rows (#295). New refuses it together with AllowAnonymousRead.
	RequireReadCredential bool
	// TrustTeamHeader and TrustedProxies, always together, are the
	// trusted-proxy mode: a read whose TCP peer is in TrustedProxies and
	// that carries this header (an authenticating proxy's group header,
	// e.g. X-Forwarded-Groups) reads as the teams it lists (proxyScope).
	// Dangerous unless that proxy strips the header from what clients
	// send, and nothing but it can reach the server from those addresses.
	TrustTeamHeader string
	TrustedProxies  []netip.Prefix
	AdminToken      string  // bearer for cluster delete/rename (also accepted for reads); "" = both refused
	TeamMap         TeamMap // optional namespace→team override, applied before every Evaluate
	Version         string  // build version: SARIF tool metadata ("" = omitted there) and toolVersion in report responses ("" when unset)

	// AllowedHosts are the names, besides loopback, localhost, the Listen
	// host and the address a request arrived on, that a request's Host may
	// name while the Host guard is on (a loopback listener, or
	// TrustTeamHeader set): the Service, Ingress or proxy names the server
	// is reached under. Any port matches. See hostcheck.go.
	AllowedHosts []string

	// StaleAfter marks a cluster stale when its agent has not pushed
	// (duplicates included) for longer; 0 = DefaultStaleAfter.
	StaleAfter time.Duration
	// Retention prunes snapshots and evaluations older than this, except
	// each cluster's latest snapshot and its evaluations, at startup and
	// daily; 0 = keep everything.
	Retention time.Duration

	MaxSnapshotBytes int64 // POST /api/v1/snapshots body cap; 0 = DefaultMaxSnapshotBytes
	MaxGateBytes     int64 // POST /api/v1/gate body cap; 0 = DefaultMaxGateBytes

	// TLSCertFile/TLSKeyFile (PEM) make Start serve HTTPS; both or neither.
	// Loaded in New (a bad pair fails it) and re-read when either file
	// changes, checked at most once a second on a new handshake, so a
	// rotated certificate needs no restart.
	TLSCertFile string
	TLSKeyFile  string

	// IngestTokenFile, ReadTokenFile and AdminTokenFile name a file that
	// holds the token (a mounted Secret), in place of IngestToken,
	// ReadToken and AdminToken. They are read in New (a missing, empty or
	// unacceptable file fails it) and re-read when the file changes,
	// checked at most every 5 seconds on a request that needs the token, so
	// a rotated token needs no restart; a new file that is empty or
	// unreadable, or that would make two of the tokens equal, leaves the old
	// token in service and is logged, naming the file and never the token.
	IngestTokenFile string
	ReadTokenFile   string
	AdminTokenFile  string
	// IngestTokenFileOptional lets IngestTokenFile be missing in New (no
	// shared ingest token yet) and makes removing the file revoke the
	// token: a key dropped from a Secret stops the old token working.
	IngestTokenFileOptional bool
	// contains filtered or unexported fields
}

Config wires a Server.

type Server

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

Server serves the ingest + read API. Construct with New; a Server is single-use (one Start/Shutdown cycle).

func New

func New(cfg Config) (*Server, error)

New validates cfg and builds the route table.

func (*Server) Addr

func (s *Server) Addr() string

Addr returns the bound listen address ("" before Ready is closed).

func (*Server) Handler

func (s *Server) Handler() http.Handler

Handler exposes the full route table (API + dashboard fallback) for httptest and embedding.

func (*Server) Ready

func (s *Server) Ready() <-chan struct{}

Ready is closed once the listener is bound. It is NEVER closed when Listen fails — Start just returns the error — so callers must not block on Ready alone: run Start in a goroutine and select on Ready() AND the goroutine's error channel, or a bad Listen address hangs the caller.

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

Shutdown gracefully drains in-flight requests until ctx ends, then closes whatever is still open, and unblocks Start. A connection still active at the deadline is a stalled or abusive client (ReadTimeout and WriteTimeout bound every legitimate request), so cutting it off is the expected end of the drain, not a shutdown failure.

A Shutdown that comes before Start has started serving makes Start return nil without serving or starting any background work.

Background work stops after the drain: a notification mid-delivery is cancelled and stays in the outbox (its lease expires and the next start delivers it); a re-evaluation mid-commit rolls back.

func (*Server) Start

func (s *Server) Start() error

Start binds Config.Listen and serves until Shutdown. It returns nil after a clean Shutdown, otherwise the listen/serve error. Once Ready() is closed, Addr() reports the bound address (Listen ":0" works in tests).

Without a read token the read API is open, which Start allows only on a loopback address unless AllowAnonymousRead says otherwise. It checks the address it actually bound, after binding, so no name resolution decides it: "localhost" mapped to a routable address in /etc/hosts, a hostname, or ":8080" (every interface) is refused, and nothing is served on it in between. With RequireReadCredential the API is never open, so no address is refused for it.

On a loopback address, every request must name a host the server answers for (hostcheck.go), whatever the credentials: a DNS-rebinding page reaches a loopback socket naming its own host. Wherever it listens, an anonymous read of an open read API must too (hostRefused).

type TeamMap

type TeamMap []TeamMapRule

TeamMap is the server-side namespace→team override (spec: labels + server override). It is applied over the namespace team labels carried in the inventory at evaluation time — a matching rule replaces the label; a namespace matching no rule keeps its label. A nil/empty TeamMap is a no-op.

func LoadTeamMap

func LoadTeamMap(p string) (TeamMap, error)

LoadTeamMap reads and parses a --team-map YAML file.

func ParseTeamMap

func ParseTeamMap(data []byte) (TeamMap, error)

ParseTeamMap parses YAML of the form:

  • pattern: "payments-*" team: payments

Every rule must have a non-empty pattern (valid path.Match glob) and a non-empty team. A team is free text ("Platform Team", "Équipe, Paris"): read scopes name it in the team list encoding (decodeTeams) or one per tokens create --teams flag. The one exception is a team called "*", which is read as StarTeam (logged), since "*" is a read token's scope of the whole fleet; a team called engine.UnattributedTeam is refused, being the name of the findings no team owns; a map that also names StarTeam itself is warned that the two are now one team.

func (TeamMap) Apply

Apply returns a rewritten copy of ns: for each namespace, the first rule whose glob matches sets the team; no match keeps the inventory label. The input slice is never mutated (it may alias a caller's inventory).

type TeamMapRule

type TeamMapRule struct {
	Pattern string `json:"pattern"`
	Team    string `json:"team"`
}

TeamMapRule maps namespaces matching a glob Pattern (path.Match grammar) to Team. Rules are ordered; the first matching pattern wins.

Directories

Path Synopsis
Package notify defines the notification seam fired on finding deltas (new blocker, became-ready, add-on entering the EOL window) — never on every snapshot.
Package notify defines the notification seam fired on finding deltas (new blocker, became-ready, add-on entering the EOL window) — never on every snapshot.
Package store persists clusters, snapshots and evaluations for the upgradescope server.
Package store persists clusters, snapshots and evaluations for the upgradescope server.
storetest
Package storetest pins the behavioral contract of store.Store.
Package storetest pins the behavioral contract of store.Store.

Jump to

Keyboard shortcuts

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