server

package
v0.17.3 Latest Latest
Warning

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

Go to latest
Published: Jul 31, 2026 License: Apache-2.0 Imports: 30 Imported by: 0

Documentation

Overview

Package server holds the generated server wiring (Serve) and the functional options consumers use to register their business-logic ServerInterface implementation plus auth, WebAuthn-store, and HSM/KMS signer overrides. The cmd/server entrypoint is a thin wrapper around Serve; downstream services import this package directly:

server.Serve(ctx,
    server.WithImpl(myHandlers{}),            // business logic
    server.WithAuthJWT(myVerifier),           // e.g. RS256 / JWKS
    server.WithGetCertificate(hsmGetCert),    // HSM-backed TLS
    server.WithAuthMTLS(myCACVerifier),       // CAC/PIV issuer policy
)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Serve

func Serve(ctx context.Context, opts ...Option) error

Serve starts the generated API server with the supplied options. It blocks until ctx is cancelled or the listener fails.

Types

type Option

type Option func(*Options)

Option mutates Options.

func WithAuthAPIKey

func WithAuthAPIKey(fn func(*http.Request) error) Option

WithAuthAPIKey overrides the default API-key (HMAC) verifier.

func WithAuthJWT

func WithAuthJWT(fn func(*http.Request) error) Option

WithAuthJWT overrides the default HS256 JWT verifier (e.g. RS256/JWKS).

func WithAuthMTLS

func WithAuthMTLS(fn func(*http.Request, securex.MTLSPolicy) error) Option

WithAuthMTLS wires the mTLS issuer-label verifier (PIV/CAC/custom).

func WithCorrelation added in v0.15.1

func WithCorrelation(header string) Option

WithCorrelation overrides the correlation-ID header name used both on the wire (inbound honored / outbound echoed) and as the log token. It takes priority over the APIC_CORRELATION_HEADER env var and the observability.tracing.correlation_header config. An empty header selects the default (X-Correlation-ID).

func WithExtraRoutes

func WithExtraRoutes(fn func(mux *http.ServeMux)) Option

WithExtraRoutes registers application-specific routes on the server mux after the generated API/WS routes (see Options.ExtraRoutes). Each handler must enforce its own auth; patterns must not collide with generated routes.

func WithGetCertificate

func WithGetCertificate(fn func(*tls.ClientHelloInfo) (*tls.Certificate, error)) Option

WithGetCertificate wires an HSM/KMS-backed TLS certificate source.

func WithHealthCheck added in v0.15.1

func WithHealthCheck(name string, fn func(context.Context) error) Option

WithHealthCheck registers a named health check backed by a plain func(context.Context) error against the control-plane health subsystem. The name must match a health.checks[] entry declared in the config; the check participates in whichever probes (startup/readiness) that entry lists. A non-nil error fails (or, for a non-critical check, degrades) the probe it runs in.

func WithHealthChecker added in v0.15.1

func WithHealthChecker(name string, checker healthx.Checker) Option

WithHealthChecker registers a named health check backed by a healthx.Checker implementation (use this over WithHealthCheck when the check needs to carry state). The name must match a health.checks[] entry declared in the config.

func WithImpl

func WithImpl(impl apic.ServerInterface) Option

WithImpl registers the business-logic implementation of the generated HTTP ServerInterface.

func WithInsecureHTTP

func WithInsecureHTTP() Option

WithInsecureHTTP opts the listener out of TLS and serves plain HTTP for deployments that terminate TLS upstream (ingress/mesh). It is the code-level equivalent of the config opt-in server.tls.mode:"off". This disables transport encryption on the listener — only use it when a trusted upstream (ingress controller, service mesh sidecar) terminates TLS and the process hop is on a trusted network. Without this option (or the config opt-in) Serve refuses to boot unless a TLS cert is configured.

func WithLogFile added in v0.15.1

func WithLogFile(cfg obsx.LogFileConfig) Option

WithLogFile enables rotating on-disk log delivery (lumberjack): structured log records are fanned into a size-rotated file IN ADDITION to stdout and any OTLP export, INSIDE the same redaction wrapper so on-disk lines are redacted too. It overrides the APIC_LOG_FILE env var and the observability.logs.file config block (precedence code > env > config). Zero size/backup/age members inherit the auditx defaults (100 MiB / 7 / 365d).

func WithLogger

func WithLogger(l *slog.Logger) Option

WithLogger configures a custom slog logger.

func WithMCPImpl

func WithMCPImpl(impl genmcp.MCPServerInterface) Option

WithMCPImpl registers the business-logic implementation of the generated MCP tool interface. When not supplied, genmcp.UnimplementedMCPServer{} is used (returns ErrNotImplemented for every tool). Register is always called so per-tool rate limits and RBAC (SetToolBuckets / SetToolRoles) are installed regardless of which impl is wired.

func WithMetrics

func WithMetrics(m obsx.MetricsProvider) Option

WithMetrics configures a custom metrics provider.

func WithMiddleware

func WithMiddleware(mw ...func(http.Handler) http.Handler) Option

WithMiddleware appends user middleware (runs after auth, rate limiting, CORS, and logging).

func WithOTEL added in v0.15.1

func WithOTEL(cfg otelx.Config) Option

WithOTEL enables the OpenTelemetry bootstrap with explicit code-level config; non-zero fields override the OTEL_* env vars, which override the observability.otel config block. Passing the zero otelx.Config simply forces the bootstrap on with env/config/default settings.

func WithPrometheus added in v0.15.1

func WithPrometheus(cfg ...promx.Config) Option

WithPrometheus forces the authenticated Prometheus /metrics endpoint on (equivalent to observability.metrics.enabled:true) with an optional provider config. The endpoint keeps the configured auth mode: "inherit" (the server's composite auth surface, default) or "bearer" (APIC_METRICS_TOKEN / _FILE, constant-time compare). It is never public.

func WithTelemetry

func WithTelemetry(tp *obsx.TelemetryProvider) Option

WithTelemetry configures OpenTelemetry tracing/metrics.

func WithTracing added in v0.15.1

func WithTracing(on bool) Option

WithTracing turns W3C trace-context propagation (traceparent/tracestate header parsing/forwarding) on or off explicitly, overriding the observability.tracing.enabled config block. It toggles headers-only propagation, not the OTEL exporter pipeline (span/metric export is controlled separately) — and it never disables the correlation-ID middleware, which is always-on by design regardless of this setting. Propagation is on by default.

func WithWSImpl

func WithWSImpl(impl genws.WSServerInterface) Option

WithWSImpl registers the business-logic implementation of the generated WebSocket interface.

type Options

type Options struct {
	Logger     *slog.Logger
	Middleware []func(http.Handler) http.Handler
	Metrics    obsx.MetricsProvider
	Telemetry  *obsx.TelemetryProvider

	// HealthChecks are the external dependency checks registered against the
	// control-plane health subsystem (/livez, /readyz, /startupz). Each
	// declared health.checks[] entry in the config expects a matching
	// registration here by name. Wire via WithHealthCheck / WithHealthChecker.
	HealthChecks []healthx.Registration

	// OTEL, when non-nil, overrides the env-derived OTLP bootstrap config
	// field-by-field (code wins over OTEL_* env vars, which win over the
	// observability.otel config block). Set via WithOTEL.
	OTEL *otelx.Config
	// LogFile, when non-nil, enables rotating on-disk log delivery
	// (lumberjack), overriding the APIC_LOG_FILE env var and the
	// observability.logs.file config block. Set via WithLogFile.
	LogFile *obsx.LogFileConfig
	// Prometheus, when non-nil, forces the authenticated /metrics
	// endpoint on with this provider config, overriding
	// observability.metrics.enabled. Set via WithPrometheus.
	Prometheus *promx.Config

	// Tracing, when non-nil, overrides observability.tracing.enabled: it
	// turns W3C trace-context propagation (traceparent/tracestate) on or off
	// regardless of the config block. Set via WithTracing.
	Tracing *bool
	// CorrelationHeader, when non-nil, overrides the correlation-ID header
	// name (both the inbound/outbound header and the log token), taking
	// priority over the APIC_CORRELATION_HEADER env var and the
	// observability.tracing.correlation_header config. An empty string means
	// the default (X-Correlation-ID). Set via WithCorrelation.
	CorrelationHeader *string

	// Impl is the business-logic implementation of the generated HTTP
	// ServerInterface. Embed apic.UnimplementedServer and override only
	// the methods you need. Nil uses apic.UnimplementedServer{}.
	Impl apic.ServerInterface
	// WSImpl is the business-logic implementation of the generated
	// WebSocket interface. Nil uses genws.UnimplementedWSServer{}.
	WSImpl genws.WSServerInterface
	// MCPImpl is the business-logic implementation of the generated MCP
	// tool interface. Embed genmcp.UnimplementedMCPServer and override only
	// the tools you implement. Nil uses genmcp.UnimplementedMCPServer{}.
	// Register is called unconditionally on startup so SetToolBuckets and
	// SetToolRoles (per-tool rate limits and RBAC) are always installed.
	MCPImpl genmcp.MCPServerInterface

	// AuthAPIKey / AuthJWT override the default credential verifiers. Use
	// AuthJWT to swap the built-in HS256 gate for RS256/ES256/JWKS or an
	// OIDC introspection call (e.g. an HSM-signed RS256 token verified
	// against the signer's public key). Nil keeps the built-in gate.
	AuthAPIKey func(*http.Request) error
	AuthJWT    func(*http.Request) error
	// AuthMTLS enforces deployment-specific mTLS issuer-label policy
	// (PIV/CAC/custom) AFTER securex.VerifyMTLS accepts the request. When
	// the spec declares any mtls route with supported_issuers, Serve
	// refuses to start unless this is wired; IssuerCNVerifier is a ready
	// default the thin entrypoint installs.
	AuthMTLS func(*http.Request, securex.MTLSPolicy) error

	// GetCertificate, when set, supplies the TLS server certificate at
	// handshake time instead of loading a PEM keypair from disk. Wire it
	// to signerx.GetCertificateForServer so the private key lives in an
	// HSM/KMS and never enters the process as raw bytes (NIST SC-12).
	GetCertificate func(*tls.ClientHelloInfo) (*tls.Certificate, error)

	// ExtraRoutes registers application-specific HTTP routes on the SAME mux
	// as the generated API, after the generated routes are registered. Use it
	// for bespoke endpoints that are not part of the apic spec — webhooks
	// with signature auth, reverse proxies, or a hand-wired sub-API — so a
	// service can adopt server.Serve without forking it. These routes share
	// the generated httpx pipeline (body limits, security headers, CORS,
	// per-IP rate limit) but are NOT covered by the generated per-route auth:
	// each handler MUST enforce its own authentication. Patterns must not
	// collide with a generated route (http.ServeMux panics on duplicates).
	ExtraRoutes func(mux *http.ServeMux)

	// InsecureHTTP opts the listener OUT of TLS and serves plain HTTP. It
	// exists for deployments that terminate TLS upstream (ingress/mesh) and
	// hand the process plaintext on a trusted network hop. This is the
	// code-level equivalent of the config opt-in server.tls.mode:"off";
	// either one enables it. It is OFF by default and must be set
	// explicitly — with neither opt-in set, Serve still refuses to boot
	// without a TLS cert, so plaintext is never served by accident. When
	// enabled, Serve logs a one-time warning; terminate TLS upstream.
	InsecureHTTP bool
}

Options configures the generated server. The zero value is valid: it serves the generated UnimplementedServer (501 for un-overridden routes; working WebAuthn ceremonies), the built-in HS256 JWT / HMAC API-key gates, and a PEM-loaded TLS certificate. Override any concern via the With* functions.

Jump to

Keyboard shortcuts

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