server

package
v0.21.2 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: Apache-2.0 Imports: 50 Imported by: 0

Documentation

Index

Constants

View Source
const RiverUIPrefix = "/api/admin/river"

RiverUIPrefix is where River UI mounts. The auth middleware covers only /api/, and the route table holds no scope for it, so a service key never reaches it.

Variables

This section is empty.

Functions

func InstallEdgeMiddleware added in v0.9.0

func InstallEdgeMiddleware(router chi.Router, cfg *platform.Config, live *settings.Live) (mountMetrics func())

InstallEdgeMiddleware registers every middleware a request passes through before it reaches session handling, authentication, or any route: security headers, request ID, CORS, panic recovery, request logging, and rate limiting (plus Prometheus instrumentation unless METRICS_ENABLED=false).

Order matters here, and it is the reason this lives in its own function rather than inline in Build: the rate limiter and the request logger both need to agree on who a request came from, so anything that establishes the client identity must run before either of them. Exporting it lets tests exercise the real chain — in the real order — without a database.

It returns mountMetrics, which registers the /metrics endpoint. Callers must call it only after adding every middleware of their own: chi panics if Use is called once any route exists on the mux, and route registration order has no effect on which middleware a route runs through.

func NewNotifierForTest added in v0.16.0

func NewNotifierForTest(pool *pgxpool.Pool) *webhooks.Notifier

NewNotifierForTest builds a notifier over an insert-only client, so a test can drive a change inside a transaction of its own.

func RegisterAPIRoutes added in v0.10.0

func RegisterAPIRoutes(api huma.API, router chi.Router, d RegisterAPIDeps) *evalqueue.PoolExecutor

RegisterAPIRoutes registers every /api/* route: health, readiness, capabilities, auth, skills, sync manifest, analytics, import, eval suites, eval queue, and quality. It does not register the embedded SPA catch-all — callers that serve the SPA (only Build) mount that separately, after this returns, per Huma/chi ordering requirements.

It returns the eval queue's PoolExecutor so Build can start the lease reaper against the same queue this registered — constructing a second PoolExecutor there would work against the same table but would be a needless second handle, and would drift from this function if the two ever needed to differ.

Types

type AllowAll

type AllowAll struct{}

func (AllowAll) Authorize

func (AllowAll) Authorize(_ context.Context, _ *auth.User, _, _ string) error

type AllowAllPolicy

type AllowAllPolicy struct{}

func (AllowAllPolicy) CheckActivation

func (AllowAllPolicy) CheckActivation(_ context.Context, _, _ string) error

func (AllowAllPolicy) CheckPublish

func (AllowAllPolicy) CheckPublish(_ context.Context, _ *skill.Skill) error

type AuditEvent

type AuditEvent struct {
	UserID   string
	Action   string
	Resource string
	Detail   string
}

type AuditLogger

type AuditLogger interface {
	Log(ctx context.Context, event AuditEvent) error
}

type Authorizer

type Authorizer interface {
	Authorize(ctx context.Context, user *auth.User, action, resource string) error
}

type Builder

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

Builder assembles a Server from its constituent parts. The zero value is not useful — use NewBuilder. Callers chain With* methods to opt into enterprise extension points, then call Build to get a runnable Server.

func NewBuilder

func NewBuilder(pool *pgxpool.Pool, config *platform.Config) *Builder

NewBuilder creates a Builder with OSS defaults: no extension points, no enterprise features, edition "oss".

func (*Builder) Build

func (b *Builder) Build() (*Server, error)

Build assembles all server components from the builder and returns a Server ready to serve. It creates the session manager, storage, auth stores, router, Huma API, all routes, and the embedded SPA mount. It does NOT call ListenAndServe — that's a separate method on Server so callers can inject test transports or configure TLS before starting.

func (*Builder) Capabilities

func (b *Builder) Capabilities() *Capabilities

Capabilities returns the Capabilities value accumulated so far. This is primarily useful for testing — in production you call Build.

func (*Builder) WithAuditLog

func (b *Builder) WithAuditLog(l AuditLogger) *Builder

WithAuditLog attaches an AuditLogger and enables the audit feature flag.

func (*Builder) WithAuthorizer

func (b *Builder) WithAuthorizer(a Authorizer) *Builder

WithAuthorizer attaches an Authorizer (RBAC) and enables the rbac and teams feature flags.

func (*Builder) WithClaim added in v0.19.0

func (b *Builder) WithClaim() *Builder

WithClaim requires the claim code, which the server logs at start, before the first person can sign up.

func (*Builder) WithEdition

func (b *Builder) WithEdition(edition string) *Builder

WithEdition overrides the edition string (e.g. "enterprise") in capability responses.

func (*Builder) WithEnv added in v0.19.0

func (b *Builder) WithEnv(env map[string]string) *Builder

WithEnv replaces the process environment the settings resolve against.

func (*Builder) WithIdentityProvider

func (b *Builder) WithIdentityProvider(idp IdentityProvider) *Builder

WithIdentityProvider attaches an IdentityProvider (SSO) and enables the sso feature flag.

func (*Builder) WithLicense

func (b *Builder) WithLicense(l *LicenseInfo) *Builder

WithLicense sets the license metadata returned by the capabilities endpoint.

func (*Builder) WithMasterKey added in v0.19.0

func (b *Builder) WithMasterKey(k *settings.MasterKey) *Builder

WithMasterKey records where the master key came from, for the settings page.

func (*Builder) WithPolicyEnforcer

func (b *Builder) WithPolicyEnforcer(p PolicyEnforcer) *Builder

WithPolicyEnforcer attaches a PolicyEnforcer and enables the governance feature flag.

func (*Builder) WithRoutes

func (b *Builder) WithRoutes(registrars ...RouteRegistrar) *Builder

WithRoutes registers additional route registrars that are called during Build after all core routes are wired. Enterprise plugins use this to inject their own endpoints.

func (*Builder) WithScanRules

func (b *Builder) WithScanRules(s ScanRuleProvider) *Builder

WithScanRules attaches a ScanRuleProvider and enables the custom_scan feature flag.

func (*Builder) WithVersion added in v0.10.0

func (b *Builder) WithVersion(version string) *Builder

WithVersion records the build version reported by the capabilities endpoint, so the dashboard and the server logs agree about which build is running.

type Capabilities

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

func NewCapabilities

func NewCapabilities() *Capabilities

func (*Capabilities) EnableFeature

func (c *Capabilities) EnableFeature(name string)

func (*Capabilities) Register

func (c *Capabilities) Register(api huma.API)

func (*Capabilities) Response

func (c *Capabilities) Response() CapabilitiesResponse

func (*Capabilities) SetEdition

func (c *Capabilities) SetEdition(edition string)

func (*Capabilities) SetLicense

func (c *Capabilities) SetLicense(l *LicenseInfo)

func (*Capabilities) SetSignIn added in v0.17.0

func (c *Capabilities) SetSignIn(m func() auth.SignInMethods)

SetSignIn records where the sign-in methods the SPA may show come from. It is read on each request, so a settings change shows without a restart.

func (*Capabilities) SetVersion added in v0.10.0

func (c *Capabilities) SetVersion(v string)

SetVersion records the build version reported by /api/capabilities. An empty value is ignored rather than stored: an unstamped build should read "dev", not blank.

type CapabilitiesResponse

type CapabilitiesResponse struct {
	Edition  string             `json:"edition"`
	Version  string             `json:"version"`
	Features Features           `json:"features"`
	License  *LicenseInfo       `json:"license"`
	SignIn   auth.SignInMethods `json:"sign_in"`
}

type Features

type Features struct {
	Teams             bool `json:"teams"`
	RBAC              bool `json:"rbac"`
	SSO               bool `json:"sso"`
	Audit             bool `json:"audit"`
	Governance        bool `json:"governance"`
	CustomScan        bool `json:"custom_scan"`
	AdvancedAnalytics bool `json:"advanced_analytics"`
}

type IdentityProvider

type IdentityProvider interface {
	Authenticate(ctx context.Context, token string) (*auth.User, error)
	MetadataURL() string
}

type LicenseInfo

type LicenseInfo struct {
	Org     string `json:"org"`
	Seats   int    `json:"seats"`
	Expires string `json:"expires"`
}

type NoopAuditLogger

type NoopAuditLogger struct{}

func (NoopAuditLogger) Log

type PolicyEnforcer

type PolicyEnforcer interface {
	CheckPublish(ctx context.Context, sk *skill.Skill) error
	CheckActivation(ctx context.Context, skillName, agent string) error
}

type ReadyChecks added in v0.6.0

type ReadyChecks struct {
	Database string `json:"database"`
	Storage  string `json:"storage"`
	// MasterKey is "degraded" when a key is lost or a secret does not open.
	// The server stays ready, so an owner can reach the recovery page.
	MasterKey string `json:"master_key"`
	// Evaluation is "degraded" when no judge and panel are set, or a
	// provider they use has no readable key. The server stays ready.
	Evaluation string `json:"evaluation"`
}

ReadyChecks holds the per-dependency readiness status. Each field is either "ok" or "unavailable" — real errors are logged server-side and never included in the HTTP response.

type RegisterAPIDeps added in v0.10.0

type RegisterAPIDeps struct {
	Pool   *pgxpool.Pool
	Config *platform.Config
	// Settings is the live settings snapshot. Nil resolves from an empty
	// environment, for spec generation.
	Settings *settings.Live
	// Claim guards the first sign-up. ClaimEnforced is false in tests.
	Claim         *onboarding.Claim
	ClaimEnforced bool
	// ArchiveStore names the archive store in effect, for the settings page.
	ArchiveStore string
	// Keys checks the master key. Nil for spec generation.
	Keys      *settings.KeyService
	People    *auth.People
	UserStore *auth.UserStore
	KeyStore  *auth.KeyStore
	Storage   platform.Storage
	Caps      *Capabilities
	// AnalyticsStore is optional; if nil, RegisterAPIRoutes constructs one
	// from Pool. Build() passes its own instance so the same store can be
	// reused for startup event-retention cleanup instead of constructing a
	// second one.
	AnalyticsStore *analytics.Store
	// JobInserter enqueues webhook deliveries inside a change's transaction.
	// Nil only for spec generation, which never runs a handler.
	JobInserter webhooks.JobInserter
	// RiverUI serves the job inspector. Nil only for spec generation.
	RiverUI http.Handler
	// Jobs enqueues outside a transaction, such as a git sync. Nil only for
	// spec generation.
	Jobs gitsync.JobInserter
	// GitSync is the syncer the River worker runs. Nil builds one that only
	// serves routes.
	GitSync *gitsync.Syncer
}

RegisterAPIDeps bundles everything RegisterAPIRoutes needs to wire the API. Every field except Pool, Router, and Caps may be nil (or the pool may be nil): RegisterAPIRoutes is used both by the real server, where every field is a live dependency, and by `skael-server --openapi`, which only needs the route shapes for spec generation and never executes a handler. The stores constructed here (skill.NewStore, evalqueue.NewPool, etc.) hold their pool reference lazily and don't touch it until a handler runs, so a nil pool is safe for registration-only use.

This is the single place both paths register routes from, specifically so they should not drift apart — see cmd/server/main.go's printOpenAPISpec. The guard test (routes_test.go) only checks routes registered inside this function; a new route group must be added here, not via a direct huma.Register call in Build() after RegisterAPIRoutes returns, or the guard cannot see it and the spec can silently drift again.

type RouteRegistrar

type RouteRegistrar func(api huma.API, router chi.Router, pool *pgxpool.Pool)

RouteRegistrar is a function that registers additional routes onto the Huma API and Chi router. Enterprise plugins use this to add their own endpoints.

type ScanRuleProvider

type ScanRuleProvider interface {
	ExtraRules(ctx context.Context) ([]scan.Rule, error)
}

type Server

type Server struct {
	// Handler is the fully assembled Chi router, ready to be passed to
	// http.Server or used in tests with httptest.NewServer.
	Handler http.Handler
	// contains filtered or unexported fields
}

Server wraps the assembled HTTP handler and configuration needed to start listening. Build() produces a Server; ListenAndServe() runs it.

func (*Server) ListenAndServe

func (s *Server) ListenAndServe() error

ListenAndServe starts the HTTP server and blocks until a SIGINT or SIGTERM is received, then performs a graceful shutdown with a 10-second timeout.

func (*Server) Start added in v0.16.0

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

Start runs background work: webhook deliveries and the periodic jobs. River elects one leader across replicas, so one replica runs each periodic job.

func (*Server) Stop added in v0.16.0

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

Stop ends background work. ListenAndServe calls it on shutdown.

Jump to

Keyboard shortcuts

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