grpc

package
v0.75.0 Latest Latest
Warning

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

Go to latest
Published: Jul 23, 2026 License: BSD-3-Clause, AGPL-3.0 Imports: 84 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ProxyTokenContextKey = proxyTokenContextKey{}

ProxyTokenContextKey is the typed key used to store validated token info in context.

Functions

func EncodeNetworkMapEnvelope added in v0.75.0

func EncodeNetworkMapEnvelope(in ComponentsEnvelopeInput) *proto.NetworkMapEnvelope

EncodeNetworkMapEnvelope converts NetworkMapComponents into the component wire envelope. The encoder is intentionally non-deterministic: it iterates Go maps in their native (random) order. Indexes inside the envelope (peer_indexes, source_group_ids, agent_version_idx, router_peer_indexes) are self-consistent within a single encode, so the decoder reconstructs the same typed objects regardless of emit order. Tests that need to compare envelopes do so semantically via proto round-trip + canonicalize, not byte-equal.

Callers must NOT concatenate or merge envelopes from different encodes — index spaces are local to a single envelope.

func GetProxyTokenFromContext added in v0.65.0

func GetProxyTokenFromContext(ctx context.Context) *types.ProxyAccessToken

GetProxyTokenFromContext retrieves the validated proxy token from the context

func NewProxyAuthInterceptors added in v0.65.0

func NewProxyAuthInterceptors(tokenStore proxyTokenStore) (grpc.UnaryServerInterceptor, grpc.StreamServerInterceptor, func())

NewProxyAuthInterceptors creates gRPC unary and stream interceptors that validate proxy access tokens. They only intercept ProxyService methods. Both interceptors share state for last-used and failure rate limiting. The returned close function must be called on shutdown to stop background goroutines.

func PeerIPFromContext added in v0.66.3

func PeerIPFromContext(ctx context.Context) string

PeerIPFromContext extracts the client IP from the gRPC context. Uses realip (from trusted proxy headers) first, falls back to the transport peer address.

func ToComponentSyncResponse added in v0.75.0

func ToComponentSyncResponse(
	ctx context.Context,
	config *nbconfig.Config,
	httpConfig *nbconfig.HttpServerConfig,
	deviceFlowConfig *nbconfig.DeviceAuthorizationFlow,
	peer *nbpeer.Peer,
	turnCredentials *Token,
	relayCredentials *Token,
	components *types.NetworkMapComponents,
	proxyPatch *types.NetworkMap,
	dnsName string,
	checks []*posture.Checks,
	settings *types.Settings,
	extraSettings *types.ExtraSettings,
	peerGroups []string,
	dnsFwdPort int64,
) *proto.SyncResponse

ToComponentSyncResponse builds a SyncResponse carrying the compact NetworkMapEnvelope for capability-aware peers. The legacy proto.NetworkMap field is intentionally left empty — capable peers ignore it and the envelope alone is the authoritative wire shape.

PeerConfig is computed once server-side using the receiving peer's own account-level network metadata. EnableSSH inside PeerConfig is left at peer.SSHEnabled (the peer's local setting); account-policy-driven SSH is computed by the client from the envelope's GroupIDToUserIDs / AllowedUserIDs inside Calculate(), so the SshConfig.SshEnabled bit may flip true on the client even though the server-side PeerConfig reports false.

func ToResponseProto

func ToResponseProto(configProto nbconfig.Protocol) proto.HostConfig_Protocol

func ToSyncResponse

func ToSyncResponse(ctx context.Context, config *nbconfig.Config, httpConfig *nbconfig.HttpServerConfig, deviceFlowConfig *nbconfig.DeviceAuthorizationFlow, peer *nbpeer.Peer, turnCredentials *Token, relayCredentials *Token, networkMap *types.NetworkMap, dnsName string, checks []*posture.Checks, dnsCache *cache.DNSConfigCache, settings *types.Settings, extraSettings *types.ExtraSettings, peerGroups []string, dnsFwdPort int64) *proto.SyncResponse

Types

type AgentNetworkLimitsService added in v0.74.0

type AgentNetworkLimitsService interface {
	SelectPolicyForRequest(ctx context.Context, in agentnetwork.PolicySelectionInput) (*agentnetwork.PolicySelectionResult, error)
	RecordUsage(ctx context.Context, in agentnetwork.RecordUsageInput) error
}

AgentNetworkLimitsService is the minimal slice of agentnetwork.Manager the gRPC layer needs for CheckLLMPolicyLimits + RecordLLMUsage — kept narrow so the grpc package doesn't take a hard import on the full manager.

type AgentNetworkSynthesizer added in v0.74.0

type AgentNetworkSynthesizer interface {
	SynthesizeServicesForCluster(ctx context.Context, clusterAddr string) ([]*rpservice.Service, error)
	SynthesizeServicesForAccount(ctx context.Context, accountID string) ([]*rpservice.Service, error)
	SynthesizeServiceForDomain(ctx context.Context, domain string) (*rpservice.Service, error)
}

ProxyServiceServer implements the ProxyService gRPC server AgentNetworkSynthesizer produces in-memory reverse-proxy services from Agent Network provider/policy state for the proxy snapshot path; synthesised services never appear in the reverseproxy_services table.

type ComponentsEnvelopeInput added in v0.75.0

type ComponentsEnvelopeInput struct {
	Components       *types.NetworkMapComponents
	PeerConfig       *proto.PeerConfig
	DNSDomain        string
	DNSForwarderPort int64
	// UserIDClaim is the OIDC claim name the client should embed in
	// SshAuth.UserIDClaim when reconstructing the NetworkMap. Empty value
	// is OK — client treats empty as "no SshAuth to build".
	UserIDClaim string
	// ProxyPatch carries pre-expanded NetworkMap fragments injected by
	// external controllers (BYOP/port-forwarding). Nil when no proxy data
	// is present; encoder skips the field in that case.
	ProxyPatch *proto.ProxyPatch
}

ComponentsEnvelopeInput bundles the data the component-format encoder needs. The envelope is fully self-contained — every field needed by the client's local Calculate() comes from the components struct itself. The only externally-supplied data is the receiving peer's PeerConfig (which is computed alongside the components in the network_map controller and reused from the legacy proto path) and the dns_domain string.

type OneTimeTokenStore added in v0.65.0

type OneTimeTokenStore struct {
	// contains filtered or unexported fields
}

OneTimeTokenStore manages single-use authentication tokens for proxy-to-management RPC. Supports both in-memory and Redis storage via NB_IDP_CACHE_REDIS_ADDRESS env var.

func NewOneTimeTokenStore added in v0.65.0

func NewOneTimeTokenStore(ctx context.Context, cacheStore store.StoreInterface) *OneTimeTokenStore

NewOneTimeTokenStore creates a token store using the provided shared cache store.

func (*OneTimeTokenStore) GenerateToken added in v0.65.0

func (s *OneTimeTokenStore) GenerateToken(accountID, serviceID string, ttl time.Duration) (string, error)

GenerateToken creates a new cryptographically secure one-time token with the specified TTL. The token is associated with a specific accountID and serviceID for validation purposes.

Returns the generated token string or an error if random generation fails.

func (*OneTimeTokenStore) ValidateAndConsume added in v0.65.0

func (s *OneTimeTokenStore) ValidateAndConsume(token, accountID, serviceID string) error

ValidateAndConsume verifies the token against the provided accountID and serviceID, checks expiration, and then deletes it to enforce single-use.

This method uses constant-time comparison to prevent timing attacks.

Returns nil on success, or an error if: - Token doesn't exist - Token has expired - Account ID doesn't match - Reverse proxy ID doesn't match

type PKCEVerifierStore added in v0.66.3

type PKCEVerifierStore struct {
	// contains filtered or unexported fields
}

PKCEVerifierStore manages PKCE verifiers for OAuth flows. Supports both in-memory and Redis storage via NB_IDP_CACHE_REDIS_ADDRESS env var.

func NewPKCEVerifierStore added in v0.66.3

func NewPKCEVerifierStore(ctx context.Context, cacheStore store.StoreInterface) *PKCEVerifierStore

NewPKCEVerifierStore creates a PKCE verifier store using the provided shared cache store.

func (*PKCEVerifierStore) LoadAndDelete added in v0.66.3

func (s *PKCEVerifierStore) LoadAndDelete(state string) (string, bool)

LoadAndDelete retrieves and removes a PKCE verifier for the given state. Returns the verifier and true if found, or empty string and false if not found. This enforces single-use semantics for PKCE verifiers.

func (*PKCEVerifierStore) Store added in v0.66.3

func (s *PKCEVerifierStore) Store(state, verifier string, ttl time.Duration) error

Store saves a PKCE verifier associated with an OAuth state parameter. The verifier is stored with the specified TTL and will be automatically deleted after expiration.

type ProxyOIDCConfig added in v0.65.0

type ProxyOIDCConfig struct {
	Issuer      string
	ClientID    string
	Scopes      []string
	CallbackURL string
	HMACKey     []byte

	Audience     string
	KeysLocation string
}

type ProxyServiceServer added in v0.65.0

type ProxyServiceServer struct {
	proto.UnimplementedProxyServiceServer
	// contains filtered or unexported fields
}

func NewProxyServiceServer added in v0.65.0

func NewProxyServiceServer(accessLogMgr accesslogs.Manager, tokenStore *OneTimeTokenStore, pkceStore *PKCEVerifierStore, oidcConfig ProxyOIDCConfig, peersManager peers.Manager, usersManager users.Manager, idpManager idp.Manager, proxyMgr proxy.Manager, tokenChecker ProxyTokenChecker) *ProxyServiceServer

NewProxyServiceServer creates a new proxy service server.

func (*ProxyServiceServer) Authenticate added in v0.65.0

func (*ProxyServiceServer) CheckLLMPolicyLimits added in v0.74.0

CheckLLMPolicyLimits is the pre-flight policy gate the proxy calls before forwarding an LLM request upstream. Delegates to the agent-network selector, which scores applicable policies by remaining headroom and returns the policy that pays for this request (or a deny when all are exhausted).

func (*ProxyServiceServer) Close added in v0.65.0

func (s *ProxyServiceServer) Close()

Close stops background goroutines.

func (*ProxyServiceServer) CreateProxyPeer added in v0.65.0

CreateProxyPeer handles proxy peer creation with one-time token authentication

func (*ProxyServiceServer) ForceDisconnect added in v0.71.0

func (s *ProxyServiceServer) ForceDisconnect(proxyID string)

ForceDisconnect cancels the gRPC stream for a connected proxy, causing it to disconnect.

func (*ProxyServiceServer) GenerateSessionToken added in v0.65.0

func (s *ProxyServiceServer) GenerateSessionToken(ctx context.Context, domain, userID string, method proxyauth.Method) (string, error)

GenerateSessionToken creates a signed session JWT for the given domain and user. The user's group memberships are embedded in the token so policy-aware middlewares on the proxy can authorise without an extra management round-trip.

func (*ProxyServiceServer) GetConnectedProxies added in v0.65.0

func (s *ProxyServiceServer) GetConnectedProxies() []string

GetConnectedProxies returns a list of connected proxy IDs

func (*ProxyServiceServer) GetConnectedProxyURLs added in v0.65.0

func (s *ProxyServiceServer) GetConnectedProxyURLs() []string

GetConnectedProxyURLs returns a deduplicated list of URLs from all connected proxies.

func (*ProxyServiceServer) GetMappingUpdate added in v0.65.0

GetMappingUpdate handles the control stream with proxy clients

func (*ProxyServiceServer) GetOIDCConfig added in v0.65.0

func (s *ProxyServiceServer) GetOIDCConfig() ProxyOIDCConfig

GetOIDCConfig returns the OIDC configuration for token validation.

func (*ProxyServiceServer) GetOIDCURL added in v0.65.0

func (*ProxyServiceServer) GetOIDCValidationConfig added in v0.65.0

func (s *ProxyServiceServer) GetOIDCValidationConfig() proxy.OIDCValidationConfig

GetOIDCValidationConfig returns the OIDC configuration for token validation in the format needed by ToProtoMapping.

func (*ProxyServiceServer) RecordLLMUsage added in v0.74.0

RecordLLMUsage increments the per-(dimension, window) consumption counter for the user and optional attribution group after a served request. Returns Unimplemented when the agent-network limits service hasn't been wired.

func (*ProxyServiceServer) SendAccessLog added in v0.65.0

SendAccessLog processes access log from proxy

func (*ProxyServiceServer) SendServiceUpdate added in v0.65.0

func (s *ProxyServiceServer) SendServiceUpdate(update *proto.GetMappingUpdateResponse)

SendServiceUpdate broadcasts a service update to all connected proxy servers. Management should call this when services are created/updated/removed. For create/update operations a unique one-time auth token is generated per proxy so that every replica can independently authenticate with management. BYOP proxies only receive updates for their own account's services.

func (*ProxyServiceServer) SendServiceUpdateToCluster added in v0.65.0

func (s *ProxyServiceServer) SendServiceUpdateToCluster(ctx context.Context, update *proto.ProxyMapping, clusterAddr string)

SendServiceUpdateToCluster sends a service update to all proxy servers in a specific cluster. If clusterAddr is empty, broadcasts to all connected proxy servers (backward compatibility). For create/update operations a unique one-time auth token is generated per proxy so that every replica can independently authenticate with management.

func (*ProxyServiceServer) SendStatusUpdate added in v0.65.0

SendStatusUpdate handles status updates from proxy clients.

func (*ProxyServiceServer) SetAgentNetworkLimitsService added in v0.74.0

func (s *ProxyServiceServer) SetAgentNetworkLimitsService(svc AgentNetworkLimitsService)

SetAgentNetworkLimitsService wires the policy-selection + post-flight consumption sink. Pass nil to disable; both RPCs return Unimplemented while unset so partial wiring surfaces during integration.

func (*ProxyServiceServer) SetAgentNetworkSynthesizer added in v0.74.0

func (s *ProxyServiceServer) SetAgentNetworkSynthesizer(synth AgentNetworkSynthesizer)

SetAgentNetworkSynthesizer wires the agent-network service synthesiser. Optional — when nil the snapshot path skips agent-network synthesis. The modules layer injects this after both the proxy server and the agent-network manager are constructed.

func (*ProxyServiceServer) SetProxyController added in v0.66.2

func (s *ProxyServiceServer) SetProxyController(proxyController proxy.Controller)

SetProxyController sets the proxy controller. Must be called before serving.

func (*ProxyServiceServer) SetServiceManager added in v0.66.2

func (s *ProxyServiceServer) SetServiceManager(manager rpservice.Manager)

SetServiceManager sets the service manager. Must be called before serving.

func (*ProxyServiceServer) SyncMappings added in v0.71.3

SyncMappings implements the bidirectional SyncMappings RPC. It mirrors GetMappingUpdate but provides application-level back-pressure: management waits for an ack from the proxy before sending the next batch.

func (*ProxyServiceServer) ValidateSession added in v0.65.0

ValidateSession validates a session token and checks if the user has access to the domain.

func (*ProxyServiceServer) ValidateState added in v0.65.0

func (s *ProxyServiceServer) ValidateState(state string) (verifier, redirectURL string, err error)

ValidateState validates the state parameter from an OAuth callback. Returns the original redirect URL if valid, or an error if invalid. The HMAC is verified before consuming the PKCE verifier to prevent an attacker from invalidating a legitimate user's auth flow.

func (*ProxyServiceServer) ValidateTunnelPeer added in v0.72.0

ValidateTunnelPeer resolves an inbound peer by its WireGuard tunnel IP and checks the peer's group membership against the service's access groups. Peers without a user (machine agents, automation workloads) are first-class callers; authorisation runs off peer-group memberships rather than the optional owning user's auto-groups. On success a session JWT is minted so the proxy can install a cookie and skip subsequent management round-trips.

func (*ProxyServiceServer) ValidateUserGroupAccess added in v0.65.0

func (s *ProxyServiceServer) ValidateUserGroupAccess(ctx context.Context, domain, userID string) error

ValidateUserGroupAccess checks if a user has access to a service. It looks up the service within the user's account only, then optionally checks group membership if BearerAuth with DistributionGroups is configured.

type ProxyTokenChecker added in v0.71.0

type ProxyTokenChecker interface {
	IsProxyAccessTokenValid(ctx context.Context, tokenID string) (bool, error)
}

ProxyTokenChecker checks whether a proxy access token is still valid.

type SecretsManager

type SecretsManager interface {
	GenerateTurnToken() (*Token, error)
	GenerateRelayToken() (*Token, error)
	SetupRefresh(ctx context.Context, accountID, peerKey string)
	CancelRefresh(peerKey string)
	GetWGKey() (wgtypes.Key, error)
}

SecretsManager used to manage TURN and relay secrets

type Server

type Server struct {
	proto.UnimplementedManagementServiceServer
	// contains filtered or unexported fields
}

Server an instance of a Management gRPC API server

func NewServer

func NewServer(
	config *nbconfig.Config,
	accountManager account.Manager,
	settingsManager settings.Manager,
	jobManager *job.Manager,
	secretsManager SecretsManager,
	appMetrics telemetry.AppMetrics,
	authManager auth.Manager,
	integratedPeerValidator integrated_validator.IntegratedValidator,
	networkMapController network_map.Controller,
	oAuthConfigProvider idp.OAuthConfigProvider,
	sessionStore *auth.SessionStore,
) (*Server, error)

NewServer creates a new Management server

func (*Server) CreateExpose added in v0.66.0

func (s *Server) CreateExpose(ctx context.Context, req *proto.EncryptedMessage) (*proto.EncryptedMessage, error)

CreateExpose handles a peer request to create a new expose service.

func (*Server) ExtendAuthSession added in v0.72.0

func (s *Server) ExtendAuthSession(ctx context.Context, req *proto.EncryptedMessage) (*proto.EncryptedMessage, error)

ExtendAuthSession refreshes the peer's SSO session expiry deadline using a fresh JWT. The same JWT validation pipeline as Login is used. The tunnel stays up; no network map sync is performed. The new deadline is returned in ExtendAuthSessionResponse.SessionExpiresAt.

func (*Server) GetDeviceAuthorizationFlow

func (s *Server) GetDeviceAuthorizationFlow(ctx context.Context, req *proto.EncryptedMessage) (*proto.EncryptedMessage, error)

GetDeviceAuthorizationFlow returns a device authorization flow information This is used for initiating an Oauth 2 device authorization grant flow which will be used by our clients to Login

func (*Server) GetPKCEAuthorizationFlow

func (s *Server) GetPKCEAuthorizationFlow(ctx context.Context, req *proto.EncryptedMessage) (*proto.EncryptedMessage, error)

GetPKCEAuthorizationFlow returns a pkce authorization flow information This is used for initiating an Oauth 2 pkce authorization grant flow which will be used by our clients to Login

func (*Server) GetServerKey

func (s *Server) GetServerKey(ctx context.Context, req *proto.Empty) (*proto.ServerKeyResponse, error)

func (*Server) IsHealthy

func (s *Server) IsHealthy(ctx context.Context, req *proto.Empty) (*proto.Empty, error)

IsHealthy indicates whether the service is healthy

func (*Server) Job added in v0.64.0

func (*Server) Login

Login endpoint first checks whether peer is registered under any account In case it is, the login is successful In case it isn't, the endpoint checks whether setup key is provided within the request and tries to register a peer. In case of the successful registration login is also successful

func (*Server) Logout

func (s *Server) Logout(ctx context.Context, req *proto.EncryptedMessage) (*proto.Empty, error)

func (*Server) RenewExpose added in v0.66.0

func (s *Server) RenewExpose(ctx context.Context, req *proto.EncryptedMessage) (*proto.EncryptedMessage, error)

RenewExpose extends the TTL of an active expose session.

func (*Server) SetReverseProxyManager added in v0.66.0

func (s *Server) SetReverseProxyManager(mgr rpservice.Manager)

SetReverseProxyManager sets the reverse proxy manager on the server.

func (*Server) StopExpose added in v0.66.0

func (s *Server) StopExpose(ctx context.Context, req *proto.EncryptedMessage) (*proto.EncryptedMessage, error)

StopExpose terminates an active expose session.

func (*Server) Sync

Sync validates the existence of a connecting peer, sends an initial state (all available for the connecting peers) and notifies the connected peer of any updates (e.g. new peers under the same account)

func (*Server) SyncMeta

func (s *Server) SyncMeta(ctx context.Context, req *proto.EncryptedMessage) (*proto.Empty, error)

SyncMeta endpoint is used to synchronize peer's system metadata and notifies the connected, peer's under the same account of any updates.

type TimeBasedAuthSecretsManager

type TimeBasedAuthSecretsManager struct {
	// contains filtered or unexported fields
}

TimeBasedAuthSecretsManager generates credentials with TTL and using pre-shared secret known to TURN server

func NewTimeBasedAuthSecretsManager

func NewTimeBasedAuthSecretsManager(updateManager network_map.PeersUpdateManager, turnCfg *nbconfig.TURNConfig, relayCfg *nbconfig.Relay, settingsManager settings.Manager, groupsManager groups.Manager) (*TimeBasedAuthSecretsManager, error)

func (*TimeBasedAuthSecretsManager) CancelRefresh

func (m *TimeBasedAuthSecretsManager) CancelRefresh(peerID string)

CancelRefresh cancels scheduled peer credentials refresh

func (*TimeBasedAuthSecretsManager) GenerateRelayToken

func (m *TimeBasedAuthSecretsManager) GenerateRelayToken() (*Token, error)

GenerateRelayToken generates new time-based secret credentials for relay

func (*TimeBasedAuthSecretsManager) GenerateTurnToken

func (m *TimeBasedAuthSecretsManager) GenerateTurnToken() (*Token, error)

GenerateTurnToken generates new time-based secret credentials for TURN

func (*TimeBasedAuthSecretsManager) GetWGKey added in v0.60.5

func (m *TimeBasedAuthSecretsManager) GetWGKey() (wgtypes.Key, error)

GetWGKey returns WireGuard private key used to generate peer keys

func (*TimeBasedAuthSecretsManager) SetupRefresh

func (m *TimeBasedAuthSecretsManager) SetupRefresh(ctx context.Context, accountID, peerID string)

SetupRefresh starts peer credentials refresh

type Token

type Token auth.Token

type UpdateDebouncer added in v0.64.6

type UpdateDebouncer struct {
	// contains filtered or unexported fields
}

UpdateDebouncer implements a backpressure mechanism that: - Sends the first update immediately - Coalesces rapid subsequent network map updates (only latest matters) - Queues control/config updates (all must be delivered) - Preserves the order of messages (important for control configs between network maps) - Ensures pending updates are sent after a quiet period

func NewUpdateDebouncer added in v0.64.6

func NewUpdateDebouncer(interval time.Duration) *UpdateDebouncer

NewUpdateDebouncer creates a new debouncer with the specified interval

func (*UpdateDebouncer) GetPendingUpdates added in v0.64.6

func (d *UpdateDebouncer) GetPendingUpdates() []*network_map.UpdateMessage

GetPendingUpdates returns and clears all pending updates after timer expiration. Updates are returned in the order they were received, with consecutive network maps already coalesced to only the latest one. If there were pending updates, it restarts the timer to continue debouncing. If there were no pending updates, it clears the timer (true quiet period).

func (*UpdateDebouncer) ProcessUpdate added in v0.64.6

func (d *UpdateDebouncer) ProcessUpdate(update *network_map.UpdateMessage) bool

ProcessUpdate handles an incoming update and returns whether it should be sent immediately

func (*UpdateDebouncer) Stop added in v0.64.6

func (d *UpdateDebouncer) Stop()

Stop stops the debouncer and cleans up resources

func (*UpdateDebouncer) TimerChannel added in v0.64.6

func (d *UpdateDebouncer) TimerChannel() <-chan time.Time

TimerChannel returns the timer channel for select statements

Jump to

Keyboard shortcuts

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