gserver

package
v1.0.442 Latest Latest
Warning

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

Go to latest
Published: Oct 9, 2026 License: MIT Imports: 55 Imported by: 8

Documentation

Overview

Package gserver implements a combined gRPC, gRPC-Web and REST server that listens on one or more URLs and multiplexes all three protocols on each listener.

A Server is created with Start from a Config, a dig dependency container and a map of ServiceFactory functions. Each factory builds a Service; a Service that also implements RouteRegistrator gets its REST routes registered, and one that implements GRPCRegistrator gets its gRPC services registered. Plain HTTP/1.1 traffic is routed to the REST router, HTTP/2 "application/grpc" traffic to the gRPC server, and "application/grpc-web+proto" / "application/grpc-web-text" requests are translated to gRPC and their trailers are encoded into the gRPC-Web response body.

Every REST request passes through a fixed middleware chain: rate limiting (optional), correlation ID, request metrics, CORS (optional), identity extraction (roles.IdentityProvider built from Config.IdentityMap), a nested metrics handler that reports the caller role, request logging, authorization (restserver/authz built from Config.Authz), and a readiness check. gRPC and gRPC-Web calls go through the equivalent interceptor chain: panic recovery, correlation ID, logging, rate limiting and, for unary calls, NewRequestValidationUnaryInterceptor before identity extraction. Each listener has one limiter: a limited REST request gets HTTP 429 and a limited call ResourceExhausted, logged and counted like any other response of its protocol; with RateLimit.LogRejections set, a WARNING line adds the limiter key, the socket peer and the forwarding headers.

Minimal usage:

cfg := &gserver.Config{
	ListenURLs: []string{"https://0.0.0.0:8443"},
	Services:   []string{"status"},
	ServerTLS: &gserver.TLSInfo{
		CertFile: "server.pem",
		KeyFile:  "server-key.pem",
	},
}
factories := map[string]gserver.ServiceFactory{
	"status": func(s gserver.GServer) any {
		return func() error { s.AddService(newStatusService(s)); return nil }
	},
}
srv, err := gserver.Start("api", cfg, container, factories)
if err != nil {
	return err
}
defer srv.Close()
<-srv.Err() // or wait for a signal

The container must provide discovery.Discovery and, when Config.IdentityMap enables JWT or DPoP authentication, a jwt.Parser. Config is typically loaded from YAML; see the yaml tags on Config for the field names.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// WarnUnaryRequestLatency is the duration above which a gRPC request
	// (unary or stream) is logged at WARNING level as slow_request. It is a
	// process-global setting read on every request.
	WarnUnaryRequestLatency = 2 * time.Second
)

Functions

func NewRequestValidationUnaryInterceptor added in v0.35.366

func NewRequestValidationUnaryInterceptor() grpc.UnaryServerInterceptor

NewRequestValidationUnaryInterceptor returns a unary interceptor that calls Validate on requests implementing Validator and rejects the call with the returned error. A panic in Validate fails the call with Internal; panics in the handler are left to the interceptors around it. Start installs it after the log and rate-limit interceptors, so invalid requests are logged, counted and limited.

Types

type CORS

type CORS struct {
	// Enabled specifies if the CORS is enabled.
	Enabled *bool `json:"enabled,omitempty" yaml:"enabled,omitempty"`

	// MaxAge indicates how long (in seconds) the results of a preflight request can be cached.
	MaxAge int `json:"max_age,omitempty" yaml:"max_age,omitempty"`

	// AllowedOrigins is a list of origins a cross-domain request can be executed from.
	AllowedOrigins []string `json:"allowed_origins,omitempty" yaml:"allowed_origins,omitempty"`

	// AllowedMethods is a list of methods the client is allowed to use with cross-domain requests.
	AllowedMethods []string `json:"allowed_methods,omitempty" yaml:"allowed_methods,omitempty"`

	// AllowedHeaders is list of non simple headers the client is allowed to use with cross-domain requests.
	AllowedHeaders []string `json:"allowed_headers,omitempty" yaml:"allowed_headers,omitempty"`

	// ExposedHeaders indicates which headers are safe to expose to the API of a CORS API specification.
	ExposedHeaders []string `json:"exposed_headers,omitempty" yaml:"exposed_headers,omitempty"`

	// AllowCredentials indicates whether the request can include user credentials.
	// It requires explicit AllowedOrigins or origin patterns; "*" is rejected.
	AllowCredentials *bool `json:"allow_credentials,omitempty" yaml:"allow_credentials,omitempty"`

	// OptionsPassthrough instructs preflight to let other potential next handlers to process the OPTIONS method.
	OptionsPassthrough *bool `json:"options_pass_through,omitempty" yaml:"options_pass_through,omitempty"`

	// Debug flag adds additional output to debug server side CORS issues.
	Debug *bool `json:"debug,omitempty" yaml:"debug,omitempty"`
}

CORS configures cross-origin handling. When enabled the REST handler is wrapped with github.com/rs/cors; AllowedOrigins, ExposedHeaders and AllowCredentials are also applied to gRPC-Web responses on TLS listeners. Both match origins the same way, including rs/cors origin patterns. Use AllowedOrigins with "*" to allow every origin; an empty list allows none. "*" cannot be combined with AllowCredentials: Start rejects that configuration (see Validate).

For REST, CORS only controls whether a browser may read the response; it is not request or CSRF protection. A REST request from a disallowed origin still reaches its handler and only lacks CORS response headers, and a disallowed preflight gets no allow headers. gRPC-Web rejects a request from a disallowed origin with HTTP 403 before the service is called.

func (*CORS) GetAllowCredentials

func (c *CORS) GetAllowCredentials() bool

GetAllowCredentials returns the AllowCredentials flag; safe on a nil receiver.

func (*CORS) GetDebug

func (c *CORS) GetDebug() bool

GetDebug returns the Debug flag; safe on a nil receiver.

func (*CORS) GetEnabled

func (c *CORS) GetEnabled() bool

GetEnabled returns true when CORS is configured and enabled; safe on a nil receiver.

func (*CORS) GetOptionsPassthrough

func (c *CORS) GetOptionsPassthrough() bool

GetOptionsPassthrough returns the OptionsPassthrough flag; safe on a nil receiver.

func (*CORS) Validate added in v1.0.438

func (c *CORS) Validate() error

Validate returns an error when an enabled CORS block combines the "*" origin with AllowCredentials, which would let every web origin read credentialed responses. A nil or disabled CORS is valid. Start calls it through Config.Validate.

type Config

type Config struct {
	// DebugLogs enables verbose per-request debug logging in the gRPC/HTTP mux.
	DebugLogs bool `json:"debug_logs" yaml:"debug_logs"`

	// Description provides description of the server
	Description string `json:"description,omitempty" yaml:"description,omitempty"`

	// Disabled specifies if the service is disabled
	Disabled bool `json:"disabled,omitempty" yaml:"disabled,omitempty"`

	// ClientURL is the public URL exposed to clients
	ClientURL string `json:"client_url" yaml:"client_url"`

	// ListenURLs is the list of URLs to listen on. Supported schemes are
	// http, https, unix and unixs; a URL without scheme defaults to https when
	// ServerTLS is set. URLs with the same address share one listener.
	ListenURLs []string `json:"listen_urls" yaml:"listen_urls"`

	// ServerTLS provides the TLS config for the server; required for https/unixs URLs.
	ServerTLS *TLSInfo `json:"server_tls,omitempty" yaml:"server_tls,omitempty"`

	// SkipLogPaths if set, specifies a list of paths to not log.
	// this can be used for /v1/status/node or /metrics
	SkipLogPaths []telemetry.LoggerSkipPath `json:"logger_skip_paths,omitempty" yaml:"logger_skip_paths,omitempty"`

	// PromGrpc adds the go-grpc-prometheus unary and stream interceptors.
	PromGrpc bool `json:"prom_grpc" yaml:"prom_grpc"`

	// Services is the list of service names to enable; each must have a
	// ServiceFactory registered in the map passed to Start.
	Services []string `json:"services" yaml:"services"`

	// IdentityMap configures how callers are authenticated and mapped to roles
	// (see gserver/roles). When nil an empty map is used and all callers are guests.
	IdentityMap *roles.IdentityMap `json:"identity_map" yaml:"identity_map"`

	// Authz configures path/role based authorization (see restserver/authz).
	// It is only activated when at least one of Allow, AllowAny or AllowAnyRole is set.
	Authz *authz.Config `json:"authz" yaml:"authz"`

	// CORS contains configuration for CORS.
	CORS *CORS `json:"cors,omitempty" yaml:"cors,omitempty"`

	// RateLimit contains configuration for the rate limiter
	RateLimit *RateLimit `json:"rate_limit,omitempty" yaml:"rate_limit,omitempty"`

	// TrustedProxyCIDRs permits these socket peers to supply forwarding headers.
	// By default, only the socket address is used for client IP and scheme.
	TrustedProxyCIDRs []string `json:"trusted_proxy_cidrs,omitempty" yaml:"trusted_proxy_cidrs,omitempty"`

	// Timeouts bounds HTTP reads, cmux detection and eager TLS handshakes.
	// Zero fields select limits defaults; negative fields disable deadlines.
	// Read does not apply to native gRPC streams, on any listener.
	Timeouts limits.Timeouts `json:"timeouts,omitempty" yaml:"timeouts,omitempty"`

	// MaxRequestBody limits HTTP body bytes, including TLS gRPC/gRPC-Web streams.
	// Zero uses limits.DefaultMaxRequestBody; negative disables the limit.
	// Native gRPC on plain listeners uses MaxRecvMsgSize instead.
	MaxRequestBody int64 `json:"max_request_body,omitempty" yaml:"max_request_body,omitempty"`

	// Timeout settings
	Timeout struct {
		// Request is how long Close waits for in-flight requests to finish
		// before forcing shutdown; default 3s.
		Request time.Duration `json:"request,omitempty" yaml:"request,omitempty"`
	} `json:"timeout" yaml:"timeout"`

	// KeepAlive settings
	KeepAlive KeepAliveCfg `json:"keep_alive" yaml:"keep_alive"`

	// MaxRecvMsgSize sets the maximum gRPC message size a client can send;
	// the MaxRecvMsgSize Option takes precedence when set.
	MaxRecvMsgSize int `json:"max_recv_msg_size,omitempty" yaml:"max_recv_msg_size,omitempty"`

	// MaxSendMsgSize sets the maximum gRPC message size the server can send;
	// the MaxSendMsgSize Option takes precedence when set.
	MaxSendMsgSize int `json:"max_send_msg_size,omitempty" yaml:"max_send_msg_size,omitempty"`

	// HTTPHeaders are static response headers set on every response served
	// by TLS listeners (they are not applied on plain http listeners).
	// While CORS is enabled, Access-Control-* names are rejected (see
	// Validate): the CORS block owns those headers.
	HTTPHeaders map[string]string `json:"http_headers,omitempty" yaml:"http_headers,omitempty"`
}

Config is the server configuration passed to Start. It is usually unmarshalled from YAML/JSON; the yaml and json tags give the field names.

func (*Config) ParseListenURLs

func (c *Config) ParseListenURLs() ([]*url.URL, error)

ParseListenURLs parses ListenURLs into URLs, returning an error for any malformed entry.

func (*Config) Validate added in v1.0.438

func (c *Config) Validate() error

Validate returns an error for a configuration Start cannot serve safely: an invalid TrustedProxyCIDRs entry, an invalid CORS block (see CORS.Validate), an invalid enabled RateLimit block (see RateLimit.Validate) or, while CORS is enabled, an HTTPHeaders entry that would set an Access-Control-* header outside the CORS policy. Start runs the same checks.

type GRPCRegistrator

type GRPCRegistrator interface {
	// RegisterGRPC registers the service implementation on the gRPC server.
	RegisterGRPC(*grpc.Server)
}

GRPCRegistrator is an optional interface a Service implements to expose gRPC services; it is invoked once per gRPC server instance (secure and insecure).

type GServer added in v0.14.0

type GServer interface {
	// Name returns server name
	Name() string
	// Configuration of the server
	Configuration() *Config
	// AddService to the server
	AddService(svc Service)
	// Service returns service by name
	Service(name string) Service
	// IsReady returns true when the server is ready to serve
	IsReady() bool
	// StartedAt returns Time when the server has started
	StartedAt() time.Time
	// ListenURLs is the list of URLs that the server listens on
	ListenURLs() []string
	// Hostname is the hostname
	Hostname() string
	// LocalIP is the local IP4
	LocalIP() string
	// Discovery returns Discovery interface
	Discovery() discovery.Discovery
	// Err returns error channel
	Err() <-chan error
	// Close gracefully shuts down all servers/listeners and stops the TLS
	// certificate reloader.
	// Client requests will be terminated with request timeout.
	// After timeout, enforce remaining requests be closed immediately.
	// The teardown runs once: later or concurrent calls return after it
	// has finished.
	Close()
}

GServer is the server handle passed to ServiceFactory functions and returned by Start. Services use it to register themselves and to query server state; it is safe for concurrent reads after Start returns.

func Start

func Start(
	name string,
	cfg *Config,
	container *dig.Container,
	serviceFactories map[string]ServiceFactory,
	opts ...Option,
) (GServer, error)

Start creates the services from serviceFactories, opens the listeners from cfg.ListenURLs and begins serving in background goroutines, returning the running server. The container must provide discovery.Discovery and, when cfg.IdentityMap enables JWT or DPoP, a jwt.Parser. On error the created services are closed, the opened listeners are closed, the TLS reloader is stopped and the error is returned; on success the caller must eventually call Close. Serve errors are reported on Err.

type KeepAliveCfg

type KeepAliveCfg struct {
	// MinTime is the minimum interval that a client should wait before pinging server.
	MinTime time.Duration `json:"min_time,omitempty" yaml:"min_time,omitempty"`

	// Interval is the frequency of server-to-client ping to check if a connection is alive.
	Interval time.Duration `json:"interval,omitempty" yaml:"interval,omitempty"`

	// Timeout is the additional duration of wait before closing a non-responsive connection, use 0 to disable.
	Timeout time.Duration `json:"timeout,omitempty" yaml:"timeout,omitempty"`
}

KeepAliveCfg configures gRPC keepalive. MinTime sets the enforcement policy; Interval and Timeout are only applied when both are positive. MaxConnectionIdle is always 5 minutes.

type Middleware

type Middleware func(handler http.Handler) http.Handler

Middleware wraps an http.Handler; it is applied by WithMiddleware.

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option customizes a Server created by Start.

func MaxRecvMsgSize added in v0.33.334

func MaxRecvMsgSize(size int) Option

MaxRecvMsgSize sets the maximum gRPC message size a client can send, overriding Config.MaxRecvMsgSize.

func MaxSendMsgSize added in v0.33.334

func MaxSendMsgSize(size int) Option

MaxSendMsgSize sets the maximum gRPC message size the server can send, overriding Config.MaxSendMsgSize.

func WithMiddleware

func WithMiddleware(otherHandler Middleware) Option

WithMiddleware adds an HTTP middleware to the REST handler chain. It runs after the built-in middlewares (identity, authz, logging), closest to the router; multiple middlewares wrap in the order given.

func WithStreamServerInterceptor

func WithStreamServerInterceptor(other grpc.StreamServerInterceptor) Option

WithStreamServerInterceptor appends a gRPC stream interceptor after the built-in chain (logging, correlation, rate limit, identity, authz).

func WithUnaryServerInterceptor

func WithUnaryServerInterceptor(other grpc.UnaryServerInterceptor) Option

WithUnaryServerInterceptor appends a gRPC unary interceptor after the built-in chain (panic recovery, correlation, logging, rate limit, validation, identity, authz).

type RateLimit

type RateLimit struct {
	// Enabled specifies if rate limiting is enabled.
	Enabled *bool `json:"enabled,omitempty" yaml:"enabled,omitempty"`
	// RequestsPerSecond specifies the maximum number of requests per second
	// per client; it is also the burst size. It must be positive when Enabled:
	// with zero, tollbooth admits one request per client and then rejects
	// every later one.
	RequestsPerSecond int `json:"requests_per_second,omitempty" yaml:"requests_per_second,omitempty"`
	// ExpirationTTL specifies how long a client's token bucket is kept before
	// it is recreated with a full burst; zero selects 10 minutes. Negative
	// values and values below one second are rejected, and the TTL should
	// stay long relative to the refill interval.
	ExpirationTTL time.Duration `json:"expiration_ttl,omitempty" yaml:"expiration_ttl,omitempty"`
	// HeadersIPLookups lists the sources used to identify the client, in
	// order: "RemoteAddr", "X-Forwarded-For" or "X-Real-IP" (as spelled by
	// tollbooth; any other name is rejected because tollbooth would ignore it
	// and leave requests unlimited). The default is the trusted client
	// address derived from the socket peer and TrustedProxyCIDRs; a Unix
	// socket peer has none, so its callers are not limited. Explicit header
	// lookups can be spoofed and should be configured only when the
	// deployment guarantees they are overwritten.
	HeadersIPLookups []string `json:"headers_ip_lookups,omitempty" yaml:"headers_ip_lookups,omitempty"`
	// Metods (sic) restricts limiting to the listed HTTP methods, e.g. "GET",
	// "POST"; empty means all methods. tollbooth compares them exactly, so
	// each entry must be a single upper-case HTTP method token (RFC 9110
	// tchar characters only); any other entry is rejected because it would
	// never match and leave every request unlimited.
	Metods []string `json:"metods,omitempty" yaml:"metods,omitempty"`
	// LogRejections, when true, adds a WARNING line for each rejected
	// request with the limiter key (an IPv6 client's /64 prefix, as
	// tollbooth groups it), the socket peer, the User-Agent and the
	// forwarding headers as received. Its correlation ID (ctx) is the
	// X-Correlation-ID of a 429 and the request ID of a gRPC error. It is
	// off by default. Turn it on to check whether a load balancer's client
	// IP is the limiter key, or whether every caller shares one internal
	// peer such as 10.0.x.x; gRPC log lines show no client address.
	LogRejections *bool `json:"log_rejections,omitempty" yaml:"log_rejections,omitempty"`
}

RateLimit configures the per-client token bucket rate limiter (github.com/didip/tollbooth) of each listener. It answers a limited REST request with HTTP 429 and a limited gRPC or gRPC-Web call with ResourceExhausted; both are logged and counted like other responses of their protocol. An enabled block must pass Validate; Start rejects one that does not.

func (*RateLimit) GetEnabled

func (c *RateLimit) GetEnabled() bool

GetEnabled returns true when rate limiting is configured and enabled; safe on a nil receiver.

func (*RateLimit) GetLogRejections added in v1.0.442

func (c *RateLimit) GetLogRejections() bool

GetLogRejections returns true when rejected requests are logged; safe on a nil receiver.

func (*RateLimit) Validate added in v1.0.438

func (c *RateLimit) Validate() error

Validate returns an error when rate limiting is enabled with settings that would not limit as configured: a RequestsPerSecond that is not positive, a negative or sub-second ExpirationTTL, a HeadersIPLookups entry tollbooth does not understand, or a Metods entry that is not an upper-case method name. A nil or disabled RateLimit is valid. Start calls it through Config.Validate.

type RouteRegistrator

type RouteRegistrator interface {
	// RegisterRoute adds the service HTTP handlers to the router.
	RegisterRoute(restserver.Router)
}

RouteRegistrator is an optional interface a Service implements to expose REST endpoints; it is invoked once per listener when the router is built.

type Server

type Server struct {
	// Listeners are the accepted network listeners, one per unique listen
	// address. They are wrappers (accept backoff, TCP keepalive), not the
	// *net.TCPListener or *net.UnixListener values; use Addr and Close.
	Listeners []net.Listener
	// contains filtered or unexported fields
}

Server is the GServer implementation returned by Start. It owns the listeners, the per-listener HTTP and gRPC servers, and the registered services. Use Start to construct it; the zero value is not usable.

Example
sigs := make(chan os.Signal, 2)

// A short temporary directory for the Unix socket (socket paths are
// limited to about 104 bytes), and any free port, so the example cannot
// collide with other tests; a deployment uses fixed addresses.
dir, err := os.MkdirTemp("", "gs")
if err != nil {
	panic("unable to create a socket directory: " + err.Error())
}
defer os.RemoveAll(dir)

cfg := &gserver.Config{
	ListenURLs: []string{"https://127.0.0.1:0", "unix://" + filepath.Join(dir, "gs.sock")},
	Services:   []string{"test"},
	KeepAlive: gserver.KeepAliveCfg{
		MinTime:  time.Second,
		Interval: time.Second,
		Timeout:  time.Second,
	},
	ServerTLS: &gserver.TLSInfo{
		CertFile:      "testdata/test-server.pem",
		KeyFile:       "testdata/test-server-key.pem",
		TrustedCAFile: "testdata/test-server-rootca.pem",
		ClientCAFile:  "testdata/test-server-rootca.pem", // CA bundle for client certificates
	},
	RateLimit: &gserver.RateLimit{
		RequestsPerSecond: 10,
	},
}

c := mockappcontainer.NewBuilder().
	WithJwtParser(nil).
	WithDiscovery(discovery.New()).
	Container()

fact := map[string]gserver.ServiceFactory{
	"test": testServiceFactory,
}
fmt.Println("starting server")
srv, err := gserver.Start("Empty", cfg, c, fact)
if err != nil {
	panic("unable to start the server: " + err.Error())
}

go func() {
	// Send STOP signal after few seconds,
	// in production the service should listen to
	// os.Interrupt, os.Kill, syscall.SIGTERM, syscall.SIGUSR2, syscall.SIGABRT events
	time.Sleep(3 * time.Second)
	fmt.Println("sending syscall.SIGTERM signal")
	sigs <- syscall.SIGTERM
}()

// register for signals, and wait to be shutdown
signal.Notify(sigs, os.Interrupt, syscall.SIGTERM)
// Block until a signal is received.
sig := <-sigs

fmt.Printf("received signal: %v\n", sig)

srv.Close()
fmt.Println("stopped server")
Output:
starting server
sending syscall.SIGTERM signal
received signal: terminated
stopped server

func (*Server) AddService

func (e *Server) AddService(svc Service)

AddService registers svc by its Name, replacing any service with the same name. It must be called from a ServiceFactory, before Start begins serving; the services map is not synchronized.

func (*Server) Close

func (e *Server) Close()

Close gracefully shuts down all servers/listeners. Client requests will be terminated with request timeout. After timeout, enforce remaining requests be closed immediately. It then closes the listeners and stops the TLS certificate reloader. The teardown runs once, so services are closed once; a later or concurrent call returns after the teardown has finished.

func (*Server) Configuration

func (e *Server) Configuration() *Config

Configuration returns a pointer to the server's copy of the Config; mutating it after Start has no effect on already configured listeners.

func (*Server) Discovery

func (e *Server) Discovery() discovery.Discovery

Discovery returns the discovery.Discovery injected from the container; all services are registered with it under the server name after Start.

func (*Server) Err

func (e *Server) Err() <-chan error

Err returns the channel on which listener/serve errors are reported. The channel is buffered and is never closed; errors are dropped once Close begins.

func (*Server) Hostname

func (e *Server) Hostname() string

Hostname is the hostname

func (*Server) IsReady

func (e *Server) IsReady() bool

IsReady returns true when every registered service reports IsReady.

func (*Server) ListenURLs

func (e *Server) ListenURLs() []string

ListenURLs returns the configured Config.ListenURLs (not the resolved listener addresses).

func (*Server) LocalIP

func (e *Server) LocalIP() string

LocalIP returns the local IPv4 address detected at startup, or 127.0.0.1 when it could not be determined.

func (*Server) Name

func (e *Server) Name() string

Name returns server name

func (*Server) Service

func (e *Server) Service(name string) Service

Service returns the registered service with the given name, or nil.

func (*Server) StartedAt

func (e *Server) StartedAt() time.Time

StartedAt returns Time when the server has started

type Service

type Service interface {
	// Name returns the unique service name used as the key in GServer.Service.
	Name() string
	// Close releases the service resources; it is called by Server.Close before
	// the listeners are shut down.
	Close()
	// IsReady indicates that service is ready to serve its end-points
	IsReady() bool
}

Service is a named sub-service hosted by a Server. Services are created by a ServiceFactory and registered with GServer.AddService; a Service may additionally implement RouteRegistrator, GRPCRegistrator or StartSubcriber.

type ServiceFactory

type ServiceFactory func(GServer) any

ServiceFactory builds a Service for the given server. The returned value is passed to dig.Container.Invoke, so it must be a function whose parameters are resolved from the container; the function itself should call GServer.AddService.

type StartSubcriber

type StartSubcriber interface {
	// OnStarted is called when the server started and
	// is ready to serve requests
	OnStarted() error
}

StartSubcriber is an optional interface a Service can implement to be notified once the server has started.

type SwaggerCfg

type SwaggerCfg struct {
	// Enabled allows Swagger
	Enabled bool `json:"enabled" yaml:"enabled"`

	// Files is a map of service name to location
	Files map[string]string `json:"files" yaml:"files"`
}

SwaggerCfg specifies the configuration for Swagger. It is not used by gserver itself and is provided for services that serve Swagger files.

type TLSInfo

type TLSInfo struct {
	// CertFile specifies location of the cert
	CertFile string `json:"cert,omitempty" yaml:"cert,omitempty"`

	// KeyFile specifies location of the key
	KeyFile string `json:"key,omitempty" yaml:"key,omitempty"`

	// TrustedCAFile specifies location of the trusted root CA bundle
	TrustedCAFile string `json:"trusted_ca,omitempty" yaml:"trusted_ca,omitempty"`

	// ClientCAFile specifies location of the CA bundle used to verify client certificates
	ClientCAFile string `json:"client_ca,omitempty" yaml:"client_ca,omitempty"`

	// CRLFile specifies location of the CRL
	CRLFile string `json:"crl,omitempty" yaml:"crl,omitempty"`

	// OCSPFile specifies location of the OCSP response
	OCSPFile string `json:"ocsp,omitempty" yaml:"ocsp,omitempty"`

	// CipherSuites optionally restricts the enabled TLS 1.2 cipher suites, by
	// crypto/tls name. The order is ignored: Go picks the preferred mutually
	// supported suite itself. Names Go lists as insecure and TLS 1.3 suites
	// (not configurable in Go) are rejected.
	CipherSuites []string `json:"cipher_suites,omitempty" yaml:"cipher_suites,omitempty"`

	// ClientCertAuth, when true, requires and verifies a client certificate;
	// otherwise a client certificate is verified only if presented.
	ClientCertAuth *bool `json:"client_cert_auth,omitempty" yaml:"client_cert_auth,omitempty"`
}

TLSInfo is the server TLS configuration. Cert and key files are watched and reloaded by pkg/transport; CRLFile and OCSPFile are currently not used.

func (*TLSInfo) Empty

func (info *TLSInfo) Empty() bool

Empty returns true if the receiver is nil or either CertFile or KeyFile is unset.

func (*TLSInfo) GetClientCertAuth

func (info *TLSInfo) GetClientCertAuth() bool

GetClientCertAuth returns true when ClientCertAuth is set and true.

func (*TLSInfo) String

func (info *TLSInfo) String() string

String returns a loggable summary of the TLS file locations; safe on a nil receiver.

type Validator added in v0.35.366

type Validator interface {
	// Validate returns an error (typically a gRPC status) when the request is invalid.
	Validate(ctx context.Context) error
}

Validator is implemented by request messages that can validate themselves; NewRequestValidationUnaryInterceptor calls it before the handler.

Directories

Path Synopsis
Package credentials implements gRPC transport and per-RPC credentials for porto clients and servers.
Package credentials implements gRPC transport and per-RPC credentials for porto clients and servers.
Package roles maps authenticated callers to porto roles for both HTTP and gRPC requests.
Package roles maps authenticated callers to porto roles for both HTTP and gRPC requests.

Jump to

Keyboard shortcuts

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