Documentation ¶
Overview ¶
Package rpc provides a remote procedure call (RPC) library based on gRPC.
In a server context, this package should be preferred over gRPC directly since it provides higher level configuration with more features built in, such as grpc-web, gRPC via RESTful JSON, and gRPC via WebRTC.
WebRTC services gRPC over DataChannels. The work was initially adapted from https://github.com/jsmouret/grpc-over-webrtc.
Connection ¶
All connections to RPC servers are done by way of the Dial method which will try the following mechanisms to connect to a target server:
1. mDNS (direct/WebRTC) 2. WebRTC 3. Direct gRPC
By default it will try to connect with mDNS (1) and WebRTC (2) in parallel and use the first established connection. If both fail then it will try to connection with Direct gRPC. This ordering can be modified by disabling some of these methods with DialOptions.
Direct gRPC ¶
This is the simplest form of connection and for the most part passes straight through to the gRPC libraries.
WebRTC ¶
This is the most complex form of connection. A WebRTC connection is established by way of a provided WebRTC signaling server that exchanges connection information about the client and server. This exchange has the client and server act as peers and connects them in the best way possible via ICE. If this succeeds a DataChannel is established that we use to tunnel over gRPC method calls (mimicking the gRPC over HTTP2 specification (https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md)). Using this is a powerful means of connection because it exposes ContextPeerConnection which makes it possible to use gRPC methods to modify the Video/Audio part of the connection.
Multicast DNS (mDNS)
By default, a server will broadcast its ability to be connected to over gRPC/WebRTC over mDNS. When a dial target that matches an instance name provided by the WithInstanceNames ServerOption is found via mDNS, it will convey information about its internal gRPC IP address so that a connection can be made to it directly, either via gRPC or WebRTC. This is powerful in situations where clients/servers can only communicate in a local direct or a faster connection can be made without going out to the internet. Not that the broadcasted address is that of the internal gRPC listener. That behavior can be changed via the WithExternalListenerAddress ServerOption. That means, if the WithInternalTLSConfig option is used, any mDNS connections made will request client certificates. This will not negatively affect any UI hosted (peer certificate prompt) that uses the server's GRPCHandler because since that handler will only use the tls.Config of the http.Server hosting it, separate from the internal one.
Authentication Modes ¶
Authentication into gRPC works by configuring a server with a series of authentication handlers provided by this framework. When one authentication handler is enabled, all requests must be authenticated, except for the Authenticate method itself. Each handler is associated with a type of credentials to handle (rpc.CredentialsType) and an rpc.AuthHandler which has a single method called Authenticate. Authenticate is responsible for taking the name of an entity and a payload that proves the caller is allowed to assume the role of that entity. It returns metadata about the entity (e.g. an email, a user ID, etc.). The framework then returns a JWT to the client to use in subsequent requests. On those subsequent requests, the JWT is included in an HTTP header called Authorization with a value of Bearer <token>. The framework then intercepts all calls and ensures that there is a JWT present in the header and is cryptographically valid. An optionally supplied TokenVerificationKeyProvider associated with the credential type can be used to provide a key used to verify the JWT if it was not signed by the RPC service provider. Once verified an optionally supplied EntityDataLoader associated with the credential type can use the JWT metadata to produce application to produce data for the entity to be accessible via rpc.MustContextAuthEntity.
Additionally, authentication via mutual TLS is supported by way of the WithTLSAuthHandler and WithInternalTLSConfig ServerOptions. Using these two options in tandem will ask clients connecting to present a client certificate, which will be verified. This verified certificate is then caught by the authentication middleware before JWT presence is checked. If any of the DNS names in the verified client certificate match that of the entities checked in WithTLSAuthHandler, then the request will be allowed to proceed.
For WebRTC, we assume that signaling is implemented as an authenticated/authorized service and for now, do not pass any JWTs over the WebRTC data channels that are established.
There is an additional feature, called AuthenticateTo provided by the ExternalAuthService which allows for external authentication on another server to "authenticate to" an entity on the target being connected to. This is an extension that can be used via the WithAuthenticateToHandler ServerOption. When a client is connecting, it will first connect to the external auth server with credentials intended for that server, and then it will call AuthenticateTo to get a JWT destined for the actual target being connected to. AuthenticateTo requires an entity to authenticate as. You can think of this feature as the ability to assume the role of another entity.
Expiration of JWTs is not yet handled/support.
Authorization Modes ¶
Authorization is strictly not handled by this framework. It's up to your registered services/methods to handle authorization.
Index ¶
- Constants
- Variables
- func ConfigureForRenegotiation(peerConn *webrtc.PeerConnection, role PeerRole, ...) (<-chan struct{}, <-chan struct{}, error)
- func ContextPeerConnection(ctx context.Context) (*webrtc.PeerConnection, bool)
- func ContextWithAuthEntity(ctx context.Context, authEntity EntityInfo) context.Context
- func ContextWithDialer(ctx context.Context, d Dialer) context.Context
- func DecodeSDP(in string, sdp *webrtc.SessionDescription) error
- func ED25519PublicKeyThumbprint(key ed25519.PublicKey) string
- func EncodeSDP(sdp *webrtc.SessionDescription) (string, error)
- func ErrorToStatus(err error) *status.Status
- func HeartbeatsAllowedFromCtx(ctx context.Context) bool
- func HostFromCtx(ctx context.Context) (string, error)
- func HostsFromCtx(ctx context.Context) ([]string, error)
- func InstanceNameFromAddress(addr string) (string, error)
- func MakeEntitiesChecker(forEntities []string) func(ctx context.Context, entities ...string) error
- func RSAPublicKeyThumbprint(key *rsa.PublicKey) (string, error)
- func StreamClientTracingInterceptor() grpc.StreamClientInterceptor
- func StreamServerTracingInterceptor(logger *zap.Logger) grpc.StreamServerInterceptor
- func TokenFromContext(ctx context.Context) (string, error)
- func UnaryClientInvalidAuthInterceptor(creds *perRPCJWTCredentials) grpc.UnaryClientInterceptor
- func UnaryClientTracingInterceptor() grpc.UnaryClientInterceptor
- func UnaryServerTracingInterceptor(logger *zap.Logger) grpc.UnaryServerInterceptor
- type AuthHandler
- type AuthHandlerFunc
- type AuthenticateToHandler
- type Claims
- type ClientConn
- func Dial(ctx context.Context, address string, logger utils.ZapCompatibleLogger, ...) (ClientConn, error)
- func DialDirectGRPC(ctx context.Context, address string, logger utils.ZapCompatibleLogger, ...) (ClientConn, error)
- func DialWebRTC(ctx context.Context, signalingServer string, host string, ...) (conn ClientConn, err error)
- type ClientConnAuthenticator
- type Credentials
- type CredentialsType
- type DialMulticastDNSOptions
- type DialOption
- func WithAllowInsecureDowngrade() DialOption
- func WithAllowInsecureWithCredentialsDowngrade() DialOption
- func WithCredentials(creds Credentials) DialOption
- func WithDialDebug() DialOption
- func WithDialMulticastDNSOptions(opts DialMulticastDNSOptions) DialOption
- func WithDialStatsHandler(handler stats.Handler) DialOption
- func WithDisableDirectGRPC() DialOption
- func WithEntityCredentials(entity string, creds Credentials) DialOption
- func WithExternalAuth(addr, toEntity string) DialOption
- func WithExternalAuthInsecure() DialOption
- func WithForceDirectGRPC() DialOption
- func WithInsecure() DialOption
- func WithStaticAuthenticationMaterial(authMaterial string) DialOption
- func WithStaticExternalAuthenticationMaterial(authMaterial string) DialOption
- func WithStreamClientInterceptor(interceptor grpc.StreamClientInterceptor) DialOption
- func WithTLSConfig(config *tls.Config) DialOption
- func WithUnaryClientInterceptor(interceptor grpc.UnaryClientInterceptor) DialOption
- func WithWebRTCOptions(webrtcOpts DialWebRTCOptions) DialOption
- type DialWebRTCOptions
- type Dialer
- type EntityDataLoader
- type EntityDataLoaderFunc
- type EntityInfo
- type GrpcOverHTTPClientConn
- type JWTClaims
- type PeerConnectionInfo
- type PeerConnectionType
- type PeerRole
- type RegisterServiceHandlerFromEndpointFunc
- type Server
- type ServerOption
- func WithAllowUnauthenticatedHealthCheck() ServerOption
- func WithAuthAudience(authAudience ...string) ServerOption
- func WithAuthED25519PrivateKey(authED25519PrivateKey ed25519.PrivateKey) (ServerOption, string)
- func WithAuthHandler(forType CredentialsType, handler AuthHandler) ServerOption
- func WithAuthIssuer(authIssuer string) ServerOption
- func WithAuthRSAPrivateKey(authRSAPrivateKey *rsa.PrivateKey) (ServerOption, string, error)
- func WithAuthenticateToHandler(handler AuthenticateToHandler) ServerOption
- func WithDebug() ServerOption
- func WithDisableMulticastDNS() ServerOption
- func WithEnsureAuthedHandler(eah func(ctx context.Context) (context.Context, error)) ServerOption
- func WithEntityDataLoader(forType CredentialsType, loader EntityDataLoader) ServerOption
- func WithExternalAuthEd25519PublicKeyTokenVerifier(pubKey ed25519.PublicKey) ServerOption
- func WithExternalAuthJWKSetTokenVerifier(keySet jwks.KeySet) ServerOption
- func WithExternalAuthOIDCTokenVerifier(ctx context.Context, issuer string) (ServerOption, func(ctx context.Context) error, error)
- func WithExternalAuthRSAPublicKeyTokenVerifier(pubKey *rsa.PublicKey) ServerOption
- func WithExternalListenerAddress(address *net.TCPAddr) ServerOption
- func WithExternalTokenVerificationKeyProvider(provider TokenVerificationKeyProvider) ServerOption
- func WithInstanceNames(names ...string) ServerOption
- func WithInternalBindAddress(address string) ServerOption
- func WithInternalTLSConfig(config *tls.Config) ServerOption
- func WithJWTSignerKeyID(keyID string) ServerOption
- func WithPublicMethods(fullMethods []string) ServerOption
- func WithStatsHandler(handler stats.Handler) ServerOption
- func WithStreamServerInterceptor(streamInterceptor grpc.StreamServerInterceptor) ServerOption
- func WithTLSAuthHandler(entities []string) ServerOption
- func WithTokenVerificationKeyProvider(forType CredentialsType, provider TokenVerificationKeyProvider) ServerOption
- func WithUnaryServerInterceptor(unaryInterceptor grpc.UnaryServerInterceptor) ServerOption
- func WithUnauthenticated() ServerOption
- func WithUnknownServiceHandler(streamHandler grpc.StreamHandler) ServerOption
- func WithWebRTCServerOptions(webrtcOpts WebRTCServerOptions) ServerOption
- type SimpleServerStats
- type TCPGrpcStats
- type TokenVerificationKeyProvider
- func MakeEd25519PublicKeyProvider(pubKey ed25519.PublicKey) TokenVerificationKeyProvider
- func MakeJWKSKeyProvider(provider jwks.KeyProvider) TokenVerificationKeyProvider
- func MakeOIDCKeyProvider(ctx context.Context, issuer string) (TokenVerificationKeyProvider, error)
- func MakeRSAPublicKeyProvider(pubKey *rsa.PublicKey) TokenVerificationKeyProvider
- type TokenVerificationKeyProviderFunc
- type WebRTCCallAnswer
- type WebRTCCallOffer
- type WebRTCCallOfferExchange
- type WebRTCCallQueue
- type WebRTCConfig
- type WebRTCConfigProvider
- type WebRTCGrpcStats
- type WebRTCLoggerFactory
- type WebRTCServerOptions
- type WebRTCSignalingServer
- func (srv *WebRTCSignalingServer) Answer(server webrtcpb.SignalingService_AnswerServer) error
- func (srv *WebRTCSignalingServer) Call(req *webrtcpb.CallRequest, server webrtcpb.SignalingService_CallServer) error
- func (srv *WebRTCSignalingServer) CallUpdate(ctx context.Context, req *webrtcpb.CallUpdateRequest) (*webrtcpb.CallUpdateResponse, error)
- func (srv *WebRTCSignalingServer) Close()
- func (srv *WebRTCSignalingServer) OptionalWebRTCConfig(ctx context.Context, req *webrtcpb.OptionalWebRTCConfigRequest) (*webrtcpb.OptionalWebRTCConfigResponse, error)
Constants ¶
const ( // CredentialsTypeAPIKey is intended for by external users, human and computer. CredentialsTypeAPIKey = CredentialsType("api-key") // CredentialsTypeExternal is for credentials that are to be produced by some // external authentication endpoint (see ExternalAuthService#AuthenticateTo) intended // for another, different consumer at a different endpoint. CredentialsTypeExternal = CredentialsType("external") )
const ( PeerConnectionTypeUnknown = PeerConnectionType(iota) PeerConnectionTypeGRPC PeerConnectionTypeWebRTC )
Known types of peer connections.
const ( // MetadataFieldAuthorization is a constant for the authorization header key. MetadataFieldAuthorization = "authorization" // AuthorizationValuePrefixBearer is a constant for the Bearer token prefix. AuthorizationValuePrefixBearer = "Bearer " )
const HeartbeatsAllowedMetadataField = "heartbeats-allowed"
HeartbeatsAllowedMetadataField is the identifier for allowing heartbeats from a signaling server to answerers.
const RPCHostMetadataField = "rpc-host"
RPCHostMetadataField is the identifier of a host.
Variables ¶
var ( // MaxMessageSize is the maximum size a gRPC message can be. MaxMessageSize = 1 << 25 // SocksProxyEnvVar is the name of an environment variable used by SOCKS // proxies to indicate the address through which to route all network traffic // via SOCKS5. SocksProxyEnvVar = "SOCKS_PROXY" )
var DefaultICEServers = []webrtc.ICEServer{ { URLs: []string{"stun:global.stun.twilio.com:3478"}, }, }
DefaultICEServers is the default set of ICE servers to use for WebRTC session negotiation. There is no guarantee that the defaults here will remain usable.
var DefaultWebRTCConfiguration = webrtc.Configuration{ ICEServers: DefaultICEServers, }
DefaultWebRTCConfiguration is the standard configuration used for WebRTC peers.
var DefaultWebRTCMaxGRPCCalls = 256
DefaultWebRTCMaxGRPCCalls is the maximum number of concurrent gRPC calls to allow for a server.
var ErrConnectionOptionsExhausted = errors.New("exhausted all connection options with no way to connect")
ErrConnectionOptionsExhausted is returned in cases where the given options have all been used up with no way to connect on any of them.
var ( // ErrDisconnected indicates that the channel underlying the client stream // has been closed, and the client is therefore disconnected. ErrDisconnected = errors.New("client disconnected; underlying channel closed") )
var ErrIllegalHeaderWrite = errors.New("transport: the stream is done or WriteHeader was already called")
ErrIllegalHeaderWrite indicates that setting header is illegal because of the state of the stream.
var ErrInsecureWithCredentials = errors.New("requested address is insecure and will not send credentials")
ErrInsecureWithCredentials is sent when a dial attempt is made to an address where either the insecure option or insecure downgrade with credentials options are not set.
var ErrNoWebRTCSignaler = errors.New("no signaler present")
ErrNoWebRTCSignaler happens if a gRPC request is made on a server that does not support signaling for WebRTC or explicitly not the host requested.
var JSONPB = &runtime.JSONPb{ MarshalOptions: protojson.MarshalOptions{ UseProtoNames: true, EmitUnpopulated: true, }, }
JSONPB are the JSON protobuf options we use globally.
var (
// WebRTCMaxStreamCount is the max number of streams a channel can have.
WebRTCMaxStreamCount = 256
)
Functions ¶
func ConfigureForRenegotiation ¶ added in v0.1.71
func ConfigureForRenegotiation( peerConn *webrtc.PeerConnection, role PeerRole, logger utils.ZapCompatibleLogger, ) (<-chan struct{}, <-chan struct{}, error)
ConfigureForRenegotiation sets up PeerConnection callbacks for updating local descriptions and sending offers when a negotiation is needed (e.g: adding a video track). As well as listening for offers/answers to update remote descriptions (e.g: when the peer adds a video track).
If successful, two Go channels are returned. The first Go channel will close when the negotiation DataChannel is open and available for renegotiation. The second Go channel will close when the negotiation DataChannel is closed. PeerConnection.Close does not wait on DataChannel's to finish their work. Thus waiting on this can be helpful to guarantee background goroutines have exitted.
func ContextPeerConnection ¶ added in v0.0.3
ContextPeerConnection returns a peer connection, if set.
func ContextWithAuthEntity ¶ added in v0.0.3
func ContextWithAuthEntity(ctx context.Context, authEntity EntityInfo) context.Context
ContextWithAuthEntity attaches an entity (e.g. a user) for an authenticated context to the given context.
func ContextWithDialer ¶ added in v0.0.2
ContextWithDialer attaches a Dialer to the given context.
func ED25519PublicKeyThumbprint ¶ added in v0.1.70
ED25519PublicKeyThumbprint returns the base64 encoded public key.
func ErrorToStatus ¶ added in v0.0.2
ErrorToStatus converts an error to a gRPC status. A nil error becomes a successful status.
func HeartbeatsAllowedFromCtx ¶ added in v0.1.104
HeartbeatsAllowedFromCtx checks if heartbeats are allowed with respect to the context.
func HostFromCtx ¶ added in v0.0.3
HostFromCtx gets the host being called/answered for from the context.
func HostsFromCtx ¶ added in v0.0.3
HostsFromCtx gets the hosts being called/answered for from the context.
func InstanceNameFromAddress ¶ added in v0.0.3
InstanceNameFromAddress returns a suitable instance name given an address. If it's empty or an IP address, a new UUID is returned.
func MakeEntitiesChecker ¶ added in v0.0.3
MakeEntitiesChecker checks a list of entities against a given one for use in an auth handler.
func RSAPublicKeyThumbprint ¶ added in v0.1.6
RSAPublicKeyThumbprint returns SHA1 of the public key's modulus Base64 URL encoded without padding.
func StreamClientTracingInterceptor ¶ added in v0.1.38
func StreamClientTracingInterceptor() grpc.StreamClientInterceptor
StreamClientTracingInterceptor adds the current Span's metadata to the context.
func StreamServerTracingInterceptor ¶ added in v0.1.38
func StreamServerTracingInterceptor(logger *zap.Logger) grpc.StreamServerInterceptor
StreamServerTracingInterceptor starts a new Span if Span metadata exists in the context.
func TokenFromContext ¶ added in v0.1.102
TokenFromContext returns the bearer token from the authorization header and errors if it does not exist.
func UnaryClientInvalidAuthInterceptor ¶ added in v0.1.74
func UnaryClientInvalidAuthInterceptor(creds *perRPCJWTCredentials) grpc.UnaryClientInterceptor
UnaryClientInvalidAuthInterceptor clears the access token stored on creds in the event of an "Unauthenticated" or "PermissionDenied" gRPC error to force re-auth.
func UnaryClientTracingInterceptor ¶ added in v0.1.38
func UnaryClientTracingInterceptor() grpc.UnaryClientInterceptor
UnaryClientTracingInterceptor adds the current Span's metadata to the context.
func UnaryServerTracingInterceptor ¶ added in v0.1.38
func UnaryServerTracingInterceptor(logger *zap.Logger) grpc.UnaryServerInterceptor
UnaryServerTracingInterceptor starts a new Span if Span metadata exists in the context.
Types ¶
type AuthHandler ¶ added in v0.0.2
type AuthHandler interface { // Authenticate returns nil if the given payload is valid authentication material. // Optional authentication metadata can be returned to be used in future requests // via ContextAuthMetadata. Authenticate(ctx context.Context, entity, payload string) (map[string]string, error) }
An AuthHandler is responsible for authenticating an RPC connection. That means that if the idea of multiple entities can be involved in one connection, that this is not a suitable abstraction to use. The use of entity and subject are interchangeable here.
func MakeSimpleAuthHandler ¶ added in v0.0.2
func MakeSimpleAuthHandler(forEntities []string, expectedPayload string) AuthHandler
MakeSimpleAuthHandler returns a simple auth handler that handles multiple entities sharing one payload. This is useful for setting up local/internal authentication with a shared key. This is NOT secure for usage over networks exposed to the public internet. For that, use a more sophisticated handler with at least one key per entity.
func MakeSimpleMultiAuthHandler ¶ added in v0.0.6
func MakeSimpleMultiAuthHandler(forEntities, expectedPayloads []string) AuthHandler
MakeSimpleMultiAuthHandler returns a simple auth handler that handles multiple entities sharing multiple possible payloads. This is useful for rolling keys.
func MakeSimpleMultiAuthPairHandler ¶ added in v0.1.47
func MakeSimpleMultiAuthPairHandler(expectedPayloads map[string]string) AuthHandler
MakeSimpleMultiAuthPairHandler works similarly to MakeSimpleMultiAuthHandler with the addition of supporting a key, id pair used to ensure that a key that maps to the id matches the key passed during the function call.
type AuthHandlerFunc ¶ added in v0.1.17
AuthHandlerFunc is an AuthHandler for entities.
func (AuthHandlerFunc) Authenticate ¶ added in v0.1.17
func (h AuthHandlerFunc) Authenticate(ctx context.Context, entity, payload string) (map[string]string, error)
Authenticate checks if the given entity and payload are what it expects. It returns an error otherwise.
type AuthenticateToHandler ¶ added in v0.0.3
An AuthenticateToHandler determines if the given entity should be allowed to be authenticated to by the calling entity, accessible via MustContextAuthEntity. Similarly, the returned auth metadata will be present on the given entity's endpoints via ContextAuthEntity. The use of entity and subject are interchangeable here with respect to the entity being authenticated to.
type Claims ¶ added in v0.1.1
type Claims interface { // Ensure we meet the jwt.Claims interface, return error if claims are invalid. Claims // are validated before entity checks, jwt.Claims // Entity returns the entity associated with the claims. Also known // as a Subject. Entity() string // CredentialsType returns the rpc CredentialsType based on the jwt claims. CredentialsType() CredentialsType // Metadata returns the rpc auth metadata based on the jwt claims. Metadata() map[string]string }
Claims is an interface that all custom claims must implement to be supported by the rpc system.
type ClientConn ¶ added in v0.0.2
type ClientConn interface { grpc.ClientConnInterface // PeerConn returns the backing PeerConnection object, or nil if the underlying transport is not // a PeerConnection. PeerConn() *webrtc.PeerConnection Close() error }
A ClientConn is a wrapper around the gRPC client connection interface but ensures there is a way to close the connection.
func Dial ¶ added in v0.0.2
func Dial(ctx context.Context, address string, logger utils.ZapCompatibleLogger, opts ...DialOption) (ClientConn, error)
Dial attempts to make the most convenient connection to the given address. It attempts to connect via WebRTC if a signaling server is detected or provided. Otherwise it attempts to connect directly. TODO(GOUT-7): figure out decent way to handle reconnect on connection termination.
func DialDirectGRPC ¶ added in v0.0.3
func DialDirectGRPC(ctx context.Context, address string, logger utils.ZapCompatibleLogger, opts ...DialOption) (ClientConn, error)
DialDirectGRPC dials a gRPC server directly.
func DialWebRTC ¶ added in v0.0.2
func DialWebRTC( ctx context.Context, signalingServer string, host string, logger utils.ZapCompatibleLogger, opts ...DialOption, ) (conn ClientConn, err error)
DialWebRTC connects to the signaling service at the given address and attempts to establish a WebRTC connection with the corresponding peer reflected in the address. It provider client/server functionality for gRPC serviced over WebRTC data channels. The work is adapted from https://github.com/jsmouret/grpc-over-webrtc.
type ClientConnAuthenticator ¶ added in v0.0.5
type ClientConnAuthenticator interface { ClientConn Authenticate(ctx context.Context) (string, error) }
A ClientConnAuthenticator supports instructing a connection to authenticate now.
type Credentials ¶ added in v0.0.2
type Credentials struct { Type CredentialsType `json:"type"` Payload string `json:"payload"` }
Credentials packages up both a type of credential along with its payload which is formatted specific to the type.
type CredentialsType ¶ added in v0.0.2
type CredentialsType string
CredentialsType signifies a means of representing a credential. For example, an API key.
type DialMulticastDNSOptions ¶ added in v0.0.3
type DialMulticastDNSOptions struct { // Disable disables mDNS service discovery for other robots. You may want to use this // if you do not trust the network you're in to truthfully advertise services. That // being said, if this is a concern, you should use TLS server verification. Disable bool // RemoveAuthCredentials will remove any and all authentication credentials when dialing. // This is particularly helpful in managed environments that do inter-robot TLS authN/Z. RemoveAuthCredentials bool }
DialMulticastDNSOptions dictate any special settings to apply while dialing via mDNS.
type DialOption ¶ added in v0.0.2
type DialOption interface {
// contains filtered or unexported methods
}
DialOption configures how we set up the connection. Cribbed from https://github.com/grpc/grpc-go/blob/aff571cc86e6e7e740130dbbb32a9741558db805/dialoptions.go#L41
func WithAllowInsecureDowngrade ¶ added in v0.0.3
func WithAllowInsecureDowngrade() DialOption
WithAllowInsecureDowngrade returns a DialOption which allows connections to be downgraded to plaintext if TLS cannot be detected properly. This is not used when there are credentials present. For that, use the more explicit WithAllowInsecureWithCredsDowngrade.
func WithAllowInsecureWithCredentialsDowngrade ¶ added in v0.0.3
func WithAllowInsecureWithCredentialsDowngrade() DialOption
WithAllowInsecureWithCredentialsDowngrade returns a DialOption which allows connections to be downgraded to plaintext if TLS cannot be detected properly while using credentials. This is generally unsafe to use but can be requested.
func WithCredentials ¶ added in v0.0.2
func WithCredentials(creds Credentials) DialOption
WithCredentials returns a DialOption which sets the credentials to use for authenticating the request. The associated entity is assumed to be the address of the server. This is mutually exclusive with WithEntityCredentials.
func WithDialDebug ¶ added in v0.0.3
func WithDialDebug() DialOption
WithDialDebug returns a DialOption which informs the client to be in a debug mode as much as possible.
func WithDialMulticastDNSOptions ¶ added in v0.0.3
func WithDialMulticastDNSOptions(opts DialMulticastDNSOptions) DialOption
WithDialMulticastDNSOptions returns a DialOption which allows setting options to specifically be used while doing a dial based off mDNS discovery.
func WithDialStatsHandler ¶ added in v0.0.5
func WithDialStatsHandler(handler stats.Handler) DialOption
WithDialStatsHandler returns a DialOption which sets the stats handler on the DialOption that specifies the stats handler for all the RPCs and underlying network connections.
func WithDisableDirectGRPC ¶ added in v0.0.3
func WithDisableDirectGRPC() DialOption
WithDisableDirectGRPC returns a DialOption which disables directly dialing a gRPC server. There's not really a good reason to use this unless it's for testing.
func WithEntityCredentials ¶ added in v0.0.2
func WithEntityCredentials(entity string, creds Credentials) DialOption
WithEntityCredentials returns a DialOption which sets the entity credentials to use for authenticating the request. This is mutually exclusive with WithCredentials.
func WithExternalAuth ¶ added in v0.0.2
func WithExternalAuth(addr, toEntity string) DialOption
WithExternalAuth returns a DialOption which sets the address to use to perform authentication. Authentication done in this manner will never have the dialed address be authenticated against but instead have access tokens sent directly to it. The entity which authentication is intended for must also be specified. ExternalAuth uses the ExternalAuthService extension and this library does not provide a standard implementation for it. It is expected that the credentials used in these same dial options will be used to first authenticate to the external server using the AuthService. Note: When making a gRPC connection to the given address, the same dial options are used. That means if the external address is secured, so must the internal target.
func WithExternalAuthInsecure ¶ added in v0.0.3
func WithExternalAuthInsecure() DialOption
WithExternalAuthInsecure returns a DialOption which disables transport security for this ClientConn when doing external auth. Note that transport security is required unless WithExternalAuthInsecure is set.
func WithForceDirectGRPC ¶ added in v0.1.6
func WithForceDirectGRPC() DialOption
WithForceDirectGRPC forces direct dialing to the target address. This option disables WebRTC connections and mDNS lookup.
func WithInsecure ¶ added in v0.0.2
func WithInsecure() DialOption
WithInsecure returns a DialOption which disables transport security for this ClientConn. Note that transport security is required unless WithInsecure is set.
func WithStaticAuthenticationMaterial ¶ added in v0.0.5
func WithStaticAuthenticationMaterial(authMaterial string) DialOption
WithStaticAuthenticationMaterial returns a DialOption which sets the already authenticated material (opaque) to use for authenticated requests. This is mutually exclusive with auth and external auth options.
func WithStaticExternalAuthenticationMaterial ¶ added in v0.1.8
func WithStaticExternalAuthenticationMaterial(authMaterial string) DialOption
WithStaticExternalAuthenticationMaterial returns a DialOption which sets the already authenticated material (opaque) to use for authenticated requests against an external auth service. Ignored if WithStaticAuthenticationMaterial() is set.
func WithStreamClientInterceptor ¶ added in v0.1.1
func WithStreamClientInterceptor(interceptor grpc.StreamClientInterceptor) DialOption
WithStreamClientInterceptor returns a DialOption that specifies the interceptor for streaming RPCs.
func WithTLSConfig ¶ added in v0.0.3
func WithTLSConfig(config *tls.Config) DialOption
WithTLSConfig sets the TLS configuration to use for all secured connections.
func WithUnaryClientInterceptor ¶ added in v0.1.1
func WithUnaryClientInterceptor(interceptor grpc.UnaryClientInterceptor) DialOption
WithUnaryClientInterceptor returns a DialOption that specifies the interceptor for unary RPCs.
func WithWebRTCOptions ¶ added in v0.0.2
func WithWebRTCOptions(webrtcOpts DialWebRTCOptions) DialOption
WithWebRTCOptions returns a DialOption which sets the WebRTC options to use if the dialer tries to establish a WebRTC connection.
type DialWebRTCOptions ¶ added in v0.0.2
type DialWebRTCOptions struct { // Disable prevents a WebRTC connection attempt. Disable bool // SignalingInsecure determines if the signaling connection is insecure. SignalingInsecure bool // SignalingServerAddress specifies the signaling server to // contact on behalf of this client for WebRTC communications. SignalingServerAddress string // SignalingAuthEntity is the entity to authenticate as to the signaler. SignalingAuthEntity string // SignalingExternalAuthAddress is the address to perform external auth yet. // This is unlikely to be needed since the signaler is typically in the same // place where authentication happens. SignalingExternalAuthAddress string // SignalingExternalAuthToEntity is the entity to authenticate for after // externally authenticating. // This is unlikely to be needed since the signaler is typically in the same // place where authentication happens. SignalingExternalAuthToEntity string // SignalingExternalAuthInsecure is whether or not the external auth server // is insecure. // This is unlikely to be needed since the signaler is typically in the same // place where authentication happens. SignalingExternalAuthInsecure bool // SignalingCreds are used to authenticate the request to the signaling server. SignalingCreds Credentials // SignalingExternalAuthAuthMaterial is used when the credentials for the signaler // have already been used to exchange an auth payload. In those cases this can be set // to bypass the Authenticate/AuthenticateTo rpc auth flow. SignalingExternalAuthAuthMaterial string // DisableTrickleICE controls whether to disable Trickle ICE or not. // Disabling Trickle ICE can slow down connection establishment. DisableTrickleICE bool // Config is the WebRTC specific configuration (i.e. ICE settings) Config *webrtc.Configuration // AllowAutoDetectAuthOptions allows authentication options to be automatically // detected. Only use this if you trust the signaling server. AllowAutoDetectAuthOptions bool }
DialWebRTCOptions control how WebRTC is utilized in a dial attempt.
type Dialer ¶ added in v0.0.2
type Dialer interface { // DialDirect makes a connection to the given target over standard gRPC with the supplied options. DialDirect( ctx context.Context, target string, keyExtra string, onClose func() error, opts ...grpc.DialOption, ) (conn ClientConn, cached bool, err error) // DialFunc makes a connection to the given target for the given proto using the given dial function. DialFunc( proto string, target string, keyExtra string, dialNew func() (ClientConn, func() error, error), ) (conn ClientConn, cached bool, err error) // Close ensures all connections made are cleanly closed. Close() error }
A Dialer is responsible for making connections to gRPC endpoints.
func NewCachedDialer ¶ added in v0.0.2
func NewCachedDialer() Dialer
NewCachedDialer returns a Dialer that returns the same connection if it already has been established at a particular target (regardless of the options used).
type EntityDataLoader ¶ added in v0.1.17
type EntityDataLoader interface { // EntityData loads opaque info about the authenticated entity that will be bound to the // context accessible via ContextAuthEntity. EntityData(ctx context.Context, claims Claims) (interface{}, error) }
A EntityDataLoader loads data about an entity.
type EntityDataLoaderFunc ¶ added in v0.1.17
EntityDataLoaderFunc is an EntityDataLoader for entities.
func (EntityDataLoaderFunc) EntityData ¶ added in v0.1.17
func (h EntityDataLoaderFunc) EntityData(ctx context.Context, claims Claims) (interface{}, error)
EntityData checks if the given entity is handled by this handler.
type EntityInfo ¶ added in v0.1.17
type EntityInfo struct { Entity string Data interface{} }
EntityInfo provides information about a entity specific to it's credential type's entity data loader.
func ContextAuthEntity ¶ added in v0.1.17
func ContextAuthEntity(ctx context.Context) (EntityInfo, bool)
ContextAuthEntity returns the entity (e.g. a user) associated with this authentication context.
func MustContextAuthEntity ¶ added in v0.0.3
func MustContextAuthEntity(ctx context.Context) EntityInfo
MustContextAuthEntity returns the entity associated with this authentication context; it panics if there is none set.
type GrpcOverHTTPClientConn ¶ added in v0.1.67
type GrpcOverHTTPClientConn struct {
*grpc.ClientConn
}
A GrpcOverHTTPClientConn is grpc connection that is not backed by a `webrtc.PeerConnection`.
func (GrpcOverHTTPClientConn) PeerConn ¶ added in v0.1.67
func (cc GrpcOverHTTPClientConn) PeerConn() *webrtc.PeerConnection
PeerConn returns nil as this is a native gRPC connection.
type JWTClaims ¶ added in v0.0.3
type JWTClaims struct { jwt.RegisteredClaims AuthCredentialsType CredentialsType `json:"rpc_creds_type,omitempty"` AuthMetadata map[string]string `json:"rpc_auth_md,omitempty"` ApplicationID string `json:"applicationId,omitempty"` }
JWTClaims extends jwt.RegisteredClaims with information about the credentials as well as authentication metadata.
func (JWTClaims) CredentialsType ¶ added in v0.0.3
func (c JWTClaims) CredentialsType() CredentialsType
CredentialsType returns the credential type from `rpc_creds_type` claim.
type PeerConnectionInfo ¶ added in v0.1.5
type PeerConnectionInfo struct { ConnectionType PeerConnectionType LocalAddress string RemoteAddress string }
PeerConnectionInfo details information about a connection.
func PeerConnectionInfoFromContext ¶ added in v0.1.5
func PeerConnectionInfoFromContext(ctx context.Context) PeerConnectionInfo
PeerConnectionInfoFromContext returns as much information about the connection as can be found from the request context.
type PeerConnectionType ¶ added in v0.1.5
type PeerConnectionType uint16
PeerConnectionType describes the type of connection of a peer.
type PeerRole ¶ added in v0.1.84
type PeerRole bool
PeerRole identifies which role of a Client/Server relationship a peer is assuming.
type RegisterServiceHandlerFromEndpointFunc ¶ added in v0.0.2
type RegisterServiceHandlerFromEndpointFunc func( ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption, ) (err error)
A RegisterServiceHandlerFromEndpointFunc is a means to have a service attach itself to a gRPC gateway mux.
type Server ¶ added in v0.0.2
type Server interface { // InternalAddr returns the address from the listener used for // gRPC communications. It may be the same listener the server // was constructed with. InternalAddr() net.Addr // InstanceNames are the instance names this server claims to be. Typically // set via options. InstanceNames() []string // Start only starts up the internal gRPC server. Start() error // Serve will externally serve, on the given listener, the // all in one handler described by http.Handler. Serve(listener net.Listener) error // ServeTLS will externally serve, using the given cert/key, the // all in one handler described by http.Handler. The provided tlsConfig // will be used for any extra TLS settings. If using mutual TLS authentication // (see WithTLSAuthHandler), then the tls.Config should have ClientAuth, // at a minimum, set to tls.VerifyClientCertIfGiven. ServeTLS(listener net.Listener, certFile, keyFile string, tlsConfig *tls.Config) error // Stop stops the internal gRPC and the HTTP server if it // was started. Stop() error // RegisterServiceServer associates a service description with // its implementation along with any gateway handlers. RegisterServiceServer( ctx context.Context, svcDesc *grpc.ServiceDesc, svcServer interface{}, svcHandlers ...RegisterServiceHandlerFromEndpointFunc, ) error // GatewayHandler returns a handler for gateway based gRPC requests. // See: https://github.com/grpc-ecosystem/grpc-gateway GatewayHandler() http.Handler // GRPCHandler returns a handler for standard grpc/grpc-web requests which // expect to be served from a root path. GRPCHandler() http.Handler // http.Handler implemented here is an all-in-one handler for any kind of gRPC traffic. // This is useful in a scenario where all gRPC is served from the root path due to // limitations of normal gRPC being served from a non-root path. http.Handler EnsureAuthed(ctx context.Context) (context.Context, error) // Stats returns a structure containing numbers that can be interesting for graphing over time // as a diagnostics tool. Stats() any }
A Server provides a convenient way to get a gRPC server up and running with HTTP facilities.
func NewServer ¶ added in v0.0.2
func NewServer(logger utils.ZapCompatibleLogger, opts ...ServerOption) (Server, error)
NewServer returns a new server ready to be started that will listen on localhost on a random port unless TLS is turned on and authentication is enabled in which case the server will listen on all interfaces.
type ServerOption ¶ added in v0.0.2
type ServerOption interface {
// contains filtered or unexported methods
}
A ServerOption changes the runtime behavior of the server. Cribbed from https://github.com/grpc/grpc-go/blob/aff571cc86e6e7e740130dbbb32a9741558db805/dialoptions.go#L41
func WithAllowUnauthenticatedHealthCheck ¶ added in v0.1.32
func WithAllowUnauthenticatedHealthCheck() ServerOption
WithAllowUnauthenticatedHealthCheck returns a server option that allows the health check to be unauthenticated.
func WithAuthAudience ¶ added in v0.1.17
func WithAuthAudience(authAudience ...string) ServerOption
WithAuthAudience returns a ServerOption which sets the JWT audience (aud) to use/expect in all processed JWTs. When unset, it will be debug logged that the instance names will be used instead. It is recommended this option is used.
func WithAuthED25519PrivateKey ¶ added in v0.1.70
func WithAuthED25519PrivateKey(authED25519PrivateKey ed25519.PrivateKey) (ServerOption, string)
WithAuthED25519PrivateKey returns a ServerOption which sets the ed25519 private key to use for signed JWTs.
func WithAuthHandler ¶ added in v0.0.2
func WithAuthHandler(forType CredentialsType, handler AuthHandler) ServerOption
WithAuthHandler returns a ServerOption which adds an auth handler associated to the given credential type to use for authentication requests.
func WithAuthIssuer ¶ added in v0.1.17
func WithAuthIssuer(authIssuer string) ServerOption
WithAuthIssuer returns a ServerOption which sets the JWT issuer (iss) to use in all issued JWTs. When unset, it will be debug logged that the first audience member will be used instead. It is recommended this option is used.
func WithAuthRSAPrivateKey ¶ added in v0.0.2
func WithAuthRSAPrivateKey(authRSAPrivateKey *rsa.PrivateKey) (ServerOption, string, error)
WithAuthRSAPrivateKey returns a ServerOption which sets the RSA private key to use for signed JWTs.
func WithAuthenticateToHandler ¶ added in v0.0.3
func WithAuthenticateToHandler(handler AuthenticateToHandler) ServerOption
WithAuthenticateToHandler returns a ServerOption which adds an authentication handler designed to allow the caller to authenticate itself to some other entity. This is useful when externally authenticating as one entity for the purpose of getting access to another entity. Only one handler can exist and will always produce a credential type of CredentialsTypeExternal. This can technically be used internal to the same server to "assume" the identity of another entity but is not intended for such usage.
func WithDebug ¶ added in v0.0.2
func WithDebug() ServerOption
WithDebug returns a ServerOption which informs the server to be in a debug mode as much as possible.
func WithDisableMulticastDNS ¶ added in v0.0.3
func WithDisableMulticastDNS() ServerOption
WithDisableMulticastDNS returns a ServerOption which disables using mDNS to broadcast how to connect to this host.
func WithEnsureAuthedHandler ¶ added in v0.1.74
WithEnsureAuthedHandler returns a ServerOptions which adds custom logic for the ensuring of authentication on each incoming request. Can only be used in testing environments (will produce an error when ensuring authentication otherwise).
func WithEntityDataLoader ¶ added in v0.1.17
func WithEntityDataLoader(forType CredentialsType, loader EntityDataLoader) ServerOption
WithEntityDataLoader returns a ServerOption which adds an entity data loader associated to the given credential type to use for loading data after the signed access token has been verified.
func WithExternalAuthEd25519PublicKeyTokenVerifier ¶ added in v0.1.70
func WithExternalAuthEd25519PublicKeyTokenVerifier(pubKey ed25519.PublicKey) ServerOption
WithExternalAuthEd25519PublicKeyTokenVerifier returns a ServerOption to verify all externally authenticated entity access tokens with the given public key.
func WithExternalAuthJWKSetTokenVerifier ¶ added in v0.1.17
func WithExternalAuthJWKSetTokenVerifier(keySet jwks.KeySet) ServerOption
WithExternalAuthJWKSetTokenVerifier returns a ServerOption to verify all externally authenticated entity access tokens against the given JWK key set.
func WithExternalAuthOIDCTokenVerifier ¶ added in v0.1.17
func WithExternalAuthOIDCTokenVerifier(ctx context.Context, issuer string) (ServerOption, func(ctx context.Context) error, error)
WithExternalAuthOIDCTokenVerifier returns a ServerOption to verify all externally authenticated entity access tokens against the given OIDC JWT issuer that follows the OIDC Discovery protocol.
func WithExternalAuthRSAPublicKeyTokenVerifier ¶ added in v0.1.70
func WithExternalAuthRSAPublicKeyTokenVerifier(pubKey *rsa.PublicKey) ServerOption
WithExternalAuthRSAPublicKeyTokenVerifier returns a ServerOption to verify all externally authenticated entity access tokens with the given public key.
func WithExternalListenerAddress ¶ added in v0.0.3
func WithExternalListenerAddress(address *net.TCPAddr) ServerOption
WithExternalListenerAddress returns a ServerOption which sets the listener address if the server is going to be served via its handlers and not internally. This is only helpful for mDNS broadcasting. If the server has TLS enabled internally (see WithInternalTLSConfig), then the internal listener will bind everywhere and this option may not be needed.
func WithExternalTokenVerificationKeyProvider ¶ added in v0.1.17
func WithExternalTokenVerificationKeyProvider(provider TokenVerificationKeyProvider) ServerOption
WithExternalTokenVerificationKeyProvider returns a ServerOption to verify all externally authenticated entity access tokens against the given TokenVerificationKeyProvider.
func WithInstanceNames ¶ added in v0.0.3
func WithInstanceNames(names ...string) ServerOption
WithInstanceNames returns a ServerOption which sets the names for this server instance. These names will be used for auth token issuance (first name) and mDNS service discovery to report the server itself. If unset the value is the address set by WithExternalListenerAddress, WithInternalBindAddress, or the localhost and random port address, in preference order from left to right.
func WithInternalBindAddress ¶ added in v0.0.3
func WithInternalBindAddress(address string) ServerOption
WithInternalBindAddress returns a ServerOption which sets the bind address for the gRPC listener. If unset, the address is localhost on a random port unless TLS is turned on and authentication is enabled in which case the server will bind to all interfaces.
func WithInternalTLSConfig ¶ added in v0.0.3
func WithInternalTLSConfig(config *tls.Config) ServerOption
WithInternalTLSConfig returns a ServerOption which sets the TLS config for the internal listener. This is needed to have mutual TLS authentication work (see WithTLSAuthHandler). When using ServeTLS on the server, which serves from an external listener, with mutual TLS authentication, you will want to pass its own tls.Config with ClientAuth, at a minimum, set to tls.VerifyClientCertIfGiven.
func WithJWTSignerKeyID ¶ added in v0.1.70
func WithJWTSignerKeyID(keyID string) ServerOption
WithJWTSignerKeyID returns a ServerOption which sets the private key to use for signed JWTs by its key ID.
func WithPublicMethods ¶ added in v0.1.40
func WithPublicMethods(fullMethods []string) ServerOption
WithPublicMethods returns a server option with grpc methods that can bypass auth validation.
func WithStatsHandler ¶ added in v0.0.5
func WithStatsHandler(handler stats.Handler) ServerOption
WithStatsHandler returns a ServerOption which sets the stats handler on the DialOption that specifies the stats handler for all the RPCs and underlying network connections.
func WithStreamServerInterceptor ¶ added in v0.0.2
func WithStreamServerInterceptor(streamInterceptor grpc.StreamServerInterceptor) ServerOption
WithStreamServerInterceptor returns a ServerOption that sets a interceptor for all stream grpc methods registered. It will run after authentication and prior to the registered method.
func WithTLSAuthHandler ¶ added in v0.0.3
func WithTLSAuthHandler(entities []string) ServerOption
WithTLSAuthHandler returns a ServerOption which when TLS info is available to a connection, it will authenticate the given entities in the event that no other authentication has been established via the standard auth handler.
func WithTokenVerificationKeyProvider ¶ added in v0.0.2
func WithTokenVerificationKeyProvider(forType CredentialsType, provider TokenVerificationKeyProvider) ServerOption
WithTokenVerificationKeyProvider returns a ServerOption which adds a token verification key provider associated to the given credential type to use for determining an encryption key to verify signed access token prior to following through with any RPC methods or entity data loading.
func WithUnaryServerInterceptor ¶ added in v0.0.2
func WithUnaryServerInterceptor(unaryInterceptor grpc.UnaryServerInterceptor) ServerOption
WithUnaryServerInterceptor returns a ServerOption that sets a interceptor for all unary grpc methods registered. It will run after authentication and prior to the registered method.
func WithUnauthenticated ¶ added in v0.0.2
func WithUnauthenticated() ServerOption
WithUnauthenticated returns a ServerOption which turns off all authentication to the server's endpoints.
func WithUnknownServiceHandler ¶ added in v0.0.5
func WithUnknownServiceHandler(streamHandler grpc.StreamHandler) ServerOption
WithUnknownServiceHandler returns a ServerOption that allows for adding a custom unknown service handler. The provided method is a bidi-streaming RPC service handler that will be invoked instead of returning the "unimplemented" gRPC error whenever a request is received for an unregistered service or method. The handling function and stream interceptor (if set) have full access to the ServerStream, including its Context. See grpc#WithUnknownServiceHandler.
func WithWebRTCServerOptions ¶ added in v0.0.2
func WithWebRTCServerOptions(webrtcOpts WebRTCServerOptions) ServerOption
WithWebRTCServerOptions returns a ServerOption which sets the WebRTC options to use if the server sets up serving WebRTC connections.
type SimpleServerStats ¶ added in v0.1.114
type SimpleServerStats struct { TCPGrpcStats TCPGrpcStats WebRTCGrpcStats WebRTCGrpcStats }
SimpleServerStats are stats of the simple variety.
type TCPGrpcStats ¶ added in v0.1.114
type TCPGrpcStats struct { RequestsStarted int64 WebRequestsStarted int64 OtherRequestsStarted int64 RequestsCompleted int64 WebRequestsCompleted int64 OtherRequestsCompleted int64 }
TCPGrpcStats are stats for the classic tcp/http2 webserver.
type TokenVerificationKeyProvider ¶ added in v0.0.2
type TokenVerificationKeyProvider interface { // TokenVerificationKey returns the key needed to do JWT verification. TokenVerificationKey(ctx context.Context, token *jwt.Token) (interface{}, error) Close(ctx context.Context) error }
TokenVerificationKeyProvider allows an auth for a cred type to supply a key needed to peform verification of a JWT. This is helpful when the server itself is not responsible for authentication. For example, this could be for a central auth server with untrusted peers using a public key to verify JWTs.
func MakeEd25519PublicKeyProvider ¶ added in v0.1.70
func MakeEd25519PublicKeyProvider(pubKey ed25519.PublicKey) TokenVerificationKeyProvider
MakeEd25519PublicKeyProvider returns a TokenVerificationKeyProvider that provides a public key for JWT verification.
func MakeJWKSKeyProvider ¶ added in v0.1.17
func MakeJWKSKeyProvider(provider jwks.KeyProvider) TokenVerificationKeyProvider
MakeJWKSKeyProvider returns a TokenVerificationKeyProvider that dynamically looks up a public key for JWT verification by inspecting the JWT's kid field. The given JWK key provider is used to look up keys from the JWT.
func MakeOIDCKeyProvider ¶ added in v0.1.17
func MakeOIDCKeyProvider(ctx context.Context, issuer string) (TokenVerificationKeyProvider, error)
MakeOIDCKeyProvider returns a TokenVerificationKeyProvider that dynamically looks up a public key for JWT verification by inspecting the JWT's kid field. The given issuer is used to discover the JWKs used for verification. This issuer is expected to follow the OIDC Discovery protocol.
func MakeRSAPublicKeyProvider ¶ added in v0.1.70
func MakeRSAPublicKeyProvider(pubKey *rsa.PublicKey) TokenVerificationKeyProvider
MakeRSAPublicKeyProvider returns a TokenVerificationKeyProvider that provides a public key for JWT verification.
type TokenVerificationKeyProviderFunc ¶ added in v0.1.17
type TokenVerificationKeyProviderFunc func(ctx context.Context, token *jwt.Token) (interface{}, error)
TokenVerificationKeyProviderFunc is a TokenVerificationKeyProvider that provides keys for JWT verification. Note: This function MUST do checks on the token signing method for security purposes.
func (TokenVerificationKeyProviderFunc) Close ¶ added in v0.1.20
func (p TokenVerificationKeyProviderFunc) Close(ctx context.Context) error
Close does nothing.
func (TokenVerificationKeyProviderFunc) TokenVerificationKey ¶ added in v0.1.17
func (p TokenVerificationKeyProviderFunc) TokenVerificationKey(ctx context.Context, token *jwt.Token) (interface{}, error)
TokenVerificationKey returns a key that can be used to verify the given token. This is used when ensuring an RPC request is properly authenticated.
type WebRTCCallAnswer ¶ added in v0.0.2
WebRTCCallAnswer is the response to an offer. An agreement to start the call will contain an SDP about how the answerer wishes to speak.
type WebRTCCallOffer ¶ added in v0.0.2
type WebRTCCallOffer interface { // The UUID uniquely identifies this offer. UUID() string // The SDP contains initial information the caller wants to tell the answerer about. // In this case of Trickle ICE being disabled, this is an SDP with all ICE // candidate info gathered. SDP() string // DisableTrickleICE indicates if Trickle ICE should be used. Currently, both // sides must both respect this setting. DisableTrickleICE() bool // Deadline returns how long this offer has to live. Deadline() time.Time }
WebRTCCallOffer contains the information needed to offer to start a call.
type WebRTCCallOfferExchange ¶ added in v0.0.2
type WebRTCCallOfferExchange interface { WebRTCCallOffer // CallerCandidates transmits all candidates the caller discovers. CallerCandidates() <-chan webrtc.ICECandidateInit // CallerDone indicates when the caller has no more information to offer. CallerDone() <-chan struct{} // CallerErr returns any error that happened on the caller side. This should only // be called after CallerDone is done. CallerErr() error // Respond responds to the associated call offer with the given answer which contains // the SDP of the answerer or an error. AnswererRespond(ctx context.Context, ans WebRTCCallAnswer) error // AnswererDone signals that there is no more information to expect from the answerer. AnswererDone(ctx context.Context) error }
A WebRTCCallOfferExchange is used by an answerer to respond to a call offer with an answer.
type WebRTCCallQueue ¶ added in v0.0.2
type WebRTCCallQueue interface { // SendOfferInit initializes an offer associated with the given SDP to the given host. // It returns a UUID to track/authenticate the offer over time, a channel receive offer updates // on over time, and a cancel func to inform the sender to stop. SendOfferInit(ctx context.Context, host, sdp string, disableTrickle bool) ( uuid string, respCh <-chan WebRTCCallAnswer, respDone <-chan struct{}, cancel func(), err error) // SendOfferUpdate updates the offer associated with the given UUID with a newly discovered // ICE candidate. SendOfferUpdate(ctx context.Context, host, uuid string, candidate webrtc.ICECandidateInit) error // SendOfferDone informs the queue that the offer associated with the UUID is done sending any // more information. SendOfferDone(ctx context.Context, host, uuid string) error // SendOfferError informs the queue that the offer associated with the UUID has encountered // an error from the sender side. SendOfferError(ctx context.Context, host, uuid string, err error) error // RecvOffer receives the next offer for the given hosts. It should respond with an answer // once a decision is made. RecvOffer(ctx context.Context, hosts []string) (WebRTCCallOfferExchange, error) // Close shuts down the queue. Close() error }
A WebRTCCallQueue handles the transmission and reception of call offers. For every sending of an offer done, it is expected that there is someone to receive that offer and subsequently respond to it.
func NewMemoryWebRTCCallQueue ¶ added in v0.0.2
func NewMemoryWebRTCCallQueue(logger utils.ZapCompatibleLogger) WebRTCCallQueue
NewMemoryWebRTCCallQueue returns a new, empty in-memory call queue.
func NewMongoDBWebRTCCallQueue ¶ added in v0.0.2
func NewMongoDBWebRTCCallQueue( ctx context.Context, operatorID string, maxHostCallers uint64, client *mongo.Client, logger utils.ZapCompatibleLogger, activeAnswerersfunc func(hostnames []string, atTime time.Time), ) (WebRTCCallQueue, error)
NewMongoDBWebRTCCallQueue returns a new MongoDB based call queue where calls are transferred through the given client. The operator ID must be unique (e.g. a hostname, container ID, UUID, etc.). Currently, the queue can grow to an unbounded size in terms of goroutines in memory but it is expected that this code is run in an auto scaling environment that bounds how many incoming requests there can be. The given max queue size specifies how many big a queue can be for a given host; the size is used as an approximation and at times may exceed the max as a performance/consistency balance of being a distributed queue.
type WebRTCConfig ¶ added in v0.0.2
A WebRTCConfig represents a time bound WebRTC configuration.
type WebRTCConfigProvider ¶ added in v0.0.2
type WebRTCConfigProvider interface {
Config(ctx context.Context) (WebRTCConfig, error)
}
A WebRTCConfigProvider returns time bound WebRTC configurations.
type WebRTCGrpcStats ¶ added in v0.1.114
type WebRTCGrpcStats struct { PeersConnected int64 PeersDisconnected int64 PeerConnectionErrors int64 PeersActive int64 HeadersProcessed int64 CallTicketsAvailable int32 TotalTimeConnectingMillis int64 // When the FTDC frontend is more feature rich, we can remove this and let the frontend compute // the value. AverageTimeConnectingMillis float64 }
WebRTCGrpcStats are stats of the webrtc variety.
type WebRTCLoggerFactory ¶ added in v0.0.2
type WebRTCLoggerFactory struct {
Logger utils.ZapCompatibleLogger
}
WebRTCLoggerFactory wraps a utils.ZapCompatibleLogger for use with pion's webrtc logging system.
func (WebRTCLoggerFactory) NewLogger ¶ added in v0.0.2
func (lf WebRTCLoggerFactory) NewLogger(scope string) logging.LeveledLogger
NewLogger returns a new webrtc logger under the given scope.
type WebRTCServerOptions ¶ added in v0.0.2
type WebRTCServerOptions struct { // Enable controls if WebRTC should be turned on. It is disabled // by default since signaling has the potential to open up random // ports on the host which may not be expected. Enable bool // ExternalSignalingDialOpts are the options used to dial the external signaler. ExternalSignalingDialOpts []DialOption // ExternalSignalingAddress specifies where the WebRTC signaling // answerer should connect to and "listen" from. If it is empty, // it will connect to the server's internal address acting as // an answerer for itself. ExternalSignalingAddress string // EnableInternalSignaling specifies whether an internal signaling answerer // should be started up. This is useful if you want to have a fallback // server if the external cannot be reached. It is started up by default // if ExternalSignalingAddress is unset. EnableInternalSignaling bool // ExternalSignalingHosts specifies what hosts are being listened for when answering // externally. ExternalSignalingHosts []string // InternalSignalingHosts specifies what hosts are being listened for when answering // internally. InternalSignalingHosts []string // Config is the WebRTC specific configuration (i.e. ICE settings) Config *webrtc.Configuration // OnPeerAdded is called when a new peer connection is added. OnPeerAdded func(pc *webrtc.PeerConnection) // OnPeerRemoved is called when an existing peer connection is removed. OnPeerRemoved func(pc *webrtc.PeerConnection) }
WebRTCServerOptions control how WebRTC is utilized in a server.
type WebRTCSignalingServer ¶ added in v0.0.2
type WebRTCSignalingServer struct { webrtcpb.UnimplementedSignalingServiceServer // contains filtered or unexported fields }
A WebRTCSignalingServer implements a signaling service for WebRTC by exchanging SDPs (https://webrtcforthecurious.com/docs/02-signaling/#what-is-the-session-description-protocol-sdp) via gRPC. The service consists of a many-to-many interaction where there are many callers and many answerers. The callers provide an SDP to the service which asks a corresponding waiting answerer to provide an SDP in exchange in order to establish a P2P connection between the two parties. Note: authorization should happen by something wrapping this service server.
func NewWebRTCSignalingServer ¶ added in v0.0.2
func NewWebRTCSignalingServer( callQueue WebRTCCallQueue, webrtcConfigProvider WebRTCConfigProvider, logger utils.ZapCompatibleLogger, heartbeatInterval time.Duration, forHosts ...string, ) *WebRTCSignalingServer
NewWebRTCSignalingServer makes a new signaling server that uses the given call queue and looks routes based on a given robot host. If forHosts is non-empty, the server will only accept the given hosts and reject all others. The signaling server will send heartbeats to answerers at the provided heartbeatInterval if the answerer requests heartbeats through the initial Answer metadata.
func (*WebRTCSignalingServer) Answer ¶ added in v0.0.2
func (srv *WebRTCSignalingServer) Answer(server webrtcpb.SignalingService_AnswerServer) error
Answer listens on call/offer queue for a single call responding with a corresponding SDP and candidate updates/errors. Note: See SinalingAnswer.answer for the complementary side of this process.
func (*WebRTCSignalingServer) Call ¶ added in v0.0.2
func (srv *WebRTCSignalingServer) Call(req *webrtcpb.CallRequest, server webrtcpb.SignalingService_CallServer) error
Call is a request/offer to start a caller with the connected answerer.
func (*WebRTCSignalingServer) CallUpdate ¶ added in v0.0.2
func (srv *WebRTCSignalingServer) CallUpdate(ctx context.Context, req *webrtcpb.CallUpdateRequest) (*webrtcpb.CallUpdateResponse, error)
CallUpdate is used to send additional info in relation to a Call. In a world where https://github.com/grpc/grpc-web/issues/24 is fixed, this should be removed in favor of a bidirectional stream on Call.
func (*WebRTCSignalingServer) Close ¶ added in v0.1.5
func (srv *WebRTCSignalingServer) Close()
Close cancels all active workers and waits to cleanly close all background workers.
func (*WebRTCSignalingServer) OptionalWebRTCConfig ¶ added in v0.0.2
func (srv *WebRTCSignalingServer) OptionalWebRTCConfig( ctx context.Context, req *webrtcpb.OptionalWebRTCConfigRequest, ) (*webrtcpb.OptionalWebRTCConfigResponse, error)
OptionalWebRTCConfig returns any WebRTC configuration the caller may want to use.
Source Files ¶
- auth.go
- client_interceptors.go
- const.go
- context.go
- dial.go
- dial_options.go
- dialer.go
- doc.go
- json.go
- server.go
- server_auth.go
- server_interceptors.go
- server_options.go
- wrtc_base_channel.go
- wrtc_base_stream.go
- wrtc_call_queue.go
- wrtc_call_queue_memory.go
- wrtc_call_queue_mongodb.go
- wrtc_client.go
- wrtc_client_channel.go
- wrtc_client_stream.go
- wrtc_config.go
- wrtc_logger.go
- wrtc_peer.go
- wrtc_server.go
- wrtc_server_channel.go
- wrtc_server_stream.go
- wrtc_signaling.go
- wrtc_signaling_answerer.go
- wrtc_signaling_server.go
Directories ¶
Path | Synopsis |
---|---|
examples
|
|
echo/client
Package main runs a gRPC client over WebRTC connecting to the proto/rpc/examples/echo/v1 service.
|
Package main runs a gRPC client over WebRTC connecting to the proto/rpc/examples/echo/v1 service. |
echo/server
Package server implement an echo server used for testing.
|
Package server implement an echo server used for testing. |
echo/server/cmd
Package main runs a gRPC server running the proto/rpc/examples/echo/v1 service.
|
Package main runs a gRPC server running the proto/rpc/examples/echo/v1 service. |