Documentation
¶
Overview ¶
///////////////////////////////////////////////////////////////////// David Gurley dmgurley@gmail.com May 2019
//////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////// David Gurley dmgurley@gmail.com June 2018
//////////////////////////////////////////////////////////////////////
Index ¶
- Constants
- Variables
- func SPAHandler(fsys fs.FS) http.Handler
- func SetAllowAllWebsocketOrigins(allow bool)
- func SetAllowedOrigins(origins []string)
- type AccountConnections
- type AccountConnector
- type AccountCredentialsProvider
- type AccountRef
- type FollowOption
- type Response
- type Server
- func (server *Server) AddMessenger(options *messenger.ClientOptions) error
- func (server *Server) FollowAccounts(provider AccountCredentialsProvider, accounts []AccountRef, ...) (*AccountConnections, error)
- func (server *Server) Serve()
- func (server *Server) ServeNATSAccount(accountID string, nc *nats.Conn) error
- func (server *Server) ServeOpenAPI(spec []byte)
- func (server *Server) StartNATSAPI() error
- func (server *Server) Stop()
- func (server *Server) StopNATSAccount(accountID string) error
- type ServerOptions
- func (options *ServerOptions) GetCertificate() (tls.Certificate, error)
- func (options *ServerOptions) GetConnectionString() string
- func (options *ServerOptions) GetMetadata(key string) interface{}
- func (options *ServerOptions) GetTLSConfig() (*tls.Config, error)
- func (options *ServerOptions) UseLetsEncrypt() bool
- type Websocket
- type WebsocketOptions
Constants ¶
const ( EndpointNotImplementedResponse = `{"status": "404", "message": "endpoint not implemented"}` NoopResponse = `{"status": "200", "message": "noop"}` InternalServerError = `{"status": "500", "message": "internal server error"}` )
Variables ¶
var EndpointNotImplemented = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNotFound) json.NewEncoder(w).Encode(EndpointNotImplementedResponse) })
var Noop = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(NoopResponse) })
Functions ¶
func SPAHandler ¶
SPAHandler serves a single-page application from fsys: static files with long-lived caching for hashed assets, index.html as the fallback for client-side routes, and precompressed variants (file.br, file.gz) when the build produced them and the client accepts the encoding.
func SetAllowAllWebsocketOrigins ¶
func SetAllowAllWebsocketOrigins(allow bool)
SetAllowAllWebsocketOrigins disables WebSocket origin validation. Development use only; leaving this on in production is a cross-origin (CSRF) hole.
func SetAllowedOrigins ¶
func SetAllowedOrigins(origins []string)
SetAllowedOrigins replaces the WebSocket origin allowlist.
Types ¶
type AccountConnections ¶
type AccountConnections struct {
// contains filtered or unexported fields
}
AccountConnections serves the NATS API inside every tenant account. NATS accounts isolate subjects, so a service connected in its own account is invisible to a caller inside a tenant account; the follower therefore opens one connection per account, serves the API on each, and follows accounts as the admin creates and deletes them (tenant.notify.*).
func (*AccountConnections) Accounts ¶
func (ac *AccountConnections) Accounts() []string
Accounts returns the IDs of the followed accounts currently served.
func (*AccountConnections) AddAccount ¶
func (ac *AccountConnections) AddAccount(accountID, accountName string)
AddAccount connects inside the account and serves the API there. It is idempotent per account ID, skips the primary account, and is a no-op after Close. Failures are logged, not returned, because the follower runs from notifications.
func (*AccountConnections) Close ¶
func (ac *AccountConnections) Close()
Close drops the notification subscriptions and closes every account connection. The primary connection is left alone.
func (*AccountConnections) RemoveAccount ¶
func (ac *AccountConnections) RemoveAccount(accountID string)
RemoveAccount stops serving the account and closes its connection.
type AccountConnector ¶
AccountConnector opens a NATS connection inside an account with the given credentials and returns it together with a function that closes it. The default connector uses the server's TLS material and MessengerServerURL through package messenger; tests inject a plain one.
type AccountCredentialsProvider ¶
type AccountCredentialsProvider interface {
ServiceCredentials(accountID, accountName string) (jwt, seed string, err error)
}
AccountCredentialsProvider mints the NATS credentials a service uses to connect inside a tenant account. The admin server implements it for the process that hosts it; a remote service can implement it over GET /api/v1/servicecredentials/{accountName}/{serviceName}.
type AccountRef ¶
AccountRef names a tenant account to follow.
type FollowOption ¶
type FollowOption func(*AccountConnections)
FollowOption configures FollowAccounts.
func WithAccountConnector ¶
func WithAccountConnector(c AccountConnector) FollowOption
WithAccountConnector replaces the default connector.
type Server ¶
type Server struct {
ServerOptions *ServerOptions
Srv *http.Server
Logger *logger.Logger
Router *mux.Router
Middleware []*mux.MiddlewareFunc
Websocket *Websocket
MessengerClient *messenger.Client
TrustedAccounts []string
LetsEncryptMgr *letsencrypt.Manager
// NATSAPI is the bridge that serves the HTTP API over NATS once
// StartNATSAPI (or ServeNATSAccount) has been called; nil until then.
NATSAPI *natsapi.Service
// contains filtered or unexported fields
}
func NewServer ¶
func NewServer(options *ServerOptions) (*Server, error)
func (*Server) AddMessenger ¶
func (server *Server) AddMessenger(options *messenger.ClientOptions) error
func (*Server) FollowAccounts ¶
func (server *Server) FollowAccounts(provider AccountCredentialsProvider, accounts []AccountRef, opts ...FollowOption) (*AccountConnections, error)
FollowAccounts serves the NATS API inside each of accounts (except the server's own messenger account, which StartNATSAPI serves) and keeps following tenant lifecycle notifications on the primary messenger connection. The server must have a messenger client.
func (*Server) ServeNATSAccount ¶
ServeNATSAccount serves the HTTP API over NATS on nc, pinned to accountID. The bridge is created on first use. Serving an account that is already served is a no-op.
func (*Server) ServeOpenAPI ¶
ServeOpenAPI registers GET /api/v1/openapi.json returning the given spec. The route is unauthenticated so the API explorer can load it before or after login; specs document the API but contain no secrets.
func (*Server) StartNATSAPI ¶
StartNATSAPI serves the HTTP API over NATS on the server's messenger connection, pinned to the messenger account (ServerOptions. MessengerAccountID, else the client's AccountID). It is idempotent and is called by Serve when ServerOptions.NATSAPI is set; call it directly when the messenger client is attached after Serve (AddMessenger).
func (*Server) Stop ¶
func (server *Server) Stop()
Stop gracefully stops the server and cleans up resources
func (*Server) StopNATSAccount ¶
StopNATSAccount stops serving one account; its connection stays open.
type ServerOptions ¶
type ServerOptions struct {
Application string `json:"application"`
Component string `json:"component"`
// Static TLS certificates (used when LetsEncrypt is not enabled)
PrivateKey []byte `json:"private_key"`
Certificate []byte `json:"certificate"`
CA []byte `json:"ca"`
// Let's Encrypt configuration (optional - if enabled, overrides static certs)
LetsEncrypt *config.LetsEncryptConfig `json:"lets_encrypt,omitempty"`
// Shared Let's Encrypt manager (preferred over LetsEncrypt config for all-in-one deployments)
LetsEncryptManager *letsencrypt.Manager `json:"-"`
HTTPPort int `json:"http_port"`
PublicKey string `json:"public_key"`
Messenger bool `json:"messenger"`
MessengerAccountID string `json:"messenger_account_id"`
MessengerServerURL string `json:"messenger_server_url"`
MessengerServerName string `json:"messenger_server_name"`
MessengerJWT string `json:"messenger_jwt"`
MessengerSeed string `json:"messenger_seed"`
TrustedAccounts []string `json:"trusted_accounts"`
BasicAuth bool `json:"basic_auth"`
// NATSAPI serves the HTTP API over NATS as well (package natsapi):
// the same routes, verbs, payloads, and auth wrappers, reachable by
// any caller inside the messenger account with only the controller URL
// and its own credentials. It needs a messenger client.
NATSAPI bool `json:"nats_api"`
// NATSAPIService is the subject token and micro service name
// (api.{service}.{METHOD}.{resource}). Default: Component.
NATSAPIService string `json:"nats_api_service"`
// NATSAPIVersion is the micro service version (semver). Default 1.0.0.
NATSAPIVersion string `json:"nats_api_version"`
// NATSAPIDescription is published in the micro service info.
NATSAPIDescription string `json:"nats_api_description"`
// AllowedOrigins configures the CORS allowlist. When empty it defaults to
// ["*"]. Auth is header-based (bearer/basic, not cookies) so a wildcard
// does not leak credentials, but production deployments should pin their
// own origins here to narrow the surface.
AllowedOrigins []string `json:"allowed_origins"`
// this is for http authZ
Metadata map[string]interface{} `json:"metadata"`
}
Logger per server
func DefaultServerOptions ¶
func DefaultServerOptions() *ServerOptions
func (*ServerOptions) GetCertificate ¶
func (options *ServerOptions) GetCertificate() (tls.Certificate, error)
func (*ServerOptions) GetConnectionString ¶
func (options *ServerOptions) GetConnectionString() string
This is for HTTP server
func (*ServerOptions) GetMetadata ¶
func (options *ServerOptions) GetMetadata(key string) interface{}
Get metadata value from key. Returns nil if key does not exist.
func (*ServerOptions) GetTLSConfig ¶
func (options *ServerOptions) GetTLSConfig() (*tls.Config, error)
GetTLSConfig returns a *tls.Config for the static certificate. It returns a pointer (not a value) because tls.Config contains a sync.RWMutex and must not be copied.
func (*ServerOptions) UseLetsEncrypt ¶
func (options *ServerOptions) UseLetsEncrypt() bool
UseLetsEncrypt returns true if Let's Encrypt is configured and enabled
type Websocket ¶
type Websocket struct {
Options *WebsocketOptions
Logger *logger.Logger
}
implementation of http.Handler
func NewWebsocket ¶
func NewWebsocket(options *WebsocketOptions) *Websocket
type WebsocketOptions ¶
type WebsocketOptions struct {
Application string `json:"application"`
}