Documentation
¶
Index ¶
- Constants
- Variables
- func AuthenticationCLIFlags() []cli.Flag
- func CORSMiddleware(opts CORSOptions, handler http.Handler) http.Handler
- func CallWithRecover(ctx context.Context, fn func(ctx context.Context) error) (outErr error)
- func Close(name string, c io.Closer, outErr *error)
- func ContextWithFeatureFlags(ctx context.Context, flags map[string]bool) context.Context
- func FeatureIsEnabled(ctx context.Context, flag string, defaultState bool) bool
- func GetLogMetadata(ctx context.Context) map[string]any
- func HTTPErrorFromResponse(res *http.Response) error
- func HTTPErrorHandlerFunc(fn func(http.ResponseWriter, *http.Request) error) http.HandlerFunc
- func InvalidArgumentf(argument string, format string, a ...any) error
- func IsHTTPErrorWithStatus(err error, status int) bool
- func IsTwirpErrorCode(err error, code twirp.ErrorCode) bool
- func ListenAndServeContext(ctx context.Context, server *http.Server, shutdownTimeout time.Duration, ...) error
- func LogMetadataMiddleware(next http.Handler) http.Handler
- func LoggingHooks(logger *slog.Logger) *twirp.ServerHooks
- func MarshalFile(path string, o any) (outErr error)
- func NewHTTPClient(timeout time.Duration, opts ...HTTPClientOption) *http.Client
- func NewTwirpMetricsHooks(opts ...TwirpMetricOptionFunc) (*twirp.ServerHooks, error)
- func RHandleFunc(fn func(http.ResponseWriter, *http.Request, httprouter.Params) error) httprouter.Handledeprecated
- func SafeClose(logger *slog.Logger, name string, c io.Closer)deprecated
- func ScopePrefixRegexp(prefix string) *regexp.Regexp
- func SetAuthInfo(ctx context.Context, info *AuthInfo) context.Context
- func SetLogMetadata(ctx context.Context, key string, value any)
- func SetUpLogger(logLevel string, w io.Writer) *slog.Logger
- func TwirpErrorToHTTPStatusCode(err error) int
- func UnmarshalFile(path string, o any) (outErr error)
- func UnmarshalHTTPResource(resURL string, o any) (outErr error)
- func WithLogMetadata(ctx context.Context) context.Context
- type APIServer
- type APIServerOption
- type APIServiceHandler
- type AuthInfo
- type AuthInfoParser
- type AuthenticationConfig
- type AuthenticationSettings
- type BackoffFunction
- type CORSOptions
- type Cleaner
- type ErrGroup
- type ErrPanicRecovered
- type GracefulShutdown
- func (gs *GracefulShutdown) CancelOnQuit(ctx context.Context) context.Context
- func (gs *GracefulShutdown) CancelOnStop(ctx context.Context) context.Context
- func (gs *GracefulShutdown) ShouldQuit() <-chan struct{}
- func (gs *GracefulShutdown) ShouldStop() <-chan struct{}
- func (gs *GracefulShutdown) Stop()
- type HTTPClientInstrumentation
- type HTTPClientOption
- func DialTimeout(d time.Duration) HTTPClientOption
- func IdleConnections(maxIdle int, maxIdlePerHost int, idleConnTimeout time.Duration) HTTPClientOption
- func LongpollClient() HTTPClientOption
- func MaxConnectionsPerHost(n int) HTTPClientOption
- func ResponseHeaderTimeout(d time.Duration) HTTPClientOption
- func TLSHandshakeTimeout(d time.Duration) HTTPClientOption
- func WithTokenSource(source oauth2.TokenSource) HTTPClientOption
- type HTTPClientOptions
- type HTTPError
- type HealthServer
- type JWTAuthInfoParser
- func NewJWKSAuthInfoParser(ctx context.Context, jwksUrl string, opts JWTAuthInfoParserOptions) (*JWTAuthInfoParser, error)
- func NewJWTAuthInfoParser(ctx context.Context, keyfunc jwt.Keyfunc, opts JWTAuthInfoParserOptions) *JWTAuthInfoParser
- func NewStaticAuthInfoParser(ctx context.Context, key ecdsa.PublicKey, opts JWTAuthInfoParserOptions) *JWTAuthInfoParser
- func (p *JWTAuthInfoParser) AuthInfoFromHeader(authorization string) (*AuthInfo, error)
- func (p *JWTAuthInfoParser) AuthInfoFromToken(token string) (*AuthInfo, error)
- func (p *JWTAuthInfoParser) Valid(c jwt.Claims) error
- func (p *JWTAuthInfoParser) ValidateTokenWithClaims(token string, claims jwt.Claims) (*jwt.Token, error)
- type JWTAuthInfoParserOptions
- type JWTClaims
- type ListenAndServeOption
- type ListenAndServeOptions
- type MetricsHelper
- func (h *MetricsHelper) Counter(o *prometheus.Counter, opts prometheus.CounterOpts)
- func (h *MetricsHelper) CounterVec(o **prometheus.CounterVec, opts prometheus.CounterOpts, labels []string)
- func (h *MetricsHelper) Err() error
- func (h *MetricsHelper) Gauge(o *prometheus.Gauge, opts prometheus.GaugeOpts)
- func (h *MetricsHelper) GaugeVec(o **prometheus.GaugeVec, opts prometheus.GaugeOpts, labels []string)
- func (h *MetricsHelper) Histogram(o *prometheus.Histogram, opts prometheus.HistogramOpts)
- func (h *MetricsHelper) HistogramVec(o **prometheus.HistogramVec, opts prometheus.HistogramOpts, labels []string)
- type OpenIDConnectConfig
- type ReadyFunc
- type ServiceAuth
- type ServiceOptions
- type TwirpMetricOptionFunc
- type TwirpMetricsOptions
- type Vault
Constants ¶
const ( DialTimeoutInternal = 1 * time.Second DialTimeoutExternal = 5 * time.Second DialTimeoutSlow = 10 * time.Second )
const ( // LogKeyLogLevel is the log level that an application was configured // with. LogKeyLogLevel = "log_level" // LogKeyError is an error message. LogKeyError = "err" // LogKeyErrorCode is an error code. LogKeyErrorCode = "err_code" // LogKeyErrorMeta is a JSON object with error metadata. LogKeyErrorMeta = "err_meta" // LogKeyCountMetric was planned to be used to increment a given metric // when used. TODO: not implemented yet, should it be removed? LogKeyCountMetric = "count_metric" // LogKeyDocumentUUID is the UUID of a document. LogKeyDocumentUUID = "document_uuid" // LogKeyDocumentType is the type of a document. LogKeyDocumentType = "document_type" // LogKeyDocumenTitle is the title of a document. LogKeyDocumentTitle = "document_title" // LogKeyDocumentVersion is the version of a document. LogKeyDocumentVersion = "document_version" // LogKeyDocumentStatus is the status of a document. LogKeyDocumentStatus = "document_status" // LogKeyDocumentStatus is the id of a document status. LogKeyDocumentStatusID = "document_status_id" // LogKeyTransaction is the name of a transaction, usually used to // identify a transaction that has failed. LogKeyTransaction = "transaction" // LogKeyOCSource is used to identify a source document from OC by UUID. LogKeyOCSource = "oc_source" // LogKeyOCVersion is the version of the OC document. LogKeyOCVersion = "oc_version" // LogKeyOCEvent is the type of an OC event- or content-log event. LogKeyOCEvent = "oc_event" // LogKeyChannel identifies a notification channel. LogKeyChannel = "channel" // LogKeyMessage can be used to log a unexpected message. LogKeyMessage = "message" // LogKeyDelay can be used to communicate the delay when logging // information about retry attempts and backoff delays. LogKeyDelay = "delay" // LogKeyRetries can be used to communicate a retry attempt counter. LogKeyAttempts = "attempts" // LogKeyBucket is used to log a S3 bucket name. LogKeyBucket = "bucket" // LogKeyObjectKey is used to log a S3 object key. LogKeyObjectKey = "object_key" // LogKeyComponent is used to communicate what application subcomponent // the log entry is from. LogKeyComponent = "component" // LogKeyCount is used to communicate a count. LogKeyCount = "count" // LogKeyEventID is the ID of an event. LogKeyEventID = "event_id" // LogKeyEventType is the type of an event. LogKeyEventType = "event_type" // LogKeyJobLock is the name of a job lock. LogKeyJobLock = "job_lock" // LogKeyJobLockID is the ID of a job lock. LogKeyJobLockID = "job_lock_id" // LogKeyState is the name of a state, like "held", "lost" or "accepted". LogKeyState = "state" // LogKeyIndex is the name of a search index, like an Open Search index. LogKeyIndex = "index" // LogKeyRoute is used to name a route or path. LogKeyRoute = "route" // LogKeyService is used to specify an RPC service. LogKeyService = "service" // LogKeyMethod is used to specify an RPC method. LogKeyMethod = "method" // LogKeySubject is the sub of an authenticated client. LogKeySubject = "sub" // LogKeyScopes are the scopes of the authenticated client. LogKeyScopes = "scopes" // LogKeyStatusCode is the HTTP status code used for a response. LogKeyStatusCode = "status_code" // LogKeyName is the name of a resource. LogKeyName = "name" // LogKeyAlertCode is a code used to flag that something needs the // attention of a human operator. LogKeyAlertCode = "alert_code" )
Log attribute keys used throughout the application.
const ( EnvServiceAccountToken = "SERVICE_ACCOUNT_TOKEN" DefaultServiceAccountTokenPath = "/var/run/secrets/kubernetes.io/serviceaccount/token" EnvVaultAuthRole = "VAULT_AUTH_ROLE" DefaultAuthRole = "deploy" )
Variables ¶
var ( ErrGracefulStop = errors.New("stop requested") ErrGracefulQuit = errors.New("quit requested") )
var ErrNoAuthorization = errors.New("no authorization provided")
ErrNoAuthorization is used to communicate that authorization was completely missing, rather than being invalid, expired, or malformed.
Functions ¶
func AuthenticationCLIFlags ¶ added in v0.13.5
AuthenticationCLIFlags returns all the CLI flags that are needed to later call AuthenticationConfigFromCLI with the resulting cli.Context.
func CORSMiddleware ¶ added in v0.11.0
func CORSMiddleware(opts CORSOptions, handler http.Handler) http.Handler
func CallWithRecover ¶ added in v0.22.0
func Close ¶ added in v0.17.4
Close a resource and joins the error to the outError if the close fails. Will ignore os.ErrClosed so it's safe to use together with "manual" closing of files.
func ContextWithFeatureFlags ¶ added in v0.23.5
ContextWithFeatureFlags creates a context with the specified context flags set. If the context already has feature flags set they will be preserved as is unless overridden by the new flags.
func FeatureIsEnabled ¶ added in v0.23.5
FeatureIsEnabled checks the state of a feature flag.
func GetLogMetadata ¶ added in v0.5.0
GetLogMetadata returns the log metatada map for the context.
func HTTPErrorFromResponse ¶
HTTPErrorFromResponse creates a HTTPError from a response struct. This will consume and create a copy of the response body, so don't use it in a scenario where you expect really large error response bodies.
If we fail to copy the response body the error will be joined with the HTTPError.
func HTTPErrorHandlerFunc ¶ added in v0.14.0
func HTTPErrorHandlerFunc( fn func(http.ResponseWriter, *http.Request) error, ) http.HandlerFunc
HTTPErrorHandlerFunc creates a http.HandlerFunc from a function that can return an error. If the error is a HTTPError the information it carries will be used for the error response. Otherwise it will be treated as a internal server error and the error message will be sent as the response.
func InvalidArgumentf ¶ added in v0.17.10
InvalidArgumentf creates a invaldid argument error with a formatted message.
func IsHTTPErrorWithStatus ¶
IsHTTPErrorWithStatus checks if the error (or any error in its tree) is a HTTP error with the given status code.
func IsTwirpErrorCode ¶ added in v0.4.0
IsTwirpErrorCode checks if any error in the tree is a twirp.Error with the given error code.
func ListenAndServeContext ¶
func ListenAndServeContext( ctx context.Context, server *http.Server, shutdownTimeout time.Duration, opts ...ListenAndServeOption, ) error
ListenAndServeContext will call ListenAndServe() for the provided server and then Shutdown() if the context is cancelled.
Check `errors.Is(err, http.ErrServerClosed)` to differentiate between a graceful server close and other errors.
func LogMetadataMiddleware ¶ added in v0.9.6
LogMetadataMiddleware wraps an http.Handler with a middleware that adds a log metadata map to the request context.
func LoggingHooks ¶ added in v0.5.0
func LoggingHooks( logger *slog.Logger, ) *twirp.ServerHooks
LoggingHooks creaes a twirp.ServerHooks that will set log metadata for the twirp service and method name, and log error responses.
func MarshalFile ¶ added in v0.8.2
MarshalToFile is a utility function for marshalling a data structore to JSON and write it to a fil. The JSON will be pretty printed.
func NewHTTPClient ¶ added in v0.21.0
func NewHTTPClient( timeout time.Duration, opts ...HTTPClientOption, ) *http.Client
NewHTTPClient returns a http.Client configured with timeouts and connection limits. The default request timeout, including time for response read is 10 seconds. Use the option functions to customise.
func NewTwirpMetricsHooks ¶ added in v0.4.0
func NewTwirpMetricsHooks(opts ...TwirpMetricOptionFunc) (*twirp.ServerHooks, error)
NewTwirpMetricsHooks creates new twirp hooks enabling prometheus metrics.
func RHandleFunc
deprecated
func RHandleFunc( fn func(http.ResponseWriter, *http.Request, httprouter.Params) error, ) httprouter.Handle
RHandleFunc creates a httprouter.Handle from a function that can return an error. If the error is a HTTPError the information it carries will be used for the error response. Otherwise it will be treated as a internal server eror and the error message will be sent as the response.
Deprecated: use the standard library muxer and HTTPErrorHandlerFunc instead.
func ScopePrefixRegexp ¶ added in v0.12.0
func SetAuthInfo ¶ added in v0.6.0
SetAuthInfo creates a child context with the given authentication information.
func SetLogMetadata ¶ added in v0.5.0
SetLogMetadata sets a log metadata value on the context if it has a log metadata map.
func SetUpLogger ¶
SetUpLogger creates a default JSON logger and sets it as the global logger.
func TwirpErrorToHTTPStatusCode ¶ added in v0.8.4
TwirpErrorToHTTPStatusCode returns the HTTP status code for the given error. If the error is nil 200 will be returned, if the error isn't a twirp.Error 500 will be returned.
func UnmarshalFile ¶
UnmarshalFile is a utility function for reading and unmarshalling a file containing JSON. The parsing will be strict and disallow unknown fields.
func UnmarshalHTTPResource ¶
UnmarshalHTTPResource is a utility function for reading and unmarshalling a HTTP resource. Uses the default HTTP client.
Types ¶
type APIServer ¶ added in v0.14.0
type APIServer struct {
Mux *http.ServeMux
Health *HealthServer
CORS *CORSOptions
// contains filtered or unexported fields
}
func NewAPIServer ¶ added in v0.14.0
func NewTestAPIServer ¶ added in v0.17.0
func (*APIServer) AliveEndpoint ¶ added in v0.14.0
func (*APIServer) ListenAndServe ¶ added in v0.14.0
func (*APIServer) RegisterAPI ¶ added in v0.14.0
func (s *APIServer) RegisterAPI( api APIServiceHandler, opt ServiceOptions, )
func (*APIServer) RegisterAPIs ¶ added in v0.21.4
func (s *APIServer) RegisterAPIs( opt ServiceOptions, apis ...APIServiceHandler, )
type APIServerOption ¶ added in v0.17.13
type APIServerOption func(s *APIServer)
func APIServerCORSHosts ¶ added in v0.17.13
func APIServerCORSHosts(hosts ...string) APIServerOption
func APIServerTLS ¶ added in v0.23.6
func APIServerTLS(addr string, certFile string, keyFile string) APIServerOption
type APIServiceHandler ¶ added in v0.14.0
type AuthInfo ¶ added in v0.6.0
AuthInfo is used to add authentication information to a request context.
func GetAuthInfo ¶ added in v0.6.0
GetAuthInfo returns the authentication information for the given context.
type AuthInfoParser ¶ added in v0.12.0
type AuthInfoParser interface {
// AuthInfoFromHeader extracts the AuthInfo from a HTTP Authorization
// header, then validates the bearer token. Return ErrNoAuthorization
// if no authorization information was provided.
AuthInfoFromHeader(authorization string) (*AuthInfo, error)
// AuthInfoFromToken validates a bearer token and returns the AuthInfo.
// Useful when we have already extracted the token from header and/or
// query parameter.
AuthInfoFromToken(token string) (*AuthInfo, error)
// ValidateTokenWithClaims validates a bearer token and returns the raw token
// object. Useful if you need to do custom claims deserialization.
ValidateTokenWithClaims(token string, claims jwt.Claims) (*jwt.Token, error)
}
type AuthenticationConfig ¶ added in v0.13.0
type AuthenticationConfig struct {
OIDCConfig *OpenIDConnectConfig
TokenSource oauth2.TokenSource
AuthParser *JWTAuthInfoParser
// contains filtered or unexported fields
}
func AuthenticationConfigFromCLI ¶ added in v0.13.0
func AuthenticationConfigFromSettings ¶ added in v0.20.4
func AuthenticationConfigFromSettings( ctx context.Context, settings AuthenticationSettings, scopes []string, ) (*AuthenticationConfig, error)
func (*AuthenticationConfig) NewTokenSource ¶ added in v0.13.6
func (conf *AuthenticationConfig) NewTokenSource( ctx context.Context, scopes []string, ) (oauth2.TokenSource, error)
type AuthenticationSettings ¶ added in v0.20.4
type BackoffFunction ¶ added in v0.14.0
func StaticBackoff ¶ added in v0.14.0
func StaticBackoff(wait time.Duration) BackoffFunction
type CORSOptions ¶ added in v0.11.0
type ErrGroup ¶ added in v0.14.0
type ErrGroup struct {
// contains filtered or unexported fields
}
ErrGroup is meant to be used when we run "top level" subsystems in a service. If a task panics it will be handled as a ErrPanicRecovered error.
func NewErrGroup ¶ added in v0.14.0
func (*ErrGroup) GoWithRetries ¶ added in v0.14.0
func (eg *ErrGroup) GoWithRetries( task string, maxRetries int, backoff BackoffFunction, resetAfter time.Duration, fn func(ctx context.Context) error, )
GoWithRetries runs a task in a retry loop. The retry counter will reset to zero if more time than `resetAfter` has passed since the last error. This is used to avoid creeping up on a retry limit over long periods of time.
type ErrPanicRecovered ¶ added in v0.22.0
type ErrPanicRecovered struct {
PanicValue any
}
func (ErrPanicRecovered) Error ¶ added in v0.22.0
func (err ErrPanicRecovered) Error() string
type GracefulShutdown ¶ added in v0.4.0
type GracefulShutdown struct {
// contains filtered or unexported fields
}
GracefulShutdown is a helper that can be used to listen for SIGINT and SIGTERM to gracefully shut down your application.
SIGTERM will trigger a stop, followed by quit after the specified timeout. SIGINT will trigger a immediate quit.
func NewGracefulShutdown ¶ added in v0.4.0
func NewGracefulShutdown(logger *slog.Logger, timeout time.Duration) *GracefulShutdown
NewGracefulShutdown creates a new GracefulShutdown that will wait for `timeout` between "stop" and "quit".
func NewManualGracefulShutdown ¶ added in v0.9.1
func NewManualGracefulShutdown(logger *slog.Logger, timeout time.Duration) *GracefulShutdown
NewManualGracefulShutdown creates a GracefulShutdown instance that doesn't listen to OS signals.
func (*GracefulShutdown) CancelOnQuit ¶ added in v0.4.0
func (gs *GracefulShutdown) CancelOnQuit(ctx context.Context) context.Context
CancelOnQuit returns a child context that will be cancelled when quit is triggered.
func (*GracefulShutdown) CancelOnStop ¶ added in v0.4.0
func (gs *GracefulShutdown) CancelOnStop(ctx context.Context) context.Context
CancelOnStop returns a child context that will be cancelled when stop is triggered.
func (*GracefulShutdown) ShouldQuit ¶ added in v0.4.0
func (gs *GracefulShutdown) ShouldQuit() <-chan struct{}
ShouldQuit returns a channel that will be closed when quit is triggered.
func (*GracefulShutdown) ShouldStop ¶ added in v0.4.0
func (gs *GracefulShutdown) ShouldStop() <-chan struct{}
ShouldStop returns a channel that will be closed when stop is triggered.
func (*GracefulShutdown) Stop ¶ added in v0.4.0
func (gs *GracefulShutdown) Stop()
Stop triggers a stop, which will trigger quit after the configured timeout.
type HTTPClientInstrumentation ¶ added in v0.4.0
type HTTPClientInstrumentation struct {
// contains filtered or unexported fields
}
HTTPClientInstrumentation provides a way to instrument HTTP clients.
func NewHTTPClientIntrumentation ¶ added in v0.4.0
func NewHTTPClientIntrumentation( registerer prometheus.Registerer, ) (*HTTPClientInstrumentation, error)
NewHTTPClientIntrumentation registers a set of HTTP client metrics with the provided registerer.
func (*HTTPClientInstrumentation) Client ¶ added in v0.4.0
func (ci *HTTPClientInstrumentation) Client(name string, client *http.Client) error
Client instruments the HTTP client transport with the standard promhttp metrics. The client_requests_total, client_in_flight_requests, and client_request_duration_seconds metrics will be labelled with the client name.
type HTTPClientOption ¶ added in v0.21.0
type HTTPClientOption func(opts *HTTPClientOptions)
func DialTimeout ¶ added in v0.21.0
func DialTimeout(d time.Duration) HTTPClientOption
func IdleConnections ¶ added in v0.21.0
func IdleConnections( maxIdle int, maxIdlePerHost int, idleConnTimeout time.Duration, ) HTTPClientOption
func LongpollClient ¶ added in v0.21.0
func LongpollClient() HTTPClientOption
LongpollClient is syntactic sugar for setting the response header timeout to 0 (no timeout), can be used to communicate intent.
func MaxConnectionsPerHost ¶ added in v0.21.0
func MaxConnectionsPerHost(n int) HTTPClientOption
func ResponseHeaderTimeout ¶ added in v0.21.0
func ResponseHeaderTimeout(d time.Duration) HTTPClientOption
func TLSHandshakeTimeout ¶ added in v0.21.0
func TLSHandshakeTimeout(d time.Duration) HTTPClientOption
func WithTokenSource ¶ added in v0.21.0
func WithTokenSource(source oauth2.TokenSource) HTTPClientOption
Wraps the client transport with an oauth2.Transport.
type HTTPClientOptions ¶ added in v0.21.0
type HTTPClientOptions struct {
// contains filtered or unexported fields
}
type HTTPError ¶
HTTPError can be used to describe a non-OK response. Either as an error value in a client that got an error response from a server, or in a server implementation to communicate what the error response to a client should be.
func HTTPErrorf ¶
HTTPErrorf creates a HTTPError using a format string.
func NewHTTPError ¶
NewHTTPError creates a new HTTPError with the given status code and response message.
type HealthServer ¶
type HealthServer struct {
// contains filtered or unexported fields
}
HealthServer exposes health endpoints, metrics, and PPROF endpoints.
A HealthServer should never be publicly exposed, as that both could expose sensitive information and could be used to DDOS your application.
Example output for a request to `GET /health/ready`:
{
"api_liveness": {
"ok": false,
"error": "api liveness endpoint returned non-ok status: 404 Not Found"
},
"postgres": {
"ok": true
},
"s3": {
"ok": true
}
}
func NewHealthServer ¶
func NewHealthServer(logger *slog.Logger, addr string) *HealthServer
NewHealthServer creates a new health server that will listen to the provided address.
func NewTestHealthServer ¶ added in v0.9.3
func NewTestHealthServer(logger *slog.Logger) *HealthServer
func (*HealthServer) AddReadyFunction ¶
func (s *HealthServer) AddReadyFunction(name string, fn ReadyFunc)
AddReadyFunction adds a function that will be called when a client requests "/health/ready".
func (*HealthServer) Addr ¶ added in v0.17.0
func (s *HealthServer) Addr() string
func (*HealthServer) ListenAndServe ¶
func (s *HealthServer) ListenAndServe(ctx context.Context) error
ListenAndServe starts the health server, shutting it down if the context gets cancelled.
type JWTAuthInfoParser ¶ added in v0.16.0
type JWTAuthInfoParser struct {
// contains filtered or unexported fields
}
func NewJWKSAuthInfoParser ¶ added in v0.12.0
func NewJWKSAuthInfoParser(ctx context.Context, jwksUrl string, opts JWTAuthInfoParserOptions) (*JWTAuthInfoParser, error)
func NewJWTAuthInfoParser ¶ added in v0.20.2
func NewJWTAuthInfoParser( ctx context.Context, keyfunc jwt.Keyfunc, opts JWTAuthInfoParserOptions, ) *JWTAuthInfoParser
func NewStaticAuthInfoParser ¶ added in v0.12.0
func NewStaticAuthInfoParser(ctx context.Context, key ecdsa.PublicKey, opts JWTAuthInfoParserOptions) *JWTAuthInfoParser
func (*JWTAuthInfoParser) AuthInfoFromHeader ¶ added in v0.16.0
func (p *JWTAuthInfoParser) AuthInfoFromHeader(authorization string) (*AuthInfo, error)
func (*JWTAuthInfoParser) AuthInfoFromToken ¶ added in v0.17.9
func (p *JWTAuthInfoParser) AuthInfoFromToken(token string) (*AuthInfo, error)
func (*JWTAuthInfoParser) Valid ¶ added in v0.16.0
func (p *JWTAuthInfoParser) Valid(c jwt.Claims) error
Valid validates the jwt.RegisteredClaims.
func (*JWTAuthInfoParser) ValidateTokenWithClaims ¶ added in v0.17.9
type JWTAuthInfoParserOptions ¶ added in v0.16.0
type JWTClaims ¶ added in v0.6.0
type JWTClaims struct {
jwt.RegisteredClaims
OriginalSub string `json:"-"`
Name string `json:"sub_name"`
Scope string `json:"scope"`
AuthorizedParty string `json:"azp"`
ClientID string `json:"client_id"`
Units []string `json:"units,omitempty"`
Org string `json:"org"`
}
JWTClaims defines the claims that the elephant services understand.
func (JWTClaims) HasAnyScope ¶ added in v0.6.0
HasScope returns true if the Scope claim contains any of the named scopes.
type ListenAndServeOption ¶ added in v0.23.6
type ListenAndServeOption func(s *http.Server, o *ListenAndServeOptions)
func ListenAndServeTLS ¶ added in v0.23.6
func ListenAndServeTLS(certFile string, keyFile string) ListenAndServeOption
ListenAndServeTLS configures the server to use TLS.
type ListenAndServeOptions ¶ added in v0.23.6
type ListenAndServeOptions struct {
// contains filtered or unexported fields
}
type MetricsHelper ¶ added in v0.23.2
type MetricsHelper struct {
// contains filtered or unexported fields
}
func NewMetricsHelper ¶ added in v0.23.2
func NewMetricsHelper(reg prometheus.Registerer) *MetricsHelper
func (*MetricsHelper) Counter ¶ added in v0.23.2
func (h *MetricsHelper) Counter( o *prometheus.Counter, opts prometheus.CounterOpts, )
func (*MetricsHelper) CounterVec ¶ added in v0.23.2
func (h *MetricsHelper) CounterVec( o **prometheus.CounterVec, opts prometheus.CounterOpts, labels []string, )
func (*MetricsHelper) Err ¶ added in v0.23.2
func (h *MetricsHelper) Err() error
func (*MetricsHelper) Gauge ¶ added in v0.23.2
func (h *MetricsHelper) Gauge( o *prometheus.Gauge, opts prometheus.GaugeOpts, )
func (*MetricsHelper) GaugeVec ¶ added in v0.23.2
func (h *MetricsHelper) GaugeVec( o **prometheus.GaugeVec, opts prometheus.GaugeOpts, labels []string, )
func (*MetricsHelper) Histogram ¶ added in v0.23.3
func (h *MetricsHelper) Histogram( o *prometheus.Histogram, opts prometheus.HistogramOpts, )
func (*MetricsHelper) HistogramVec ¶ added in v0.23.3
func (h *MetricsHelper) HistogramVec( o **prometheus.HistogramVec, opts prometheus.HistogramOpts, labels []string, )
type OpenIDConnectConfig ¶ added in v0.13.0
type OpenIDConnectConfig struct {
Issuer string `json:"issuer"`
AuthorizationEndpoint string `json:"authorization_endpoint"`
TokenEndpoint string `json:"token_endpoint"`
IntrospectionEndpoint string `json:"introspection_endpoint"`
UserinfoEndpoint string `json:"userinfo_endpoint"`
EndSessionEndpoint string `json:"end_session_endpoint"`
FrontchannelLogoutSessionSupported bool `json:"frontchannel_logout_session_supported"`
FrontchannelLogoutSupported bool `json:"frontchannel_logout_supported"`
JwksURI string `json:"jwks_uri"`
CheckSessionIframe string `json:"check_session_iframe"`
GrantTypesSupported []string `json:"grant_types_supported"`
AcrValuesSupported []string `json:"acr_values_supported"`
ResponseTypesSupported []string `json:"response_types_supported"`
SubjectTypesSupported []string `json:"subject_types_supported"`
IDTokenSigningAlgValuesSupported []string `json:"id_token_signing_alg_values_supported"`
IDTokenEncryptionAlgValuesSupported []string `json:"id_token_encryption_alg_values_supported"`
IDTokenEncryptionEncValuesSupported []string `json:"id_token_encryption_enc_values_supported"`
UserinfoSigningAlgValuesSupported []string `json:"userinfo_signing_alg_values_supported"`
UserinfoEncryptionAlgValuesSupported []string `json:"userinfo_encryption_alg_values_supported"`
UserinfoEncryptionEncValuesSupported []string `json:"userinfo_encryption_enc_values_supported"`
RequestObjectSigningAlgValuesSupported []string `json:"request_object_signing_alg_values_supported"`
RequestObjectEncryptionAlgValuesSupported []string `json:"request_object_encryption_alg_values_supported"`
RequestObjectEncryptionEncValuesSupported []string `json:"request_object_encryption_enc_values_supported"`
ResponseModesSupported []string `json:"response_modes_supported"`
RegistrationEndpoint string `json:"registration_endpoint"`
TokenEndpointAuthMethodsSupported []string `json:"token_endpoint_auth_methods_supported"`
TokenEndpointAuthSigningAlgValuesSupported []string `json:"token_endpoint_auth_signing_alg_values_supported"`
IntrospectionEndpointAuthMethodsSupported []string `json:"introspection_endpoint_auth_methods_supported"`
IntrospectionEndpointAuthSigningAlgValuesSupported []string `json:"introspection_endpoint_auth_signing_alg_values_supported"`
AuthorizationSigningAlgValuesSupported []string `json:"authorization_signing_alg_values_supported"`
AuthorizationEncryptionAlgValuesSupported []string `json:"authorization_encryption_alg_values_supported"`
AuthorizationEncryptionEncValuesSupported []string `json:"authorization_encryption_enc_values_supported"`
ClaimsSupported []string `json:"claims_supported"`
ClaimTypesSupported []string `json:"claim_types_supported"`
ClaimsParameterSupported bool `json:"claims_parameter_supported"`
ScopesSupported []string `json:"scopes_supported"`
RequestParameterSupported bool `json:"request_parameter_supported"`
RequestURIParameterSupported bool `json:"request_uri_parameter_supported"`
RequireRequestURIRegistration bool `json:"require_request_uri_registration"`
CodeChallengeMethodsSupported []string `json:"code_challenge_methods_supported"`
TLSClientCertificateBoundAccessTokens bool `json:"tls_client_certificate_bound_access_tokens"`
RevocationEndpoint string `json:"revocation_endpoint"`
RevocationEndpointAuthMethodsSupported []string `json:"revocation_endpoint_auth_methods_supported"`
RevocationEndpointAuthSigningAlgValuesSupported []string `json:"revocation_endpoint_auth_signing_alg_values_supported"`
BackchannelLogoutSupported bool `json:"backchannel_logout_supported"`
BackchannelLogoutSessionSupported bool `json:"backchannel_logout_session_supported"`
DeviceAuthorizationEndpoint string `json:"device_authorization_endpoint"`
BackchannelTokenDeliveryModesSupported []string `json:"backchannel_token_delivery_modes_supported"`
BackchannelAuthenticationEndpoint string `json:"backchannel_authentication_endpoint"`
BackchannelAuthenticationRequestSigningAlgValuesSupported []string `json:"backchannel_authentication_request_signing_alg_values_supported"`
RequirePushedAuthorizationRequests bool `json:"require_pushed_authorization_requests"`
PushedAuthorizationRequestEndpoint string `json:"pushed_authorization_request_endpoint"`
MtlsEndpointAliases map[string]string `json:"mtls_endpoint_aliases"`
AuthorizationResponseIssParameterSupported bool `json:"authorization_response_iss_parameter_supported"`
}
func OpenIDConnectConfigFromURL ¶ added in v0.13.0
func OpenIDConnectConfigFromURL( wellKnown string, ) (*OpenIDConnectConfig, error)
type ReadyFunc ¶
ReadyFunc is a function that will be called to determine if a service is ready to recieve traffic. It should return a descriptive error that helps with debugging if the underlying check fails.
func LivenessReadyCheck ¶ added in v0.6.3
LivenessReadyCheck returns a ReadyFunc that verifies that an endpoint aswers to GET requests with 200 OK.
type ServiceAuth ¶ added in v0.16.0
type ServiceAuth bool
ServiceAuth is used to control behaviour when an unauthorized client makes a call to the service.
const ( // ServiceAuthRequired respond with a Twirp Unauthenticated error for // unauthorized calls. ServiceAuthRequired ServiceAuth = true // ServiceAuthOptional allow unauthorized calls, invalid authorizations // will still result in an error, but calls missing authorization will // be let through to the service implementation. ServiceAuthOptional ServiceAuth = false )
type ServiceOptions ¶ added in v0.14.0
type ServiceOptions struct {
Hooks *twirp.ServerHooks
AuthMiddleware func(
w http.ResponseWriter, r *http.Request, next http.Handler,
) error
// JSONSkipDefaults configures JSON serialization to skip unpopulated or
// default values in JSON responses, which results in smaller responses
// that are easier to read if your messages contain lots of fields that
// may have their default/zero value.
JSONSkipDefaults bool
}
func NewDefaultServiceOptions ¶ added in v0.14.0
func NewDefaultServiceOptions( logger *slog.Logger, parser AuthInfoParser, reg prometheus.Registerer, requireAuth ServiceAuth, ) (ServiceOptions, error)
NewDefaultServiceOptions sets up the standard options for our Twirp services. This sets up authentication, logging and metrics. Apply the options to your Twirp servers using the ServerOptions() method.
func (*ServiceOptions) AddLoggingHooks ¶ added in v0.14.0
func (so *ServiceOptions) AddLoggingHooks( logger *slog.Logger, )
func (*ServiceOptions) AddMetricsHooks ¶ added in v0.15.0
func (so *ServiceOptions) AddMetricsHooks(reg prometheus.Registerer) error
func (*ServiceOptions) ServerOptions ¶ added in v0.16.0
func (so *ServiceOptions) ServerOptions() twirp.ServerOption
ServerOptions returns a ServerOptions function that configures the twirp server according to the set service options.
func (*ServiceOptions) SetAuthInfoValidation ¶ added in v0.16.0
func (so *ServiceOptions) SetAuthInfoValidation( parser AuthInfoParser, requireAuth ServiceAuth, )
type TwirpMetricOptionFunc ¶ added in v0.4.0
type TwirpMetricOptionFunc func(opts *TwirpMetricsOptions)
func WithTwirpMetricsCustomerFunc ¶ added in v0.9.5
func WithTwirpMetricsCustomerFunc(fn func(ctx context.Context) string) TwirpMetricOptionFunc
WithTwirpMetricsCustomerFunc sets a function that can be used to return the customer label value for a context.
func WithTwirpMetricsRegisterer ¶ added in v0.4.0
func WithTwirpMetricsRegisterer(reg prometheus.Registerer) TwirpMetricOptionFunc
WithTwirpMetricsRegisterer uses a custom registerer for Twirp metrics.
func WithTwirpMetricsStaticTestLatency ¶ added in v0.4.0
func WithTwirpMetricsStaticTestLatency(latency time.Duration) TwirpMetricOptionFunc
WithTwirpMetricsStaticTestLatency configures the RPC metrics to report a static duration.
type TwirpMetricsOptions ¶ added in v0.4.0
type TwirpMetricsOptions struct {
// contains filtered or unexported fields
}
type Vault ¶ added in v0.9.0
Vault is a helper for setting up a Vault client, also implements ParameterSource.
func NewVault ¶ added in v0.9.0
NewVault creates a vault client that can be used as a ParameterSource.
func (*Vault) GetParameterValue ¶ added in v0.9.0
GetParameterValue implements ParameterSource.
func (*Vault) KeepAlive ¶ added in v0.9.0
KeepAlive is used to keep the lease on the vault login active, not necessary if you're just reading secrets on startup. Returns an error if the lease is lost or fails to renew. Returns immediately without an error if a token was used to authenticate directly with vault.