mirror of
https://github.com/netbirdio/netbird.git
synced 2026-09-17 12:19:07 +02:00
Adds a new "private" service mode for the reverse proxy: services reachable exclusively over the embedded WireGuard tunnel, gated by per-peer group membership instead of operator auth schemes. Wire contract - ProxyMapping.private (field 13): the proxy MUST call ValidateTunnelPeer and fail closed; operator schemes are bypassed. - ProxyCapabilities.private (4) + supports_private_service (5): capability gate. Management never streams private mappings to proxies that don't claim the capability; the broadcast path applies the same filter via filterMappingsForProxy. - ValidateTunnelPeer RPC: resolves an inbound tunnel IP to a peer, checks the peer's groups against service.AccessGroups, and mints a session JWT on success. checkPeerGroupAccess fails closed when a private service has empty AccessGroups. - ValidateSession/ValidateTunnelPeer responses now carry peer_group_ids + peer_group_names so the proxy can authorise policy-aware middlewares without an extra management round-trip. - ProxyInboundListener + SendStatusUpdate.inbound_listener: per-account inbound listener state surfaced to dashboards. - PathTargetOptions.direct_upstream (11): bypass the embedded NetBird client and dial the target via the proxy host's network stack for upstreams reachable without WireGuard. Data model - Service.Private (bool) + Service.AccessGroups ([]string, JSON- serialised). Validate() rejects bearer auth on private services. Copy() deep-copies AccessGroups. pgx getServices loads the columns. - DomainConfig.Private threaded into the proxy auth middleware. Request handler routes private services through forwardWithTunnelPeer and returns 403 on validation failure. - Account-level SynthesizePrivateServiceZones (synthetic DNS) and injectPrivateServicePolicies (synthetic ACL) gate on len(svc.AccessGroups) > 0. Proxy - /netbird proxy --private (embedded mode) flag; Config.Private in proxy/lifecycle.go. - Per-account inbound listener (proxy/inbound.go) binding HTTP/HTTPS on the embedded NetBird client's WireGuard tunnel netstack. - proxy/internal/auth/tunnel_cache: ValidateTunnelPeer response cache with single-flight de-duplication and per-account eviction. - Local peerstore short-circuit: when the inbound IP isn't in the account roster, deny fast without an RPC. - proxy/server.go reports SupportsPrivateService=true and redacts the full ProxyMapping JSON from info logs (auth_token + header-auth hashed values now only at debug level). Identity forwarding - ValidateSessionJWT returns user_id, email, method, groups, group_names. sessionkey.Claims carries Email + Groups + GroupNames so the proxy can stamp identity onto upstream requests without an extra management round-trip on every cookie-bearing request. - CapturedData carries userEmail / userGroups / userGroupNames; the proxy stamps X-NetBird-User and X-NetBird-Groups on r.Out from the authenticated identity (strips client-supplied values first to prevent spoofing). - AccessLog.UserGroups: access-log enrichment captures the user's group memberships at write time so the dashboard can render group context without reverse-resolving stale memberships. OpenAPI/dashboard surface - ReverseProxyService gains private + access_groups; ReverseProxyCluster gains private + supports_private. ReverseProxyTarget target_type enum gains "cluster". ServiceTargetOptions gains direct_upstream. ProxyAccessLog gains user_groups.
252 lines
9.4 KiB
Go
252 lines
9.4 KiB
Go
package peers
|
|
|
|
//go:generate go run github.com/golang/mock/mockgen -package peers -destination=manager_mock.go -source=./manager.go -build_flags=-mod=mod
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"net"
|
|
"time"
|
|
|
|
"github.com/rs/xid"
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
"github.com/netbirdio/netbird/management/internals/controllers/network_map"
|
|
"github.com/netbirdio/netbird/management/internals/modules/peers/ephemeral"
|
|
"github.com/netbirdio/netbird/management/server/account"
|
|
"github.com/netbirdio/netbird/management/server/activity"
|
|
"github.com/netbirdio/netbird/management/server/integrations/integrated_validator"
|
|
"github.com/netbirdio/netbird/management/server/peer"
|
|
"github.com/netbirdio/netbird/management/server/permissions"
|
|
"github.com/netbirdio/netbird/management/server/permissions/modules"
|
|
"github.com/netbirdio/netbird/management/server/permissions/operations"
|
|
"github.com/netbirdio/netbird/management/server/store"
|
|
"github.com/netbirdio/netbird/management/server/types"
|
|
"github.com/netbirdio/netbird/shared/management/status"
|
|
)
|
|
|
|
type Manager interface {
|
|
GetPeer(ctx context.Context, accountID, userID, peerID string) (*peer.Peer, error)
|
|
GetPeerAccountID(ctx context.Context, peerID string) (string, error)
|
|
GetAllPeers(ctx context.Context, accountID, userID string) ([]*peer.Peer, error)
|
|
GetPeersByGroupIDs(ctx context.Context, accountID string, groupsIDs []string) ([]*peer.Peer, error)
|
|
DeletePeers(ctx context.Context, accountID string, peerIDs []string, userID string, checkConnected bool) error
|
|
SetNetworkMapController(networkMapController network_map.Controller)
|
|
SetIntegratedPeerValidator(integratedPeerValidator integrated_validator.IntegratedValidator)
|
|
SetAccountManager(accountManager account.Manager)
|
|
GetPeerID(ctx context.Context, peerKey string) (string, error)
|
|
CreateProxyPeer(ctx context.Context, accountID string, peerKey string, cluster string) error
|
|
// GetPeerByTunnelIP looks up a peer in accountID by its WireGuard tunnel IP.
|
|
// Returns nil with an error when no match exists. No permission check;
|
|
// callers (the proxy's ValidateTunnelPeer RPC) are trusted server components.
|
|
GetPeerByTunnelIP(ctx context.Context, accountID string, ip net.IP) (*peer.Peer, error)
|
|
// GetPeerWithGroups returns the peer and the list of *types.Group it belongs
|
|
// to. Used by the proxy's auth path to authorise a request by the calling
|
|
// peer's group memberships.
|
|
GetPeerWithGroups(ctx context.Context, accountID, peerID string) (*peer.Peer, []*types.Group, error)
|
|
}
|
|
|
|
type managerImpl struct {
|
|
store store.Store
|
|
permissionsManager permissions.Manager
|
|
integratedPeerValidator integrated_validator.IntegratedValidator
|
|
accountManager account.Manager
|
|
|
|
networkMapController network_map.Controller
|
|
}
|
|
|
|
func NewManager(store store.Store, permissionsManager permissions.Manager) Manager {
|
|
return &managerImpl{
|
|
store: store,
|
|
permissionsManager: permissionsManager,
|
|
}
|
|
}
|
|
|
|
func (m *managerImpl) SetNetworkMapController(networkMapController network_map.Controller) {
|
|
m.networkMapController = networkMapController
|
|
}
|
|
|
|
func (m *managerImpl) SetIntegratedPeerValidator(integratedPeerValidator integrated_validator.IntegratedValidator) {
|
|
m.integratedPeerValidator = integratedPeerValidator
|
|
}
|
|
|
|
func (m *managerImpl) SetAccountManager(accountManager account.Manager) {
|
|
m.accountManager = accountManager
|
|
}
|
|
|
|
func (m *managerImpl) GetPeer(ctx context.Context, accountID, userID, peerID string) (*peer.Peer, error) {
|
|
allowed, err := m.permissionsManager.ValidateUserPermissions(ctx, accountID, userID, modules.Peers, operations.Read)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to validate user permissions: %w", err)
|
|
}
|
|
|
|
if !allowed {
|
|
return nil, status.NewPermissionDeniedError()
|
|
}
|
|
|
|
return m.store.GetPeerByID(ctx, store.LockingStrengthNone, accountID, peerID)
|
|
}
|
|
|
|
func (m *managerImpl) GetAllPeers(ctx context.Context, accountID, userID string) ([]*peer.Peer, error) {
|
|
allowed, err := m.permissionsManager.ValidateUserPermissions(ctx, accountID, userID, modules.Peers, operations.Read)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to validate user permissions: %w", err)
|
|
}
|
|
|
|
if !allowed {
|
|
return m.store.GetUserPeers(ctx, store.LockingStrengthNone, accountID, userID)
|
|
}
|
|
|
|
return m.store.GetAccountPeers(ctx, store.LockingStrengthNone, accountID, "", "")
|
|
}
|
|
|
|
func (m *managerImpl) GetPeerAccountID(ctx context.Context, peerID string) (string, error) {
|
|
return m.store.GetAccountIDByPeerID(ctx, store.LockingStrengthNone, peerID)
|
|
}
|
|
|
|
func (m *managerImpl) GetPeersByGroupIDs(ctx context.Context, accountID string, groupsIDs []string) ([]*peer.Peer, error) {
|
|
return m.store.GetPeersByGroupIDs(ctx, accountID, groupsIDs)
|
|
}
|
|
|
|
// GetPeerByTunnelIP delegates to the store's indexed lookup.
|
|
func (m *managerImpl) GetPeerByTunnelIP(ctx context.Context, accountID string, ip net.IP) (*peer.Peer, error) {
|
|
return m.store.GetPeerByIP(ctx, store.LockingStrengthNone, accountID, ip)
|
|
}
|
|
|
|
// GetPeerWithGroups returns the peer plus its group memberships. Any store
|
|
// error returns (nil, nil, err) so callers never receive a valid peer
|
|
// alongside a non-nil error.
|
|
func (m *managerImpl) GetPeerWithGroups(ctx context.Context, accountID, peerID string) (*peer.Peer, []*types.Group, error) {
|
|
p, err := m.store.GetPeerByID(ctx, store.LockingStrengthNone, accountID, peerID)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
groups, err := m.store.GetPeerGroups(ctx, store.LockingStrengthNone, accountID, peerID)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
return p, groups, nil
|
|
}
|
|
|
|
func (m *managerImpl) DeletePeers(ctx context.Context, accountID string, peerIDs []string, userID string, checkConnected bool) error {
|
|
settings, err := m.store.GetAccountSettings(ctx, store.LockingStrengthNone, accountID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
dnsDomain := m.networkMapController.GetDNSDomain(settings)
|
|
|
|
for _, peerID := range peerIDs {
|
|
var eventsToStore []func()
|
|
err = m.store.ExecuteInTransaction(ctx, func(transaction store.Store) error {
|
|
peer, err := transaction.GetPeerByID(ctx, store.LockingStrengthNone, accountID, peerID)
|
|
if err != nil {
|
|
if e, ok := status.FromError(err); ok && e.Type() == status.NotFound {
|
|
log.WithContext(ctx).Tracef("DeletePeers: peer %s not found, skipping", peerID)
|
|
return nil
|
|
}
|
|
return err
|
|
}
|
|
|
|
if checkConnected && (peer.Status.Connected || peer.Status.LastSeen.After(time.Now().Add(-(ephemeral.EphemeralLifeTime - 10*time.Second)))) {
|
|
log.WithContext(ctx).Tracef("DeletePeers: peer %s skipped (connected=%t, lastSeen=%s, threshold=%s, ephemeral=%t)",
|
|
peerID, peer.Status.Connected,
|
|
peer.Status.LastSeen.Format(time.RFC3339),
|
|
time.Now().Add(-(ephemeral.EphemeralLifeTime - 10*time.Second)).Format(time.RFC3339),
|
|
peer.Ephemeral)
|
|
return nil
|
|
}
|
|
|
|
if err := transaction.RemovePeerFromAllGroups(ctx, peerID); err != nil {
|
|
return fmt.Errorf("failed to remove peer %s from groups", peerID)
|
|
}
|
|
|
|
peerPolicyRules, err := transaction.GetPolicyRulesByResourceID(ctx, store.LockingStrengthNone, accountID, peerID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, rule := range peerPolicyRules {
|
|
policy, err := transaction.GetPolicyByID(ctx, store.LockingStrengthNone, accountID, rule.PolicyID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
err = transaction.DeletePolicy(ctx, accountID, rule.PolicyID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
eventsToStore = append(eventsToStore, func() {
|
|
m.accountManager.StoreEvent(ctx, userID, peer.ID, accountID, activity.PolicyRemoved, policy.EventMeta())
|
|
})
|
|
}
|
|
|
|
if err = transaction.DeletePeer(ctx, accountID, peerID); err != nil {
|
|
return err
|
|
}
|
|
|
|
if !(peer.ProxyMeta.Embedded || peer.Meta.KernelVersion == "wasm") {
|
|
eventsToStore = append(eventsToStore, func() {
|
|
m.accountManager.StoreEvent(ctx, userID, peer.ID, accountID, activity.PeerRemovedByUser, peer.EventMeta(dnsDomain))
|
|
})
|
|
}
|
|
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
log.WithContext(ctx).Errorf("DeletePeers: failed to delete peer %s: %v", peerID, err)
|
|
continue
|
|
}
|
|
|
|
if m.integratedPeerValidator != nil {
|
|
if err = m.integratedPeerValidator.PeerDeleted(ctx, accountID, peerID, settings.Extra); err != nil {
|
|
log.WithContext(ctx).Errorf("failed to delete peer %s from integrated validator: %v", peerID, err)
|
|
}
|
|
}
|
|
|
|
for _, event := range eventsToStore {
|
|
event()
|
|
}
|
|
}
|
|
|
|
m.accountManager.UpdateAccountPeers(ctx, accountID, types.UpdateReason{Resource: types.UpdateResourcePeer, Operation: types.UpdateOperationDelete})
|
|
|
|
return nil
|
|
}
|
|
|
|
func (m *managerImpl) GetPeerID(ctx context.Context, peerKey string) (string, error) {
|
|
return m.store.GetPeerIDByKey(ctx, store.LockingStrengthNone, peerKey)
|
|
}
|
|
|
|
func (m *managerImpl) CreateProxyPeer(ctx context.Context, accountID string, peerKey string, cluster string) error {
|
|
existingPeerID, err := m.store.GetPeerIDByKey(ctx, store.LockingStrengthNone, peerKey)
|
|
if err == nil && existingPeerID != "" {
|
|
// Peer already exists
|
|
return nil
|
|
}
|
|
|
|
name := fmt.Sprintf("proxy-%s", xid.New().String())
|
|
peer := &peer.Peer{
|
|
Ephemeral: true,
|
|
ProxyMeta: peer.ProxyMeta{
|
|
Cluster: cluster,
|
|
Embedded: true,
|
|
},
|
|
Name: name,
|
|
Key: peerKey,
|
|
LoginExpirationEnabled: false,
|
|
InactivityExpirationEnabled: false,
|
|
Meta: peer.PeerSystemMeta{
|
|
Hostname: name,
|
|
GoOS: "proxy",
|
|
OS: "proxy",
|
|
},
|
|
}
|
|
|
|
_, _, _, err = m.accountManager.AddPeer(ctx, accountID, "", "", peer, true)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to create proxy peer: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|