app

package
v1.7.0 Latest Latest
Warning

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

Go to latest
Published: Sep 18, 2026 License: AGPL-3.0 Imports: 55 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultAgentSpoolMaxMemoryBytes int64 = 16777216
	DefaultAgentSpoolMaxDiskBytes   int64 = 134217728
	DefaultAgentSpoolMaxAgeSeconds  int64 = 86400
)
View Source
const DefaultAddr = "127.0.0.1:8080"

DefaultAddr is the HTTP listen address used when MAINTENANT_ADDR is unset.

Variables

View Source
var Categories []FlagCategory

Categories organises Registry entries by section for --help output.

View Source
var ErrAgentSpoolSetting = errors.New(
	"agent spool setting is not a valid whole number of bytes or seconds: use a non-negative integer, or 0 to disable the spool")

ErrAgentSpoolSetting refuses a spool budget that does not parse.

View Source
var ErrContainerDownAfter = errors.New(
	"MAINTENANT_CONTAINER_DOWN_AFTER is not a valid duration: use a Go duration such as 5m, 30s or 1h30m")

ErrContainerDownAfter refuses a container-down threshold that does not parse.

View Source
var ErrDatabaseURLInAgentMode = errors.New(
	"MAINTENANT_DATABASE_URL is set but --mode=agent")

ErrDatabaseURLInAgentMode refuses an external database in agent mode rather than ignoring the setting: the agent's local store is not negotiable (FR-003, FR-030), and a silently dropped connection string would read as accepted.

View Source
var ErrMCPUnauthenticated = errors.New(
	"MAINTENANT_MCP=true but MAINTENANT_MCP_CLIENT_ID/MAINTENANT_MCP_CLIENT_SECRET are unset: " +
		"/mcp is documented as bypassing the reverse-proxy auth, so it would serve containers, logs " +
		"and alerts to anyone reaching it. Set both, or set MAINTENANT_MCP_ALLOW_UNAUTHENTICATED=true " +
		"to accept that on a trusted network")

ErrMCPUnauthenticated refuses to expose an MCP server that answers to anyone. docs/security.md has the reverse proxy let /mcp through unauthenticated, so missing OAuth credentials do not degrade the protection — they remove it.

View Source
var ErrTrustedProxies = errors.New(
	"MAINTENANT_TRUSTED_PROXIES is not a valid list: use comma-separated CIDRs or IP addresses such as 10.0.0.0/8,192.168.1.4")

ErrTrustedProxies refuses a proxy list that does not parse.

View Source
var Registry []FlagSpec

Registry is the single source of truth for all CLI/env configuration options.

Functions

func CertificateStatus

func CertificateStatus(cert *certificate.CertMonitor) string

CertificateStatus derives the status page status for a certificate monitor.

func ContainerStatus

func ContainerStatus(c *container.Container) string

ContainerStatus derives the status page status for a container.

func EndpointStatus

func EndpointStatus(ep *endpoint.Endpoint) string

EndpointStatus derives the status page status for an endpoint.

func HeartbeatStatus

func HeartbeatStatus(hb *heartbeat.Heartbeat) string

HeartbeatStatus derives the status page status for a heartbeat.

func IsStreamingPath

func IsStreamingPath(path string) bool

IsStreamingPath reports whether path corresponds to an SSE or streaming endpoint.

func MapSecuritySeverity

func MapSecuritySeverity(s string) string

MapSecuritySeverity maps security insight severity to alert severity.

func MergeArgsIntoConfig added in v1.4.0

func MergeArgsIntoConfig(cfg *Config, visited map[string]string) error

MergeArgsIntoConfig applies visited CLI flags into cfg, overriding env values.

func ParseFlagsOrDie added in v1.4.0

func ParseFlagsOrDie(args []string) (map[string]string, error)

ParseFlagsOrDie parses args using the Registry and returns a map of explicitly set flag names to their string values.

func PrintHelp added in v1.4.0

func PrintHelp(w io.Writer, _ Config)

PrintHelp writes the formatted help text to w.

func SPAHandler

func SPAHandler(apiHandler http.Handler, logger *slog.Logger) http.Handler

SPAHandler returns an http.Handler that serves the embedded SPA frontend. API and ping routes are delegated to the API handler; everything else is served from the embedded filesystem, with a fallback to index.html for client-side routing.

func ScanContainerSecurity

func ScanContainerSecurity(ctx context.Context, dr *docker.Runtime, containerSvc *container.Service, secSvc *security.Service, externalID string, logger *slog.Logger)

ScanContainerSecurity inspects a single container and updates its security insights.

func SecurityHeaders added in v1.3.9

func SecurityHeaders(csp string) func(http.Handler) http.Handler

SecurityHeaders bounds what a browser will do with a response from this origin. Applied outside the timeout handler so the headers are on the wire even when it writes its own 503, and with Set so a route with a stricter policy of its own — the status page asset route — still wins by overwriting.

Framing is refused everywhere except the public status page, which docs and SECURITY.md both describe as embeddable. The dashboard and the admin API are the surfaces a clickjacker would want, and they are the ones locked down.

No HSTS here: TLS terminates at the reverse proxy, and deriving "this was HTTPS" from a forwarded header would trust something a client can forge. It belongs in the proxy config, where SECURITY.md puts it.

func WithRequestTimeout

func WithRequestTimeout(h http.Handler, timeout time.Duration) http.Handler

WithRequestTimeout wraps non-streaming handlers with http.TimeoutHandler so that ordinary REST requests are bounded even though the server-level WriteTimeout is disabled (required for SSE).

func WorstStatus

func WorstStatus(a, b string) string

WorstStatus returns the most severe status between two values.

Types

type App

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

App holds all application services and manages their lifecycle.

func New

func New(cfg Config, logger *slog.Logger) (*App, error)

New creates and wires all application services.

func (*App) RunMCPStdio

func (a *App) RunMCPStdio(ctx context.Context) error

RunMCPStdio runs the MCP server over stdin/stdout, then returns.

func (*App) Shutdown

func (a *App) Shutdown() error

Shutdown performs a graceful shutdown of all services.

func (*App) Start

func (a *App) Start(ctx context.Context) error

Start begins all background services and the HTTP server. It blocks until ctx is canceled, then performs a graceful shutdown.

type CVEEvaluationPostureAdapter added in v1.5.0

type CVEEvaluationPostureAdapter struct {
	Store update.UpdateStore
}

CVEEvaluationPostureAdapter adapts the update store for CVE evaluation state.

func (*CVEEvaluationPostureAdapter) GetCVEEvaluation added in v1.5.0

func (a *CVEEvaluationPostureAdapter) GetCVEEvaluation(ctx context.Context, containerExternalID string) (*security.CVEEvaluationInfo, error)

type CVEPostureAdapter

type CVEPostureAdapter struct {
	Store update.UpdateStore
}

CVEPostureAdapter adapts the update store for CVE scoring.

func (*CVEPostureAdapter) ListCVEsForContainer

func (a *CVEPostureAdapter) ListCVEsForContainer(ctx context.Context, containerExternalID string) ([]security.CVEInfo, error)

type CertPostureAdapter

type CertPostureAdapter struct {
	CertSvc *certificate.Service
}

CertPostureAdapter adapts the certificate service for posture scoring.

func (*CertPostureAdapter) ListCertificatesForContainer

func (a *CertPostureAdapter) ListCertificatesForContainer(ctx context.Context, containerExternalID string) ([]security.CertificateInfo, error)

type Config

type Config struct {
	// Server
	Addr    string
	BaseURL string

	// Database
	DBPath string
	// DatabaseURL is the operator-supplied PostgreSQL connection string.
	// Empty — the default and the only supported agent setup — means SQLite
	// on DBPath. It carries a password: never log or render it directly,
	// always through store.RedactDSN.
	DatabaseURL string
	Retention   RetentionConfig

	// License
	LicenseKey string

	// SMTP
	SMTP SMTPConfig

	// MCP
	MCP MCPConfig

	// HTTP
	CORSOrigins string
	MaxBodySize int64
	// TrustedProxies lists the CIDRs and addresses whose forwarded headers are
	// believed, comma-separated. Empty means no header is ever read.
	TrustedProxies string

	// CACertFile is a PEM bundle appended to the system roots, so endpoints and
	// certificates signed by an internal PKI validate without disabling checks.
	CACertFile string

	// Branding
	OrgName string

	// Status page
	StatusURL string // public URL of the status page (e.g. https://status.example.com)

	// Kubernetes
	K8sNamespaces string
	K8sExcludeNS  string

	// Security
	SecurityScoreThreshold int

	// ContainerDownAfter is how long a container must stay stopped before it
	// raises an alert. Zero disables the check.
	ContainerDownAfter time.Duration
	// ContainerDownAfterInvalid holds a rejected threshold verbatim, so a typo
	// stops startup instead of silently leaving the check off.
	ContainerDownAfterInvalid string

	// Telemetry
	DisableTelemetry bool

	DisableOSEOLRefresh bool

	ProxyLabels bool

	// Multi-host agent mode (Pro only)
	Mode      string // "embedded" | "server" | "agent"
	MultiHost MultiHostConfig

	// Dev
	AllowPrivateWebhooks bool

	// Runtime / logging (set via CLI flags; runtime override propagated to env)
	LogLevel string

	// Build info (injected via ldflags)
	Version      string
	Commit       string
	BuildDate    string
	PublicKeyB64 string
}

Config holds all application configuration parsed from environment variables.

func ConfigFromEnv

func ConfigFromEnv() Config

ConfigFromEnv reads configuration from environment variables.

func (Config) ParseTrustedProxies added in v1.5.0

func (c Config) ParseTrustedProxies() ([]netip.Prefix, error)

ParseTrustedProxies returns the prefixes whose forwarded headers are believed.

func (Config) ValidateAgentSpool added in v1.6.0

func (c Config) ValidateAgentSpool() error

ValidateAgentSpool refuses a spool budget that would silently be replaced by its default.

func (Config) ValidateAlerting added in v1.5.0

func (c Config) ValidateAlerting() error

ValidateAlerting refuses an alerting configuration that would leave a check silently off.

func (Config) ValidateHTTP added in v1.3.9

func (c Config) ValidateHTTP() error

func (Config) ValidateProxies added in v1.5.0

func (c Config) ValidateProxies() error

ValidateProxies refuses a trusted-proxy list that would silently be ignored.

func (Config) ValidateStorage added in v1.4.0

func (c Config) ValidateStorage() error

ValidateHTTP rejects a configuration that must not be served over HTTP. It is deliberately not called from New(): --mcp-stdio shares that path and never listens, so refusing there would break a local stdio client for no gain. ValidateStorage refuses a storage configuration the mode cannot honour. The agent stores its state in SQLite, always (FR-003, FR-030); server and embedded both run the same server plane and accept an external database.

type FlagCategory added in v1.4.0

type FlagCategory struct {
	Name  string
	Specs []FlagSpec
}

FlagCategory groups related flags for --help display.

type FlagSpec added in v1.4.0

type FlagSpec struct {
	EnvName     string
	FlagName    string
	Type        FlagType
	Default     string
	Description string
	Sensitive   bool
	// NoEnv marks an action flag that has no environment equivalent
	// (--copy-store-to, --yes): it drives what the process does, it is not
	// part of the configuration an operator writes in maintenant.env.
	NoEnv   bool
	ApplyTo func(*Config, string) error
}

FlagSpec describes one configuration option: its env var, CLI flag, type, default value, and how to apply it to a Config.

type FlagType added in v1.4.0

type FlagType int

FlagType is the value type of a configuration flag.

const (
	FlagTypeString FlagType = iota
	FlagTypeInt
	FlagTypeBool
	FlagTypeDuration
)

type InvalidSetting added in v1.6.0

type InvalidSetting struct {
	Name string
	Raw  string
}

InvalidSetting is a configuration value that was rejected rather than replaced by its default.

type MCPConfig

type MCPConfig struct {
	Enabled             bool
	ClientID            string
	ClientSecret        string
	AllowedRedirectURIs string
	// AllowUnauthenticated is the explicit opt-out for serving /mcp with no
	// OAuth at all; without it, MCP without credentials refuses to listen.
	AllowUnauthenticated bool
}

MCPConfig holds Model Context Protocol server configuration.

type MultiHostConfig added in v1.3.0

type MultiHostConfig struct {
	GRPCPublicURL              string
	GRPCListen                 string
	AgentRateLimitPerSecond    int
	AgentStaleThresholdSeconds int
	// TLS (for mode=server)
	TLSCertFile  string
	TLSKeyFile   string
	InsecureGRPC bool // h2c mode — use only behind a trusted reverse proxy
	// Agent flags (for mode=agent)
	ServerURL                string
	EnrollmentToken          string
	RuntimeOverride          string
	Label                    string
	NodeName                 string
	InsecureSkipVerify       bool
	EmbeddedAgent            bool
	AgentSpoolMaxMemoryBytes int64
	AgentSpoolMaxDiskBytes   int64
	AgentSpoolMaxAgeSeconds  int64
	InvalidSpoolSettings     []InvalidSetting
}

MultiHostConfig holds multi-server agent configuration (Pro only).

type RetentionConfig added in v1.3.8

type RetentionConfig struct {
	// Snapshots is how long raw resource samples are kept. The 24h range is the
	// longest one reading them, so 24h is the floor; longer ranges are served
	// from the hourly rollup and are unaffected.
	Snapshots time.Duration
	Interval  time.Duration
	BatchSize int
}

RetentionConfig holds the tunable part of the retention cleanup. Zero values mean "use the store defaults".

type SMTPConfig

type SMTPConfig struct {
	Host     string
	Port     string
	Username string
	Password string
	From     string
}

SMTPConfig holds SMTP mail server configuration.

type UpdatePostureAdapter

type UpdatePostureAdapter struct {
	Store update.UpdateStore
}

UpdatePostureAdapter adapts the update store for update/image-age scoring.

func (*UpdatePostureAdapter) ListUpdatesForContainer

func (a *UpdatePostureAdapter) ListUpdatesForContainer(ctx context.Context, containerExternalID string) ([]security.UpdateInfo, error)

Jump to

Keyboard shortcuts

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