Merge branch 'main' into feat/network-map-serial

This commit is contained in:
Zoltan Papp
2025-12-18 15:30:59 +01:00
522 changed files with 44941 additions and 8064 deletions

View File

@@ -0,0 +1,146 @@
package jwt
import (
"errors"
"net/url"
"time"
"github.com/golang-jwt/jwt/v5"
log "github.com/sirupsen/logrus"
"github.com/netbirdio/netbird/shared/auth"
)
const (
// AccountIDSuffix suffix for the account id claim
AccountIDSuffix = "wt_account_id"
// DomainIDSuffix suffix for the domain id claim
DomainIDSuffix = "wt_account_domain"
// DomainCategorySuffix suffix for the domain category claim
DomainCategorySuffix = "wt_account_domain_category"
// UserIDClaim claim for the user id
UserIDClaim = "sub"
// LastLoginSuffix claim for the last login
LastLoginSuffix = "nb_last_login"
// Invited claim indicates that an incoming JWT is from a user that just accepted an invitation
Invited = "nb_invited"
)
var (
errUserIDClaimEmpty = errors.New("user ID claim token value is empty")
)
// ClaimsExtractor struct that holds the extract function
type ClaimsExtractor struct {
authAudience string
userIDClaim string
}
// ClaimsExtractorOption is a function that configures the ClaimsExtractor
type ClaimsExtractorOption func(*ClaimsExtractor)
// WithAudience sets the audience for the extractor
func WithAudience(audience string) ClaimsExtractorOption {
return func(c *ClaimsExtractor) {
c.authAudience = audience
}
}
// WithUserIDClaim sets the user id claim for the extractor
func WithUserIDClaim(userIDClaim string) ClaimsExtractorOption {
return func(c *ClaimsExtractor) {
c.userIDClaim = userIDClaim
}
}
// NewClaimsExtractor returns an extractor, and if provided with a function with ExtractClaims signature,
// then it will use that logic. Uses ExtractClaimsFromRequestContext by default
func NewClaimsExtractor(options ...ClaimsExtractorOption) *ClaimsExtractor {
ce := &ClaimsExtractor{}
for _, option := range options {
option(ce)
}
if ce.userIDClaim == "" {
ce.userIDClaim = UserIDClaim
}
return ce
}
func parseTime(timeString string) time.Time {
if timeString == "" {
return time.Time{}
}
parsedTime, err := time.Parse(time.RFC3339, timeString)
if err != nil {
return time.Time{}
}
return parsedTime
}
func (c ClaimsExtractor) audienceClaim(claimName string) string {
url, err := url.JoinPath(c.authAudience, claimName)
if err != nil {
return c.authAudience + claimName // as it was previously
}
return url
}
// ToUserAuth extracts user authentication information from a JWT token
func (c *ClaimsExtractor) ToUserAuth(token *jwt.Token) (auth.UserAuth, error) {
claims := token.Claims.(jwt.MapClaims)
userAuth := auth.UserAuth{}
userID, ok := claims[c.userIDClaim].(string)
if !ok {
return userAuth, errUserIDClaimEmpty
}
userAuth.UserId = userID
if accountIDClaim, ok := claims[c.audienceClaim(AccountIDSuffix)]; ok {
userAuth.AccountId = accountIDClaim.(string)
}
if domainClaim, ok := claims[c.audienceClaim(DomainIDSuffix)]; ok {
userAuth.Domain = domainClaim.(string)
}
if domainCategoryClaim, ok := claims[c.audienceClaim(DomainCategorySuffix)]; ok {
userAuth.DomainCategory = domainCategoryClaim.(string)
}
if lastLoginClaimString, ok := claims[c.audienceClaim(LastLoginSuffix)]; ok {
userAuth.LastLogin = parseTime(lastLoginClaimString.(string))
}
if invitedBool, ok := claims[c.audienceClaim(Invited)]; ok {
if value, ok := invitedBool.(bool); ok {
userAuth.Invited = value
}
}
return userAuth, nil
}
// ToGroups extracts group information from a JWT token
func (c *ClaimsExtractor) ToGroups(token *jwt.Token, claimName string) []string {
claims := token.Claims.(jwt.MapClaims)
userJWTGroups := make([]string, 0)
if claim, ok := claims[claimName]; ok {
if claimGroups, ok := claim.([]interface{}); ok {
for _, g := range claimGroups {
if group, ok := g.(string); ok {
userJWTGroups = append(userJWTGroups, group)
} else {
log.Debugf("JWT claim %q contains a non-string group (type: %T): %v", claimName, g, g)
}
}
}
} else {
log.Debugf("JWT claim %q is not a string array", claimName)
}
return userJWTGroups
}

View File

@@ -0,0 +1,288 @@
package jwt
import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rsa"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"math/big"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
"time"
"github.com/golang-jwt/jwt/v5"
log "github.com/sirupsen/logrus"
)
// Jwks is a collection of JSONWebKey obtained from Config.HttpServerConfig.AuthKeysLocation
type Jwks struct {
Keys []JSONWebKey `json:"keys"`
expiresInTime time.Time
}
// The supported elliptic curves types
const (
// p256 represents a cryptographic elliptical curve type.
p256 = "P-256"
// p384 represents a cryptographic elliptical curve type.
p384 = "P-384"
// p521 represents a cryptographic elliptical curve type.
p521 = "P-521"
)
// JSONWebKey is a representation of a Jason Web Key
type JSONWebKey struct {
Kty string `json:"kty"`
Kid string `json:"kid"`
Use string `json:"use"`
N string `json:"n"`
E string `json:"e"`
Crv string `json:"crv"`
X string `json:"x"`
Y string `json:"y"`
X5c []string `json:"x5c"`
}
type Validator struct {
lock sync.Mutex
issuer string
audienceList []string
keysLocation string
idpSignkeyRefreshEnabled bool
keys *Jwks
}
var (
errKeyNotFound = errors.New("unable to find appropriate key")
errTokenEmpty = errors.New("required authorization token not found")
errTokenInvalid = errors.New("token is invalid")
errTokenParsing = errors.New("token could not be parsed")
)
func NewValidator(issuer string, audienceList []string, keysLocation string, idpSignkeyRefreshEnabled bool) *Validator {
keys, err := getPemKeys(keysLocation)
if err != nil {
log.WithField("keysLocation", keysLocation).Errorf("could not get keys from location: %s", err)
}
return &Validator{
keys: keys,
issuer: issuer,
audienceList: audienceList,
keysLocation: keysLocation,
idpSignkeyRefreshEnabled: idpSignkeyRefreshEnabled,
}
}
func (v *Validator) getKeyFunc(ctx context.Context) jwt.Keyfunc {
return func(token *jwt.Token) (interface{}, error) {
// If keys are rotated, verify the keys prior to token validation
if v.idpSignkeyRefreshEnabled {
// If the keys are invalid, retrieve new ones
// @todo propose a separate go routine to regularly check these to prevent blocking when actually
// validating the token
if !v.keys.stillValid() {
v.lock.Lock()
defer v.lock.Unlock()
refreshedKeys, err := getPemKeys(v.keysLocation)
if err != nil {
log.WithContext(ctx).Debugf("cannot get JSONWebKey: %v, falling back to old keys", err)
refreshedKeys = v.keys
}
log.WithContext(ctx).Debugf("keys refreshed, new UTC expiration time: %s", refreshedKeys.expiresInTime.UTC())
v.keys = refreshedKeys
}
}
publicKey, err := getPublicKey(token, v.keys)
if err == nil {
return publicKey, nil
}
msg := fmt.Sprintf("getPublicKey error: %s", err)
if errors.Is(err, errKeyNotFound) && !v.idpSignkeyRefreshEnabled {
msg = fmt.Sprintf("getPublicKey error: %s. You can enable key refresh by setting HttpServerConfig.IdpSignKeyRefreshEnabled to true in your management.json file and restart the service", err)
}
log.WithContext(ctx).Error(msg)
return nil, err
}
}
// ValidateAndParse validates the token and returns the parsed token
func (v *Validator) ValidateAndParse(ctx context.Context, token string) (*jwt.Token, error) {
// If the token is empty...
if token == "" {
// If we get here, the required token is missing
log.WithContext(ctx).Debugf(" Error: No credentials found (CredentialsOptional=false)")
return nil, errTokenEmpty
}
// Now parse the token
parsedToken, err := jwt.Parse(
token,
v.getKeyFunc(ctx),
jwt.WithAudience(v.audienceList...),
jwt.WithIssuer(v.issuer),
jwt.WithIssuedAt(),
)
// Check if there was an error in parsing...
if err != nil {
err = fmt.Errorf("%w: %s", errTokenParsing, err)
log.WithContext(ctx).Error(err.Error())
return nil, err
}
// Check if the parsed token is valid...
if !parsedToken.Valid {
log.WithContext(ctx).Debug(errTokenInvalid.Error())
return nil, errTokenInvalid
}
return parsedToken, nil
}
// stillValid returns true if the JSONWebKey still valid and have enough time to be used
func (jwks *Jwks) stillValid() bool {
return !jwks.expiresInTime.IsZero() && time.Now().Add(5*time.Second).Before(jwks.expiresInTime)
}
func getPemKeys(keysLocation string) (*Jwks, error) {
jwks := &Jwks{}
url, err := url.ParseRequestURI(keysLocation)
if err != nil {
return jwks, err
}
resp, err := http.Get(url.String())
if err != nil {
return jwks, err
}
defer resp.Body.Close()
err = json.NewDecoder(resp.Body).Decode(jwks)
if err != nil {
return jwks, err
}
cacheControlHeader := resp.Header.Get("Cache-Control")
expiresIn := getMaxAgeFromCacheHeader(cacheControlHeader)
jwks.expiresInTime = time.Now().Add(time.Duration(expiresIn) * time.Second)
return jwks, nil
}
func getPublicKey(token *jwt.Token, jwks *Jwks) (interface{}, error) {
// todo as we load the jkws when the server is starting, we should build a JKS map with the pem cert at the boot time
for k := range jwks.Keys {
if token.Header["kid"] != jwks.Keys[k].Kid {
continue
}
if len(jwks.Keys[k].X5c) != 0 {
cert := "-----BEGIN CERTIFICATE-----\n" + jwks.Keys[k].X5c[0] + "\n-----END CERTIFICATE-----"
return jwt.ParseRSAPublicKeyFromPEM([]byte(cert))
}
if jwks.Keys[k].Kty == "RSA" {
return getPublicKeyFromRSA(jwks.Keys[k])
}
if jwks.Keys[k].Kty == "EC" {
return getPublicKeyFromECDSA(jwks.Keys[k])
}
}
return nil, errKeyNotFound
}
func getPublicKeyFromECDSA(jwk JSONWebKey) (publicKey *ecdsa.PublicKey, err error) {
if jwk.X == "" || jwk.Y == "" || jwk.Crv == "" {
return nil, fmt.Errorf("ecdsa key incomplete")
}
var xCoordinate []byte
if xCoordinate, err = base64.RawURLEncoding.DecodeString(jwk.X); err != nil {
return nil, err
}
var yCoordinate []byte
if yCoordinate, err = base64.RawURLEncoding.DecodeString(jwk.Y); err != nil {
return nil, err
}
publicKey = &ecdsa.PublicKey{}
var curve elliptic.Curve
switch jwk.Crv {
case p256:
curve = elliptic.P256()
case p384:
curve = elliptic.P384()
case p521:
curve = elliptic.P521()
}
publicKey.Curve = curve
publicKey.X = big.NewInt(0).SetBytes(xCoordinate)
publicKey.Y = big.NewInt(0).SetBytes(yCoordinate)
return publicKey, nil
}
func getPublicKeyFromRSA(jwk JSONWebKey) (*rsa.PublicKey, error) {
decodedE, err := base64.RawURLEncoding.DecodeString(jwk.E)
if err != nil {
return nil, err
}
decodedN, err := base64.RawURLEncoding.DecodeString(jwk.N)
if err != nil {
return nil, err
}
var n, e big.Int
e.SetBytes(decodedE)
n.SetBytes(decodedN)
return &rsa.PublicKey{
E: int(e.Int64()),
N: &n,
}, nil
}
// getMaxAgeFromCacheHeader extracts max-age directive from the Cache-Control header
func getMaxAgeFromCacheHeader(cacheControl string) int {
// Split into individual directives
directives := strings.Split(cacheControl, ",")
for _, directive := range directives {
directive = strings.TrimSpace(directive)
if strings.HasPrefix(directive, "max-age=") {
// Extract the max-age value
maxAgeStr := strings.TrimPrefix(directive, "max-age=")
maxAge, err := strconv.Atoi(maxAgeStr)
if err != nil {
return 0
}
return maxAge
}
}
return 0
}

28
shared/auth/user.go Normal file
View File

@@ -0,0 +1,28 @@
package auth
import (
"time"
)
type UserAuth struct {
// The account id the user is accessing
AccountId string
// The account domain
Domain string
// The account domain category, TBC values
DomainCategory string
// Indicates whether this user was invited, TBC logic
Invited bool
// Indicates whether this is a child account
IsChild bool
// The user id
UserId string
// Last login time for this user
LastLogin time.Time
// The Groups the user belongs to on this account
Groups []string
// Indicates whether this user has authenticated with a Personal Access Token
IsPAT bool
}

View File

@@ -5,4 +5,4 @@ const (
AccountIDKey = "accountID"
UserIDKey = "userID"
PeerIDKey = "peerID"
)
)

View File

@@ -18,6 +18,13 @@ import (
"google.golang.org/grpc/status"
"github.com/netbirdio/management-integrations/integrations"
"github.com/netbirdio/netbird/management/internals/controllers/network_map/controller"
"github.com/netbirdio/netbird/management/internals/controllers/network_map/update_channel"
"github.com/netbirdio/netbird/management/internals/modules/peers"
"github.com/netbirdio/netbird/management/internals/modules/peers/ephemeral/manager"
nbgrpc "github.com/netbirdio/netbird/management/internals/shared/grpc"
"github.com/netbirdio/netbird/client/system"
"github.com/netbirdio/netbird/encryption"
"github.com/netbirdio/netbird/management/internals/server/config"
@@ -26,7 +33,6 @@ import (
"github.com/netbirdio/netbird/management/server/groups"
"github.com/netbirdio/netbird/management/server/integrations/port_forwarding"
"github.com/netbirdio/netbird/management/server/mock_server"
"github.com/netbirdio/netbird/management/server/peers"
"github.com/netbirdio/netbird/management/server/permissions"
"github.com/netbirdio/netbird/management/server/settings"
"github.com/netbirdio/netbird/management/server/store"
@@ -66,7 +72,6 @@ func startManagement(t *testing.T) (*grpc.Server, net.Listener) {
}
t.Cleanup(cleanUp)
peersUpdateManager := mgmt.NewPeersUpdateManager(nil)
eventStore := &activity.InMemoryEventStore{}
ctrl := gomock.NewController(t)
@@ -109,15 +114,22 @@ func startManagement(t *testing.T) (*grpc.Server, net.Listener) {
Return(&types.ExtraSettings{}, nil).
AnyTimes()
accountManager, err := mgmt.BuildManager(context.Background(), store, peersUpdateManager, nil, "", "netbird.selfhosted", eventStore, nil, false, ia, metrics, port_forwarding.NewControllerMock(), settingsMockManager, permissionsManagerMock, false)
ctx := context.Background()
updateManager := update_channel.NewPeersUpdateManager(metrics)
requestBuffer := mgmt.NewAccountRequestBuffer(ctx, store)
networkMapController := controller.NewController(ctx, store, metrics, updateManager, requestBuffer, mgmt.MockIntegratedValidator{}, settingsMockManager, "netbird.selfhosted", port_forwarding.NewControllerMock(), manager.NewEphemeralManager(store, peersManger), config)
accountManager, err := mgmt.BuildManager(context.Background(), config, store, networkMapController, nil, "", eventStore, nil, false, ia, metrics, port_forwarding.NewControllerMock(), settingsMockManager, permissionsManagerMock, false)
if err != nil {
t.Fatal(err)
}
groupsManager := groups.NewManagerMock()
secretsManager := mgmt.NewTimeBasedAuthSecretsManager(peersUpdateManager, config.TURNConfig, config.Relay, settingsMockManager, groupsManager)
mgmtServer, err := mgmt.NewServer(context.Background(), config, accountManager, settingsMockManager, peersUpdateManager, secretsManager, nil, nil, nil, mgmt.MockIntegratedValidator{})
secretsManager, err := nbgrpc.NewTimeBasedAuthSecretsManager(updateManager, config.TURNConfig, config.Relay, settingsMockManager, groupsManager)
if err != nil {
t.Fatal(err)
}
mgmtServer, err := nbgrpc.NewServer(config, accountManager, settingsMockManager, secretsManager, nil, nil, mgmt.MockIntegratedValidator{}, networkMapController)
if err != nil {
t.Fatal(err)
}
@@ -301,7 +313,7 @@ func TestClient_Sync(t *testing.T) {
defer cancel()
go func() {
err = client.Sync(ctx, info, func(msg *mgmtProto.SyncResponse) error {
err = client.Sync(ctx, info, 0, func(msg *mgmtProto.SyncResponse) error {
ch <- msg
return nil
})

View File

@@ -1,19 +1,20 @@
package common
// LoginFlag introduces additional login flags to the PKCE authorization request
// LoginFlag introduces additional login flags to the PKCE authorization request.
//
// # Config Values
//
// | Value | Flag | OAuth Parameters |
// |-------|----------------------|-----------------------------------------|
// | 0 | LoginFlagPromptLogin | prompt=login |
// | 1 | LoginFlagMaxAge0 | max_age=0 |
type LoginFlag uint8
const (
// LoginFlagPrompt adds prompt=login to the authorization request
LoginFlagPrompt LoginFlag = iota
// LoginFlagPromptLogin adds prompt=login to the authorization request
LoginFlagPromptLogin LoginFlag = iota
// LoginFlagMaxAge0 adds max_age=0 to the authorization request
LoginFlagMaxAge0
// LoginFlagNone disables all login flags
LoginFlagNone
)
func (l LoginFlag) IsPromptLogin() bool {
return l == LoginFlagPrompt
}
func (l LoginFlag) IsMaxAge0Login() bool {
return l == LoginFlagMaxAge0
}

View File

@@ -22,6 +22,7 @@ import (
"github.com/netbirdio/netbird/encryption"
"github.com/netbirdio/netbird/shared/management/domain"
"github.com/netbirdio/netbird/shared/management/proto"
"github.com/netbirdio/netbird/util/wsproxy"
)
const ConnectTimeout = 10 * time.Second
@@ -52,10 +53,9 @@ func NewClient(ctx context.Context, addr string, ourPrivateKey wgtypes.Key, tlsE
operation := func() error {
var err error
conn, err = nbgrpc.CreateConnection(ctx, addr, tlsEnabled)
conn, err = nbgrpc.CreateConnection(ctx, addr, tlsEnabled, wsproxy.ManagementComponent)
if err != nil {
log.Printf("createConnection error: %v", err)
return err
return fmt.Errorf("create connection: %w", err)
}
return nil
}

View File

@@ -1,26 +0,0 @@
package client
import (
"testing"
)
func TestGrpcClient_LastNetworkMapSerial_SetGet(t *testing.T) {
c := &GrpcClient{}
if got := c.getLastNetworkMapSerial(); got != 0 {
t.Fatalf("initial serial should be 0, got %d", got)
}
c.setLastNetworkMapSerial(123)
if got := c.getLastNetworkMapSerial(); got != 123 {
t.Fatalf("serial after set should be 123, got %d", got)
}
// overwrite should work
c.setLastNetworkMapSerial(5)
if got := c.getLastNetworkMapSerial(); got != 5 {
t.Fatalf("serial after overwrite should be 5, got %d", got)
}
}

View File

@@ -4,10 +4,14 @@ import (
"bytes"
"context"
"encoding/json"
"errors"
"github.com/netbirdio/netbird/shared/management/http/api"
)
// ErrGroupNotFound is returned when a group is not found
var ErrGroupNotFound = errors.New("group not found")
// GroupsAPI APIs for Groups, do not use directly
type GroupsAPI struct {
c *Client
@@ -27,6 +31,27 @@ func (a *GroupsAPI) List(ctx context.Context) ([]api.Group, error) {
return ret, err
}
// GetByName get group by name
// See more: https://docs.netbird.io/api/resources/groups#list-all-groups
func (a *GroupsAPI) GetByName(ctx context.Context, groupName string) (*api.Group, error) {
params := map[string]string{"name": groupName}
resp, err := a.c.NewRequest(ctx, "GET", "/api/groups", nil, params)
if err != nil {
return nil, err
}
if resp.Body != nil {
defer resp.Body.Close()
}
ret, err := parseResponse[[]api.Group](resp)
if err != nil {
return nil, err
}
if len(ret) == 0 {
return nil, ErrGroupNotFound
}
return &ret[0], nil
}
// Get get group info
// See more: https://docs.netbird.io/api/resources/groups#retrieve-a-group
func (a *GroupsAPI) Get(ctx context.Context, groupID string) (*api.Group, error) {

View File

@@ -463,6 +463,9 @@ components:
description: (Cloud only) Indicates whether peer needs approval
type: boolean
example: true
disapproval_reason:
description: (Cloud only) Reason why the peer requires approval
type: string
country_code:
$ref: '#/components/schemas/CountryCode'
city_name:
@@ -507,6 +510,48 @@ components:
- serial_number
- extra_dns_labels
- ephemeral
PeerTemporaryAccessRequest:
type: object
properties:
name:
description: Peer's hostname
type: string
example: temp-host-1
wg_pub_key:
description: Peer's WireGuard public key
type: string
example: "n0r3pL4c3h0ld3rK3y=="
rules:
description: List of temporary access rules
type: array
items:
type: string
example: "tcp/80"
required:
- name
- wg_pub_key
- rules
PeerTemporaryAccessResponse:
type: object
properties:
name:
description: Peer's hostname
type: string
example: temp-host-1
id:
description: Peer ID
type: string
example: chacbco6lnnbn6cg5s90
rules:
description: List of temporary access rules
type: array
items:
type: string
example: "tcp/80"
required:
- name
- id
- rules
AccessiblePeer:
allOf:
- $ref: '#/components/schemas/PeerMinimum'
@@ -1404,7 +1449,8 @@ components:
allOf:
- $ref: '#/components/schemas/NetworkResourceType'
- type: string
example: host
enum: ["peer"]
example: peer
NetworkRequest:
type: object
properties:
@@ -2793,6 +2839,42 @@ paths:
"$ref": "#/components/responses/forbidden"
'500':
"$ref": "#/components/responses/internal_error"
/api/peers/{peerId}/temporary-access:
post:
summary: Create a Temporary Access Peer
description: Creates a temporary access peer that can be used to access this peer and this peer only. The temporary access peer and its access policies will be automatically deleted after it disconnects.
tags: [ Peers ]
security:
- BearerAuth: [ ]
- TokenAuth: [ ]
parameters:
- in: path
name: peerId
required: true
schema:
type: string
description: The unique identifier of a peer
requestBody:
description: Temporary Access Peer create request
content:
'application/json':
schema:
$ref: '#/components/schemas/PeerTemporaryAccessRequest'
responses:
'200':
description: Temporary Access Peer response
content:
application/json:
schema:
$ref: '#/components/schemas/PeerTemporaryAccessResponse'
'400':
"$ref": "#/components/responses/bad_request"
'401':
"$ref": "#/components/responses/requires_authentication"
'403':
"$ref": "#/components/responses/forbidden"
'500':
"$ref": "#/components/responses/internal_error"
/api/peers/{peerId}/ingress/ports:
get:
x-cloud-only: true
@@ -3280,6 +3362,14 @@ paths:
security:
- BearerAuth: [ ]
- TokenAuth: [ ]
parameters:
- in: query
name: name
required: false
schema:
type: string
description: Filter groups by name (exact match)
example: "devs"
responses:
'200':
description: A JSON Array of Groups
@@ -3293,6 +3383,8 @@ paths:
"$ref": "#/components/responses/bad_request"
'401':
"$ref": "#/components/responses/requires_authentication"
'404':
"$ref": "#/components/responses/not_found"
'403':
"$ref": "#/components/responses/forbidden"
'500':

View File

@@ -168,6 +168,7 @@ const (
const (
ResourceTypeDomain ResourceType = "domain"
ResourceTypeHost ResourceType = "host"
ResourceTypePeer ResourceType = "peer"
ResourceTypeSubnet ResourceType = "subnet"
)
@@ -1036,6 +1037,9 @@ type Peer struct {
// CreatedAt Peer creation date (UTC)
CreatedAt time.Time `json:"created_at"`
// DisapprovalReason (Cloud only) Reason why the peer requires approval
DisapprovalReason *string `json:"disapproval_reason,omitempty"`
// DnsLabel Peer's DNS label is the parsed peer name for domain resolution. It is used to form an FQDN by appending the account's domain to the peer label. e.g. peer-dns-label.netbird.cloud
DnsLabel string `json:"dns_label"`
@@ -1123,6 +1127,9 @@ type PeerBatch struct {
// CreatedAt Peer creation date (UTC)
CreatedAt time.Time `json:"created_at"`
// DisapprovalReason (Cloud only) Reason why the peer requires approval
DisapprovalReason *string `json:"disapproval_reason,omitempty"`
// DnsLabel Peer's DNS label is the parsed peer name for domain resolution. It is used to form an FQDN by appending the account's domain to the peer label. e.g. peer-dns-label.netbird.cloud
DnsLabel string `json:"dns_label"`
@@ -1221,6 +1228,30 @@ type PeerRequest struct {
SshEnabled bool `json:"ssh_enabled"`
}
// PeerTemporaryAccessRequest defines model for PeerTemporaryAccessRequest.
type PeerTemporaryAccessRequest struct {
// Name Peer's hostname
Name string `json:"name"`
// Rules List of temporary access rules
Rules []string `json:"rules"`
// WgPubKey Peer's WireGuard public key
WgPubKey string `json:"wg_pub_key"`
}
// PeerTemporaryAccessResponse defines model for PeerTemporaryAccessResponse.
type PeerTemporaryAccessResponse struct {
// Id Peer ID
Id string `json:"id"`
// Name Peer's hostname
Name string `json:"name"`
// Rules List of temporary access rules
Rules []string `json:"rules"`
}
// PersonalAccessToken defines model for PersonalAccessToken.
type PersonalAccessToken struct {
// CreatedAt Date the token was created
@@ -1877,6 +1908,12 @@ type GetApiEventsNetworkTrafficParamsConnectionType string
// GetApiEventsNetworkTrafficParamsDirection defines parameters for GetApiEventsNetworkTraffic.
type GetApiEventsNetworkTrafficParamsDirection string
// GetApiGroupsParams defines parameters for GetApiGroups.
type GetApiGroupsParams struct {
// Name Filter groups by name (exact match)
Name *string `form:"name,omitempty" json:"name,omitempty"`
}
// GetApiPeersParams defines parameters for GetApiPeers.
type GetApiPeersParams struct {
// Name Filter peers by name
@@ -1949,6 +1986,9 @@ type PostApiPeersPeerIdIngressPortsJSONRequestBody = IngressPortAllocationReques
// PutApiPeersPeerIdIngressPortsAllocationIdJSONRequestBody defines body for PutApiPeersPeerIdIngressPortsAllocationId for application/json ContentType.
type PutApiPeersPeerIdIngressPortsAllocationIdJSONRequestBody = IngressPortAllocationRequest
// PostApiPeersPeerIdTemporaryAccessJSONRequestBody defines body for PostApiPeersPeerIdTemporaryAccess for application/json ContentType.
type PostApiPeersPeerIdTemporaryAccessJSONRequestBody = PeerTemporaryAccessRequest
// PostApiPoliciesJSONRequestBody defines body for PostApiPolicies for application/json ContentType.
type PostApiPoliciesJSONRequestBody = PolicyUpdate

View File

@@ -106,6 +106,8 @@ func WriteError(ctx context.Context, err error, w http.ResponseWriter) {
httpStatus = http.StatusUnauthorized
case status.BadRequest:
httpStatus = http.StatusBadRequest
case status.TooManyRequests:
httpStatus = http.StatusTooManyRequests
default:
}
msg = strings.ToLower(err.Error())

View File

@@ -1,4 +1,4 @@
package operations
// Operation represents a permission operation type
type Operation string
type Operation string

File diff suppressed because it is too large Load Diff

View File

@@ -151,6 +151,12 @@ message Flags {
bool blockInbound = 9;
bool lazyConnectionEnabled = 10;
bool enableSSHRoot = 11;
bool enableSSHSFTP = 12;
bool enableSSHLocalPortForwarding = 13;
bool enableSSHRemotePortForwarding = 14;
bool disableSSHAuth = 15;
}
// PeerSystemMeta is machine meta data like OS and version.
@@ -245,6 +251,14 @@ message FlowConfig {
bool dnsCollection = 8;
}
// JWTConfig represents JWT authentication configuration
message JWTConfig {
string issuer = 1;
string audience = 2;
string keysLocation = 3;
int64 maxTokenAge = 4;
}
// ProtectedHostConfig is similar to HostConfig but has additional user and password
// Mostly used for TURN servers
message ProtectedHostConfig {
@@ -340,6 +354,8 @@ message SSHConfig {
// sshPubKey is a SSH public key of a peer to be added to authorized_hosts.
// This property should be ignore if SSHConfig comes from PeerConfig.
bytes sshPubKey = 2;
JWTConfig jwtConfig = 3;
}
// DeviceAuthorizationFlowRequest empty struct for future expansion
@@ -415,12 +431,15 @@ message DNSConfig {
bool ServiceEnable = 1;
repeated NameServerGroup NameServerGroups = 2;
repeated CustomZone CustomZones = 3;
int64 ForwarderPort = 4 [deprecated = true];
}
// CustomZone represents a dns.CustomZone
message CustomZone {
string Domain = 1;
repeated SimpleRecord Records = 2;
bool SearchDomainDisabled = 3;
bool SkipPTRProcess = 4;
}
// SimpleRecord represents a dns.SimpleRecord

View File

@@ -37,6 +37,9 @@ const (
// Unauthenticated indicates that user is not authenticated due to absence of valid credentials
Unauthenticated Type = 10
// TooManyRequests indicates that the user has sent too many requests in a given amount of time (rate limiting)
TooManyRequests Type = 11
)
// Type is a type of the Error

View File

@@ -9,11 +9,8 @@ import (
log "github.com/sirupsen/logrus"
"github.com/netbirdio/netbird/client/iface"
auth "github.com/netbirdio/netbird/shared/relay/auth/hmac"
"github.com/netbirdio/netbird/shared/relay/client/dialer"
"github.com/netbirdio/netbird/shared/relay/client/dialer/quic"
"github.com/netbirdio/netbird/shared/relay/client/dialer/ws"
"github.com/netbirdio/netbird/shared/relay/healthcheck"
"github.com/netbirdio/netbird/shared/relay/messages"
)
@@ -296,14 +293,7 @@ func (c *Client) Close() error {
}
func (c *Client) connect(ctx context.Context) (*RelayAddr, error) {
// Force WebSocket for MTUs larger than default to avoid QUIC DATAGRAM frame size issues
var dialers []dialer.DialeFn
if c.mtu > 0 && c.mtu > iface.DefaultMTU {
c.log.Infof("MTU %d exceeds default (%d), forcing WebSocket transport to avoid DATAGRAM frame size issues", c.mtu, iface.DefaultMTU)
dialers = []dialer.DialeFn{ws.Dialer{}}
} else {
dialers = []dialer.DialeFn{quic.Dialer{}, ws.Dialer{}}
}
dialers := c.getDialers()
rd := dialer.NewRaceDial(c.log, dialer.DefaultConnectionTimeout, c.connectionURL, dialers...)
conn, err := rd.Dial()

View File

@@ -11,8 +11,8 @@ import (
"github.com/quic-go/quic-go"
log "github.com/sirupsen/logrus"
quictls "github.com/netbirdio/netbird/shared/relay/tls"
nbnet "github.com/netbirdio/netbird/client/net"
quictls "github.com/netbirdio/netbird/shared/relay/tls"
)
type Dialer struct {

View File

@@ -38,8 +38,7 @@ func (c *Conn) Read(b []byte) (n int, err error) {
}
func (c *Conn) Write(b []byte) (n int, err error) {
err = c.Conn.Write(c.ctx, websocket.MessageBinary, b)
return 0, err
return 0, c.Conn.Write(c.ctx, websocket.MessageBinary, b)
}
func (c *Conn) RemoteAddr() net.Addr {

View File

@@ -0,0 +1,11 @@
//go:build !js
package ws
import "github.com/coder/websocket"
func createDialOptions() *websocket.DialOptions {
return &websocket.DialOptions{
HTTPClient: httpClientNbDialer(),
}
}

View File

@@ -0,0 +1,10 @@
//go:build js
package ws
import "github.com/coder/websocket"
func createDialOptions() *websocket.DialOptions {
// WASM version doesn't support HTTPClient
return &websocket.DialOptions{}
}

View File

@@ -14,9 +14,9 @@ import (
"github.com/coder/websocket"
log "github.com/sirupsen/logrus"
nbnet "github.com/netbirdio/netbird/client/net"
"github.com/netbirdio/netbird/shared/relay"
"github.com/netbirdio/netbird/util/embeddedroots"
nbnet "github.com/netbirdio/netbird/client/net"
)
type Dialer struct {
@@ -32,9 +32,7 @@ func (d Dialer) Dial(ctx context.Context, address string) (net.Conn, error) {
return nil, err
}
opts := &websocket.DialOptions{
HTTPClient: httpClientNbDialer(),
}
opts := createDialOptions()
parsedURL, err := url.Parse(wsURL)
if err != nil {

View File

@@ -0,0 +1,19 @@
//go:build !js
package client
import (
"github.com/netbirdio/netbird/client/iface"
"github.com/netbirdio/netbird/shared/relay/client/dialer"
"github.com/netbirdio/netbird/shared/relay/client/dialer/quic"
"github.com/netbirdio/netbird/shared/relay/client/dialer/ws"
)
// getDialers returns the list of dialers to use for connecting to the relay server.
func (c *Client) getDialers() []dialer.DialeFn {
if c.mtu > 0 && c.mtu > iface.DefaultMTU {
c.log.Infof("MTU %d exceeds default (%d), forcing WebSocket transport to avoid DATAGRAM frame size issues", c.mtu, iface.DefaultMTU)
return []dialer.DialeFn{ws.Dialer{}}
}
return []dialer.DialeFn{quic.Dialer{}, ws.Dialer{}}
}

View File

@@ -0,0 +1,13 @@
//go:build js
package client
import (
"github.com/netbirdio/netbird/shared/relay/client/dialer"
"github.com/netbirdio/netbird/shared/relay/client/dialer/ws"
)
func (c *Client) getDialers() []dialer.DialeFn {
// JS/WASM build only uses WebSocket transport
return []dialer.DialeFn{ws.Dialer{}}
}

View File

@@ -3,4 +3,4 @@ package relay
const (
// WebSocketURLPath is the path for the websocket relay connection
WebSocketURLPath = "/relay"
)
)

View File

@@ -20,6 +20,7 @@ import (
"github.com/netbirdio/netbird/encryption"
"github.com/netbirdio/netbird/shared/management/client"
"github.com/netbirdio/netbird/shared/signal/proto"
"github.com/netbirdio/netbird/util/wsproxy"
)
// ConnStateNotifier is a wrapper interface of the status recorder
@@ -57,10 +58,9 @@ func NewClient(ctx context.Context, addr string, key wgtypes.Key, tlsEnabled boo
operation := func() error {
var err error
conn, err = nbgrpc.CreateConnection(ctx, addr, tlsEnabled)
conn, err = nbgrpc.CreateConnection(ctx, addr, tlsEnabled, wsproxy.SignalComponent)
if err != nil {
log.Printf("createConnection error: %v", err)
return err
return fmt.Errorf("create connection: %w", err)
}
return nil
}