mirror of
https://github.com/netbirdio/netbird.git
synced 2026-04-06 01:24:06 -04:00
Compare commits
5 Commits
fix/grpc-r
...
fix/ui-deb
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0293cc2bd7 | ||
|
|
c2c6396a04 | ||
|
|
aaf813fc0c | ||
|
|
d97fe84296 | ||
|
|
81f45dab21 |
@@ -44,6 +44,10 @@ import (
|
||||
"github.com/netbirdio/netbird/version"
|
||||
)
|
||||
|
||||
// androidRunOverride is set on Android to inject mobile dependencies
|
||||
// when using embed.Client (which calls Run() with empty MobileDependency).
|
||||
var androidRunOverride func(c *ConnectClient, runningChan chan struct{}, logPath string) error
|
||||
|
||||
type ConnectClient struct {
|
||||
ctx context.Context
|
||||
config *profilemanager.Config
|
||||
@@ -76,6 +80,9 @@ func (c *ConnectClient) SetUpdateManager(um *updater.Manager) {
|
||||
|
||||
// Run with main logic.
|
||||
func (c *ConnectClient) Run(runningChan chan struct{}, logPath string) error {
|
||||
if androidRunOverride != nil {
|
||||
return androidRunOverride(c, runningChan, logPath)
|
||||
}
|
||||
return c.run(MobileDependency{}, runningChan, logPath)
|
||||
}
|
||||
|
||||
|
||||
73
client/internal/connect_android_default.go
Normal file
73
client/internal/connect_android_default.go
Normal file
@@ -0,0 +1,73 @@
|
||||
//go:build android
|
||||
|
||||
package internal
|
||||
|
||||
import (
|
||||
"net/netip"
|
||||
|
||||
"github.com/netbirdio/netbird/client/internal/dns"
|
||||
"github.com/netbirdio/netbird/client/internal/listener"
|
||||
"github.com/netbirdio/netbird/client/internal/stdnet"
|
||||
)
|
||||
|
||||
// noopIFaceDiscover is a stub ExternalIFaceDiscover for embed.Client on Android.
|
||||
// It returns an empty interface list, which means ICE P2P candidates won't be
|
||||
// discovered — connections will fall back to relay. Applications that need P2P
|
||||
// should provide a real implementation via runOnAndroidEmbed that uses
|
||||
// Android's ConnectivityManager to enumerate network interfaces.
|
||||
type noopIFaceDiscover struct{}
|
||||
|
||||
func (noopIFaceDiscover) IFaces() (string, error) {
|
||||
// Return empty JSON array — no local interfaces advertised for ICE.
|
||||
// This is intentional: without Android's ConnectivityManager, we cannot
|
||||
// reliably enumerate interfaces (netlink is restricted on Android 11+).
|
||||
// Relay connections still work; only P2P hole-punching is disabled.
|
||||
return "[]", nil
|
||||
}
|
||||
|
||||
// noopNetworkChangeListener is a stub for embed.Client on Android.
|
||||
// Network change events are ignored since the embed client manages its own
|
||||
// reconnection logic via the engine's built-in retry mechanism.
|
||||
type noopNetworkChangeListener struct{}
|
||||
|
||||
func (noopNetworkChangeListener) OnNetworkChanged(string) {
|
||||
// No-op: embed.Client relies on the engine's internal reconnection
|
||||
// logic rather than OS-level network change notifications.
|
||||
}
|
||||
|
||||
func (noopNetworkChangeListener) SetInterfaceIP(string) {
|
||||
// No-op: in netstack mode, the overlay IP is managed by the userspace
|
||||
// network stack, not by OS-level interface configuration.
|
||||
}
|
||||
|
||||
// noopDnsReadyListener is a stub for embed.Client on Android.
|
||||
// DNS readiness notifications are not needed in netstack/embed mode
|
||||
// since system DNS is disabled and DNS resolution happens externally.
|
||||
type noopDnsReadyListener struct{}
|
||||
|
||||
func (noopDnsReadyListener) OnReady() {
|
||||
// No-op: embed.Client does not need DNS readiness notifications.
|
||||
// System DNS is disabled in netstack mode.
|
||||
}
|
||||
|
||||
var _ stdnet.ExternalIFaceDiscover = noopIFaceDiscover{}
|
||||
var _ listener.NetworkChangeListener = noopNetworkChangeListener{}
|
||||
var _ dns.ReadyListener = noopDnsReadyListener{}
|
||||
|
||||
func init() {
|
||||
// Wire up the default override so embed.Client.Start() works on Android
|
||||
// with netstack mode. Provides complete no-op stubs for all mobile
|
||||
// dependencies so the engine's existing Android code paths work unchanged.
|
||||
// Applications that need P2P ICE or real DNS should replace this by
|
||||
// setting androidRunOverride before calling Start().
|
||||
androidRunOverride = func(c *ConnectClient, runningChan chan struct{}, logPath string) error {
|
||||
return c.runOnAndroidEmbed(
|
||||
noopIFaceDiscover{},
|
||||
noopNetworkChangeListener{},
|
||||
[]netip.AddrPort{},
|
||||
noopDnsReadyListener{},
|
||||
runningChan,
|
||||
logPath,
|
||||
)
|
||||
}
|
||||
}
|
||||
32
client/internal/connect_android_embed.go
Normal file
32
client/internal/connect_android_embed.go
Normal file
@@ -0,0 +1,32 @@
|
||||
//go:build android
|
||||
|
||||
package internal
|
||||
|
||||
import (
|
||||
"net/netip"
|
||||
|
||||
"github.com/netbirdio/netbird/client/internal/dns"
|
||||
"github.com/netbirdio/netbird/client/internal/listener"
|
||||
"github.com/netbirdio/netbird/client/internal/stdnet"
|
||||
)
|
||||
|
||||
// runOnAndroidEmbed is like RunOnAndroid but accepts a runningChan
|
||||
// so embed.Client.Start() can detect when the engine is ready.
|
||||
// It provides complete MobileDependency so the engine's existing
|
||||
// Android code paths work unchanged.
|
||||
func (c *ConnectClient) runOnAndroidEmbed(
|
||||
iFaceDiscover stdnet.ExternalIFaceDiscover,
|
||||
networkChangeListener listener.NetworkChangeListener,
|
||||
dnsAddresses []netip.AddrPort,
|
||||
dnsReadyListener dns.ReadyListener,
|
||||
runningChan chan struct{},
|
||||
logPath string,
|
||||
) error {
|
||||
mobileDependency := MobileDependency{
|
||||
IFaceDiscover: iFaceDiscover,
|
||||
NetworkChangeListener: networkChangeListener,
|
||||
HostDNSAddresses: dnsAddresses,
|
||||
DnsReadyListener: dnsReadyListener,
|
||||
}
|
||||
return c.run(mobileDependency, runningChan, logPath)
|
||||
}
|
||||
@@ -371,46 +371,49 @@ func (s *serviceClient) configureServiceForDebug(
|
||||
conn proto.DaemonServiceClient,
|
||||
state *debugInitialState,
|
||||
enablePersistence bool,
|
||||
) error {
|
||||
) {
|
||||
if state.wasDown {
|
||||
if _, err := conn.Up(s.ctx, &proto.UpRequest{}); err != nil {
|
||||
return fmt.Errorf("bring service up: %v", err)
|
||||
log.Warnf("failed to bring service up: %v", err)
|
||||
} else {
|
||||
log.Info("Service brought up for debug")
|
||||
time.Sleep(time.Second * 10)
|
||||
}
|
||||
log.Info("Service brought up for debug")
|
||||
time.Sleep(time.Second * 10)
|
||||
}
|
||||
|
||||
if !state.isLevelTrace {
|
||||
if _, err := conn.SetLogLevel(s.ctx, &proto.SetLogLevelRequest{Level: proto.LogLevel_TRACE}); err != nil {
|
||||
return fmt.Errorf("set log level to TRACE: %v", err)
|
||||
log.Warnf("failed to set log level to TRACE: %v", err)
|
||||
} else {
|
||||
log.Info("Log level set to TRACE for debug")
|
||||
}
|
||||
log.Info("Log level set to TRACE for debug")
|
||||
}
|
||||
|
||||
if _, err := conn.Down(s.ctx, &proto.DownRequest{}); err != nil {
|
||||
return fmt.Errorf("bring service down: %v", err)
|
||||
log.Warnf("failed to bring service down: %v", err)
|
||||
} else {
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
time.Sleep(time.Second)
|
||||
|
||||
if enablePersistence {
|
||||
if _, err := conn.SetSyncResponsePersistence(s.ctx, &proto.SetSyncResponsePersistenceRequest{
|
||||
Enabled: true,
|
||||
}); err != nil {
|
||||
return fmt.Errorf("enable sync response persistence: %v", err)
|
||||
log.Warnf("failed to enable sync response persistence: %v", err)
|
||||
} else {
|
||||
log.Info("Sync response persistence enabled for debug")
|
||||
}
|
||||
log.Info("Sync response persistence enabled for debug")
|
||||
}
|
||||
|
||||
if _, err := conn.Up(s.ctx, &proto.UpRequest{}); err != nil {
|
||||
return fmt.Errorf("bring service back up: %v", err)
|
||||
log.Warnf("failed to bring service back up: %v", err)
|
||||
} else {
|
||||
time.Sleep(time.Second * 3)
|
||||
}
|
||||
time.Sleep(time.Second * 3)
|
||||
|
||||
if _, err := conn.StartCPUProfile(s.ctx, &proto.StartCPUProfileRequest{}); err != nil {
|
||||
log.Warnf("failed to start CPU profiling: %v", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *serviceClient) collectDebugData(
|
||||
@@ -424,9 +427,7 @@ func (s *serviceClient) collectDebugData(
|
||||
var wg sync.WaitGroup
|
||||
startProgressTracker(ctx, &wg, params.duration, progress)
|
||||
|
||||
if err := s.configureServiceForDebug(conn, state, params.enablePersistence); err != nil {
|
||||
return err
|
||||
}
|
||||
s.configureServiceForDebug(conn, state, params.enablePersistence)
|
||||
|
||||
wg.Wait()
|
||||
progress.progressBar.Hide()
|
||||
@@ -484,7 +485,7 @@ func (s *serviceClient) createDebugBundleFromCollection(
|
||||
func (s *serviceClient) restoreServiceState(conn proto.DaemonServiceClient, state *debugInitialState) {
|
||||
if state.wasDown {
|
||||
if _, err := conn.Down(s.ctx, &proto.DownRequest{}); err != nil {
|
||||
log.Errorf("Failed to restore down state: %v", err)
|
||||
log.Warnf("failed to restore down state: %v", err)
|
||||
} else {
|
||||
log.Info("Service state restored to down")
|
||||
}
|
||||
@@ -492,7 +493,7 @@ func (s *serviceClient) restoreServiceState(conn proto.DaemonServiceClient, stat
|
||||
|
||||
if !state.isLevelTrace {
|
||||
if _, err := conn.SetLogLevel(s.ctx, &proto.SetLogLevelRequest{Level: state.logLevel}); err != nil {
|
||||
log.Errorf("Failed to restore log level: %v", err)
|
||||
log.Warnf("failed to restore log level: %v", err)
|
||||
} else {
|
||||
log.Info("Log level restored to original setting")
|
||||
}
|
||||
|
||||
@@ -1154,7 +1154,16 @@ print_builtin_traefik_instructions() {
|
||||
echo " - $NETBIRD_STUN_PORT/udp (STUN - required for NAT traversal)"
|
||||
if [[ "$ENABLE_PROXY" == "true" ]]; then
|
||||
echo " - 51820/udp (WIREGUARD - (optional) for P2P proxy connections)"
|
||||
echo ""
|
||||
fi
|
||||
echo ""
|
||||
echo "This setup is ideal for homelabs and smaller organization deployments."
|
||||
echo "For enterprise environments requiring high availability and advanced integrations,"
|
||||
echo "consider a commercial on-prem license or scaling your open source deployment:"
|
||||
echo ""
|
||||
echo " Commercial license: https://netbird.io/pricing#on-prem"
|
||||
echo " Scaling guide: https://docs.netbird.io/scaling-your-self-hosted-deployment"
|
||||
echo ""
|
||||
if [[ "$ENABLE_PROXY" == "true" ]]; then
|
||||
echo "NetBird Proxy:"
|
||||
echo " The proxy service is enabled and running."
|
||||
echo " Any domain NOT matching $NETBIRD_DOMAIN will be passed through to the proxy."
|
||||
|
||||
@@ -64,10 +64,19 @@ type Manager interface {
|
||||
GetVersionInfo(ctx context.Context) (*VersionInfo, error)
|
||||
}
|
||||
|
||||
type instanceStore interface {
|
||||
GetAccountsCounter(ctx context.Context) (int64, error)
|
||||
}
|
||||
|
||||
type embeddedIdP interface {
|
||||
CreateUserWithPassword(ctx context.Context, email, password, name string) (*idp.UserData, error)
|
||||
GetAllAccounts(ctx context.Context) (map[string][]*idp.UserData, error)
|
||||
}
|
||||
|
||||
// DefaultManager is the default implementation of Manager.
|
||||
type DefaultManager struct {
|
||||
store store.Store
|
||||
embeddedIdpManager *idp.EmbeddedIdPManager
|
||||
store instanceStore
|
||||
embeddedIdpManager embeddedIdP
|
||||
|
||||
setupRequired bool
|
||||
setupMu sync.RWMutex
|
||||
@@ -82,18 +91,18 @@ type DefaultManager struct {
|
||||
// NewManager creates a new instance manager.
|
||||
// If idpManager is not an EmbeddedIdPManager, setup-related operations will return appropriate defaults.
|
||||
func NewManager(ctx context.Context, store store.Store, idpManager idp.Manager) (Manager, error) {
|
||||
embeddedIdp, _ := idpManager.(*idp.EmbeddedIdPManager)
|
||||
embeddedIdp, ok := idpManager.(*idp.EmbeddedIdPManager)
|
||||
|
||||
m := &DefaultManager{
|
||||
store: store,
|
||||
embeddedIdpManager: embeddedIdp,
|
||||
setupRequired: false,
|
||||
store: store,
|
||||
setupRequired: false,
|
||||
httpClient: &http.Client{
|
||||
Timeout: httpTimeout,
|
||||
},
|
||||
}
|
||||
|
||||
if embeddedIdp != nil {
|
||||
if ok && embeddedIdp != nil {
|
||||
m.embeddedIdpManager = embeddedIdp
|
||||
err := m.loadSetupRequired(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -143,36 +152,61 @@ func (m *DefaultManager) IsSetupRequired(_ context.Context) (bool, error) {
|
||||
// CreateOwnerUser creates the initial owner user in the embedded IDP.
|
||||
func (m *DefaultManager) CreateOwnerUser(ctx context.Context, email, password, name string) (*idp.UserData, error) {
|
||||
|
||||
if err := m.validateSetupInfo(email, password, name); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if m.embeddedIdpManager == nil {
|
||||
return nil, errors.New("embedded IDP is not enabled")
|
||||
}
|
||||
|
||||
m.setupMu.RLock()
|
||||
setupRequired := m.setupRequired
|
||||
m.setupMu.RUnlock()
|
||||
if err := m.validateSetupInfo(email, password, name); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if !setupRequired {
|
||||
m.setupMu.Lock()
|
||||
defer m.setupMu.Unlock()
|
||||
|
||||
if !m.setupRequired {
|
||||
return nil, status.Errorf(status.PreconditionFailed, "setup already completed")
|
||||
}
|
||||
|
||||
if err := m.checkSetupRequiredFromDB(ctx); err != nil {
|
||||
var sErr *status.Error
|
||||
if errors.As(err, &sErr) && sErr.Type() == status.PreconditionFailed {
|
||||
m.setupRequired = false
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
userData, err := m.embeddedIdpManager.CreateUserWithPassword(ctx, email, password, name)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create user in embedded IdP: %w", err)
|
||||
}
|
||||
|
||||
m.setupMu.Lock()
|
||||
m.setupRequired = false
|
||||
m.setupMu.Unlock()
|
||||
|
||||
log.WithContext(ctx).Infof("created owner user %s in embedded IdP", email)
|
||||
|
||||
return userData, nil
|
||||
}
|
||||
|
||||
func (m *DefaultManager) checkSetupRequiredFromDB(ctx context.Context) error {
|
||||
numAccounts, err := m.store.GetAccountsCounter(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to check accounts: %w", err)
|
||||
}
|
||||
if numAccounts > 0 {
|
||||
return status.Errorf(status.PreconditionFailed, "setup already completed")
|
||||
}
|
||||
|
||||
users, err := m.embeddedIdpManager.GetAllAccounts(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to check IdP users: %w", err)
|
||||
}
|
||||
if len(users) > 0 {
|
||||
return status.Errorf(status.PreconditionFailed, "setup already completed")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *DefaultManager) validateSetupInfo(email, password, name string) error {
|
||||
if email == "" {
|
||||
return status.Errorf(status.InvalidArgument, "email is required")
|
||||
@@ -189,6 +223,9 @@ func (m *DefaultManager) validateSetupInfo(email, password, name string) error {
|
||||
if len(password) < 8 {
|
||||
return status.Errorf(status.InvalidArgument, "password must be at least 8 characters")
|
||||
}
|
||||
if len(password) > 72 {
|
||||
return status.Errorf(status.InvalidArgument, "password must be at most 72 characters")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,12 @@ package instance
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
@@ -11,173 +16,215 @@ import (
|
||||
"github.com/netbirdio/netbird/management/server/idp"
|
||||
)
|
||||
|
||||
// mockStore implements a minimal store.Store for testing
|
||||
type mockIdP struct {
|
||||
mu sync.Mutex
|
||||
createUserFunc func(ctx context.Context, email, password, name string) (*idp.UserData, error)
|
||||
users map[string][]*idp.UserData
|
||||
getAllAccountsErr error
|
||||
}
|
||||
|
||||
func (m *mockIdP) CreateUserWithPassword(ctx context.Context, email, password, name string) (*idp.UserData, error) {
|
||||
if m.createUserFunc != nil {
|
||||
return m.createUserFunc(ctx, email, password, name)
|
||||
}
|
||||
return &idp.UserData{ID: "test-user-id", Email: email, Name: name}, nil
|
||||
}
|
||||
|
||||
func (m *mockIdP) GetAllAccounts(_ context.Context) (map[string][]*idp.UserData, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.getAllAccountsErr != nil {
|
||||
return nil, m.getAllAccountsErr
|
||||
}
|
||||
return m.users, nil
|
||||
}
|
||||
|
||||
type mockStore struct {
|
||||
accountsCount int64
|
||||
err error
|
||||
}
|
||||
|
||||
func (m *mockStore) GetAccountsCounter(ctx context.Context) (int64, error) {
|
||||
func (m *mockStore) GetAccountsCounter(_ context.Context) (int64, error) {
|
||||
if m.err != nil {
|
||||
return 0, m.err
|
||||
}
|
||||
return m.accountsCount, nil
|
||||
}
|
||||
|
||||
// mockEmbeddedIdPManager wraps the real EmbeddedIdPManager for testing
|
||||
type mockEmbeddedIdPManager struct {
|
||||
createUserFunc func(ctx context.Context, email, password, name string) (*idp.UserData, error)
|
||||
}
|
||||
|
||||
func (m *mockEmbeddedIdPManager) CreateUserWithPassword(ctx context.Context, email, password, name string) (*idp.UserData, error) {
|
||||
if m.createUserFunc != nil {
|
||||
return m.createUserFunc(ctx, email, password, name)
|
||||
func newTestManager(idpMock *mockIdP, storeMock *mockStore) *DefaultManager {
|
||||
return &DefaultManager{
|
||||
store: storeMock,
|
||||
embeddedIdpManager: idpMock,
|
||||
setupRequired: true,
|
||||
httpClient: &http.Client{Timeout: httpTimeout},
|
||||
}
|
||||
return &idp.UserData{
|
||||
ID: "test-user-id",
|
||||
Email: email,
|
||||
Name: name,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// testManager is a test implementation that accepts our mock types
|
||||
type testManager struct {
|
||||
store *mockStore
|
||||
embeddedIdpManager *mockEmbeddedIdPManager
|
||||
}
|
||||
|
||||
func (m *testManager) IsSetupRequired(ctx context.Context) (bool, error) {
|
||||
if m.embeddedIdpManager == nil {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
count, err := m.store.GetAccountsCounter(ctx)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
return count == 0, nil
|
||||
}
|
||||
|
||||
func (m *testManager) CreateOwnerUser(ctx context.Context, email, password, name string) (*idp.UserData, error) {
|
||||
if m.embeddedIdpManager == nil {
|
||||
return nil, errors.New("embedded IDP is not enabled")
|
||||
}
|
||||
|
||||
return m.embeddedIdpManager.CreateUserWithPassword(ctx, email, password, name)
|
||||
}
|
||||
|
||||
func TestIsSetupRequired_EmbeddedIdPDisabled(t *testing.T) {
|
||||
manager := &testManager{
|
||||
store: &mockStore{accountsCount: 0},
|
||||
embeddedIdpManager: nil, // No embedded IDP
|
||||
}
|
||||
|
||||
required, err := manager.IsSetupRequired(context.Background())
|
||||
require.NoError(t, err)
|
||||
assert.False(t, required, "setup should not be required when embedded IDP is disabled")
|
||||
}
|
||||
|
||||
func TestIsSetupRequired_NoAccounts(t *testing.T) {
|
||||
manager := &testManager{
|
||||
store: &mockStore{accountsCount: 0},
|
||||
embeddedIdpManager: &mockEmbeddedIdPManager{},
|
||||
}
|
||||
|
||||
required, err := manager.IsSetupRequired(context.Background())
|
||||
require.NoError(t, err)
|
||||
assert.True(t, required, "setup should be required when no accounts exist")
|
||||
}
|
||||
|
||||
func TestIsSetupRequired_AccountsExist(t *testing.T) {
|
||||
manager := &testManager{
|
||||
store: &mockStore{accountsCount: 1},
|
||||
embeddedIdpManager: &mockEmbeddedIdPManager{},
|
||||
}
|
||||
|
||||
required, err := manager.IsSetupRequired(context.Background())
|
||||
require.NoError(t, err)
|
||||
assert.False(t, required, "setup should not be required when accounts exist")
|
||||
}
|
||||
|
||||
func TestIsSetupRequired_MultipleAccounts(t *testing.T) {
|
||||
manager := &testManager{
|
||||
store: &mockStore{accountsCount: 5},
|
||||
embeddedIdpManager: &mockEmbeddedIdPManager{},
|
||||
}
|
||||
|
||||
required, err := manager.IsSetupRequired(context.Background())
|
||||
require.NoError(t, err)
|
||||
assert.False(t, required, "setup should not be required when multiple accounts exist")
|
||||
}
|
||||
|
||||
func TestIsSetupRequired_StoreError(t *testing.T) {
|
||||
manager := &testManager{
|
||||
store: &mockStore{err: errors.New("database error")},
|
||||
embeddedIdpManager: &mockEmbeddedIdPManager{},
|
||||
}
|
||||
|
||||
_, err := manager.IsSetupRequired(context.Background())
|
||||
assert.Error(t, err, "should return error when store fails")
|
||||
}
|
||||
|
||||
func TestCreateOwnerUser_Success(t *testing.T) {
|
||||
expectedEmail := "admin@example.com"
|
||||
expectedName := "Admin User"
|
||||
expectedPassword := "securepassword123"
|
||||
idpMock := &mockIdP{}
|
||||
mgr := newTestManager(idpMock, &mockStore{})
|
||||
|
||||
manager := &testManager{
|
||||
store: &mockStore{accountsCount: 0},
|
||||
embeddedIdpManager: &mockEmbeddedIdPManager{
|
||||
createUserFunc: func(ctx context.Context, email, password, name string) (*idp.UserData, error) {
|
||||
assert.Equal(t, expectedEmail, email)
|
||||
assert.Equal(t, expectedPassword, password)
|
||||
assert.Equal(t, expectedName, name)
|
||||
return &idp.UserData{
|
||||
ID: "created-user-id",
|
||||
Email: email,
|
||||
Name: name,
|
||||
}, nil
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
userData, err := manager.CreateOwnerUser(context.Background(), expectedEmail, expectedPassword, expectedName)
|
||||
userData, err := mgr.CreateOwnerUser(context.Background(), "admin@example.com", "password123", "Admin")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "created-user-id", userData.ID)
|
||||
assert.Equal(t, expectedEmail, userData.Email)
|
||||
assert.Equal(t, expectedName, userData.Name)
|
||||
assert.Equal(t, "admin@example.com", userData.Email)
|
||||
|
||||
_, err = mgr.CreateOwnerUser(context.Background(), "admin2@example.com", "password123", "Admin2")
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "setup already completed")
|
||||
}
|
||||
|
||||
func TestCreateOwnerUser_SetupAlreadyCompleted(t *testing.T) {
|
||||
mgr := newTestManager(&mockIdP{}, &mockStore{})
|
||||
mgr.setupRequired = false
|
||||
|
||||
_, err := mgr.CreateOwnerUser(context.Background(), "admin@example.com", "password123", "Admin")
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "setup already completed")
|
||||
}
|
||||
|
||||
func TestCreateOwnerUser_EmbeddedIdPDisabled(t *testing.T) {
|
||||
manager := &testManager{
|
||||
store: &mockStore{accountsCount: 0},
|
||||
embeddedIdpManager: nil,
|
||||
}
|
||||
mgr := &DefaultManager{setupRequired: true}
|
||||
|
||||
_, err := manager.CreateOwnerUser(context.Background(), "admin@example.com", "password123", "Admin")
|
||||
assert.Error(t, err, "should return error when embedded IDP is disabled")
|
||||
_, err := mgr.CreateOwnerUser(context.Background(), "admin@example.com", "password123", "Admin")
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "embedded IDP is not enabled")
|
||||
}
|
||||
|
||||
func TestCreateOwnerUser_IdPError(t *testing.T) {
|
||||
manager := &testManager{
|
||||
store: &mockStore{accountsCount: 0},
|
||||
embeddedIdpManager: &mockEmbeddedIdPManager{
|
||||
createUserFunc: func(ctx context.Context, email, password, name string) (*idp.UserData, error) {
|
||||
return nil, errors.New("user already exists")
|
||||
},
|
||||
idpMock := &mockIdP{
|
||||
createUserFunc: func(_ context.Context, _, _, _ string) (*idp.UserData, error) {
|
||||
return nil, errors.New("provider error")
|
||||
},
|
||||
}
|
||||
mgr := newTestManager(idpMock, &mockStore{})
|
||||
|
||||
_, err := manager.CreateOwnerUser(context.Background(), "admin@example.com", "password123", "Admin")
|
||||
assert.Error(t, err, "should return error when IDP fails")
|
||||
_, err := mgr.CreateOwnerUser(context.Background(), "admin@example.com", "password123", "Admin")
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "provider error")
|
||||
|
||||
required, _ := mgr.IsSetupRequired(context.Background())
|
||||
assert.True(t, required, "setup should still be required after IdP error")
|
||||
}
|
||||
|
||||
func TestCreateOwnerUser_TransientDBError_DoesNotBlockSetup(t *testing.T) {
|
||||
mgr := newTestManager(&mockIdP{}, &mockStore{err: errors.New("connection refused")})
|
||||
|
||||
_, err := mgr.CreateOwnerUser(context.Background(), "admin@example.com", "password123", "Admin")
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "connection refused")
|
||||
|
||||
required, _ := mgr.IsSetupRequired(context.Background())
|
||||
assert.True(t, required, "setup should still be required after transient DB error")
|
||||
|
||||
mgr.store = &mockStore{}
|
||||
userData, err := mgr.CreateOwnerUser(context.Background(), "admin@example.com", "password123", "Admin")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "admin@example.com", userData.Email)
|
||||
}
|
||||
|
||||
func TestCreateOwnerUser_TransientIdPError_DoesNotBlockSetup(t *testing.T) {
|
||||
idpMock := &mockIdP{getAllAccountsErr: errors.New("connection reset")}
|
||||
mgr := newTestManager(idpMock, &mockStore{})
|
||||
|
||||
_, err := mgr.CreateOwnerUser(context.Background(), "admin@example.com", "password123", "Admin")
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "connection reset")
|
||||
|
||||
required, _ := mgr.IsSetupRequired(context.Background())
|
||||
assert.True(t, required, "setup should still be required after transient IdP error")
|
||||
|
||||
idpMock.getAllAccountsErr = nil
|
||||
userData, err := mgr.CreateOwnerUser(context.Background(), "admin@example.com", "password123", "Admin")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "admin@example.com", userData.Email)
|
||||
}
|
||||
|
||||
func TestCreateOwnerUser_DBCheckBlocksConcurrent(t *testing.T) {
|
||||
idpMock := &mockIdP{
|
||||
users: map[string][]*idp.UserData{
|
||||
"acc1": {{ID: "existing-user"}},
|
||||
},
|
||||
}
|
||||
mgr := newTestManager(idpMock, &mockStore{})
|
||||
|
||||
_, err := mgr.CreateOwnerUser(context.Background(), "admin@example.com", "password123", "Admin")
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "setup already completed")
|
||||
}
|
||||
|
||||
func TestCreateOwnerUser_DBCheckBlocksWhenAccountsExist(t *testing.T) {
|
||||
mgr := newTestManager(&mockIdP{}, &mockStore{accountsCount: 1})
|
||||
|
||||
_, err := mgr.CreateOwnerUser(context.Background(), "admin@example.com", "password123", "Admin")
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "setup already completed")
|
||||
}
|
||||
|
||||
func TestCreateOwnerUser_ConcurrentRequests(t *testing.T) {
|
||||
var idpCallCount atomic.Int32
|
||||
var successCount atomic.Int32
|
||||
var failCount atomic.Int32
|
||||
|
||||
idpMock := &mockIdP{
|
||||
createUserFunc: func(_ context.Context, email, _, _ string) (*idp.UserData, error) {
|
||||
idpCallCount.Add(1)
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
return &idp.UserData{ID: "user-1", Email: email, Name: "Owner"}, nil
|
||||
},
|
||||
}
|
||||
mgr := newTestManager(idpMock, &mockStore{})
|
||||
|
||||
var wg sync.WaitGroup
|
||||
for i := range 10 {
|
||||
wg.Add(1)
|
||||
go func(idx int) {
|
||||
defer wg.Done()
|
||||
_, err := mgr.CreateOwnerUser(
|
||||
context.Background(),
|
||||
fmt.Sprintf("owner%d@example.com", idx),
|
||||
"password1234",
|
||||
fmt.Sprintf("Owner%d", idx),
|
||||
)
|
||||
if err != nil {
|
||||
failCount.Add(1)
|
||||
} else {
|
||||
successCount.Add(1)
|
||||
}
|
||||
}(i)
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
assert.Equal(t, int32(1), successCount.Load(), "exactly one concurrent setup request should succeed")
|
||||
assert.Equal(t, int32(9), failCount.Load(), "remaining concurrent requests should fail")
|
||||
assert.Equal(t, int32(1), idpCallCount.Load(), "IdP CreateUser should be called exactly once")
|
||||
}
|
||||
|
||||
func TestIsSetupRequired_EmbeddedIdPDisabled(t *testing.T) {
|
||||
mgr := &DefaultManager{}
|
||||
|
||||
required, err := mgr.IsSetupRequired(context.Background())
|
||||
require.NoError(t, err)
|
||||
assert.False(t, required)
|
||||
}
|
||||
|
||||
func TestIsSetupRequired_ReturnsFlag(t *testing.T) {
|
||||
mgr := newTestManager(&mockIdP{}, &mockStore{})
|
||||
|
||||
required, err := mgr.IsSetupRequired(context.Background())
|
||||
require.NoError(t, err)
|
||||
assert.True(t, required)
|
||||
|
||||
mgr.setupMu.Lock()
|
||||
mgr.setupRequired = false
|
||||
mgr.setupMu.Unlock()
|
||||
|
||||
required, err = mgr.IsSetupRequired(context.Background())
|
||||
require.NoError(t, err)
|
||||
assert.False(t, required)
|
||||
}
|
||||
|
||||
func TestDefaultManager_ValidateSetupRequest(t *testing.T) {
|
||||
manager := &DefaultManager{
|
||||
setupRequired: true,
|
||||
}
|
||||
manager := &DefaultManager{setupRequired: true}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -188,11 +235,10 @@ func TestDefaultManager_ValidateSetupRequest(t *testing.T) {
|
||||
errorMsg string
|
||||
}{
|
||||
{
|
||||
name: "valid request",
|
||||
email: "admin@example.com",
|
||||
password: "password123",
|
||||
userName: "Admin User",
|
||||
expectError: false,
|
||||
name: "valid request",
|
||||
email: "admin@example.com",
|
||||
password: "password123",
|
||||
userName: "Admin User",
|
||||
},
|
||||
{
|
||||
name: "empty email",
|
||||
@@ -235,11 +281,24 @@ func TestDefaultManager_ValidateSetupRequest(t *testing.T) {
|
||||
errorMsg: "password must be at least 8 characters",
|
||||
},
|
||||
{
|
||||
name: "password exactly 8 characters",
|
||||
name: "password exactly 8 characters",
|
||||
email: "admin@example.com",
|
||||
password: "12345678",
|
||||
userName: "Admin User",
|
||||
},
|
||||
{
|
||||
name: "password exactly 72 characters",
|
||||
email: "admin@example.com",
|
||||
password: "aaaaaaaabbbbbbbbccccccccddddddddeeeeeeeeffffffffgggggggghhhhhhhhiiiiiiii",
|
||||
userName: "Admin User",
|
||||
},
|
||||
{
|
||||
name: "password too long",
|
||||
email: "admin@example.com",
|
||||
password: "12345678",
|
||||
password: "aaaaaaaabbbbbbbbccccccccddddddddeeeeeeeeffffffffgggggggghhhhhhhhiiiiiiiij",
|
||||
userName: "Admin User",
|
||||
expectError: false,
|
||||
expectError: true,
|
||||
errorMsg: "password must be at most 72 characters",
|
||||
},
|
||||
}
|
||||
|
||||
@@ -255,14 +314,3 @@ func TestDefaultManager_ValidateSetupRequest(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDefaultManager_CreateOwnerUser_SetupAlreadyCompleted(t *testing.T) {
|
||||
manager := &DefaultManager{
|
||||
setupRequired: false,
|
||||
embeddedIdpManager: &idp.EmbeddedIdPManager{},
|
||||
}
|
||||
|
||||
_, err := manager.CreateOwnerUser(context.Background(), "admin@example.com", "password123", "Admin")
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "setup already completed")
|
||||
}
|
||||
|
||||
@@ -780,9 +780,15 @@ func (am *DefaultAccountManager) processUserUpdate(ctx context.Context, transact
|
||||
updatedUser.Role = update.Role
|
||||
updatedUser.Blocked = update.Blocked
|
||||
updatedUser.AutoGroups = update.AutoGroups
|
||||
// these two fields can't be set via API, only via direct call to the method
|
||||
// these fields can't be set via API, only via direct call to the method
|
||||
updatedUser.Issued = update.Issued
|
||||
updatedUser.IntegrationReference = update.IntegrationReference
|
||||
if update.Name != "" {
|
||||
updatedUser.Name = update.Name
|
||||
}
|
||||
if update.Email != "" {
|
||||
updatedUser.Email = update.Email
|
||||
}
|
||||
|
||||
var transferredOwnerRole bool
|
||||
result, err := handleOwnerRoleTransfer(ctx, transaction, initiatorUser, update)
|
||||
|
||||
@@ -4414,6 +4414,9 @@ components:
|
||||
items:
|
||||
type: string
|
||||
example: [ "Users" ]
|
||||
connector_id:
|
||||
type: string
|
||||
description: DEX connector ID for embedded IDP setups
|
||||
IntegrationEnabled:
|
||||
type: object
|
||||
properties:
|
||||
|
||||
@@ -1492,6 +1492,9 @@ type AzureIntegration struct {
|
||||
// ClientId Azure AD application (client) ID
|
||||
ClientId string `json:"client_id"`
|
||||
|
||||
// ConnectorId DEX connector ID for embedded IDP setups
|
||||
ConnectorId *string `json:"connector_id,omitempty"`
|
||||
|
||||
// Enabled Whether the integration is enabled
|
||||
Enabled bool `json:"enabled"`
|
||||
|
||||
@@ -1632,6 +1635,9 @@ type CreateAzureIntegrationRequest struct {
|
||||
// ClientSecret Base64-encoded Azure AD client secret
|
||||
ClientSecret string `json:"client_secret"`
|
||||
|
||||
// ConnectorId DEX connector ID for embedded IDP setups
|
||||
ConnectorId *string `json:"connector_id,omitempty"`
|
||||
|
||||
// GroupPrefixes List of start_with string patterns for groups to sync
|
||||
GroupPrefixes *[]string `json:"group_prefixes,omitempty"`
|
||||
|
||||
@@ -1653,6 +1659,9 @@ type CreateAzureIntegrationRequestHost string
|
||||
|
||||
// CreateGoogleIntegrationRequest defines model for CreateGoogleIntegrationRequest.
|
||||
type CreateGoogleIntegrationRequest struct {
|
||||
// ConnectorId DEX connector ID for embedded IDP setups
|
||||
ConnectorId *string `json:"connector_id,omitempty"`
|
||||
|
||||
// CustomerId Customer ID from Google Workspace Account Settings
|
||||
CustomerId string `json:"customer_id"`
|
||||
|
||||
@@ -1689,6 +1698,9 @@ type CreateOktaScimIntegrationRequest struct {
|
||||
// ConnectionName The Okta enterprise connection name on Auth0
|
||||
ConnectionName string `json:"connection_name"`
|
||||
|
||||
// ConnectorId DEX connector ID for embedded IDP setups
|
||||
ConnectorId *string `json:"connector_id,omitempty"`
|
||||
|
||||
// GroupPrefixes List of start_with string patterns for groups to sync
|
||||
GroupPrefixes *[]string `json:"group_prefixes,omitempty"`
|
||||
|
||||
@@ -1698,6 +1710,9 @@ type CreateOktaScimIntegrationRequest struct {
|
||||
|
||||
// CreateScimIntegrationRequest defines model for CreateScimIntegrationRequest.
|
||||
type CreateScimIntegrationRequest struct {
|
||||
// ConnectorId DEX connector ID for embedded IDP setups
|
||||
ConnectorId *string `json:"connector_id,omitempty"`
|
||||
|
||||
// GroupPrefixes List of start_with string patterns for groups to sync
|
||||
GroupPrefixes *[]string `json:"group_prefixes,omitempty"`
|
||||
|
||||
@@ -2154,6 +2169,9 @@ type GetTenantsResponse = []TenantResponse
|
||||
|
||||
// GoogleIntegration defines model for GoogleIntegration.
|
||||
type GoogleIntegration struct {
|
||||
// ConnectorId DEX connector ID for embedded IDP setups
|
||||
ConnectorId *string `json:"connector_id,omitempty"`
|
||||
|
||||
// CustomerId Customer ID from Google Workspace
|
||||
CustomerId string `json:"customer_id"`
|
||||
|
||||
@@ -2502,6 +2520,9 @@ type IntegrationResponsePlatform string
|
||||
|
||||
// IntegrationSyncFilters defines model for IntegrationSyncFilters.
|
||||
type IntegrationSyncFilters struct {
|
||||
// ConnectorId DEX connector ID for embedded IDP setups
|
||||
ConnectorId *string `json:"connector_id,omitempty"`
|
||||
|
||||
// GroupPrefixes List of start_with string patterns for groups to sync
|
||||
GroupPrefixes *[]string `json:"group_prefixes,omitempty"`
|
||||
|
||||
@@ -2994,6 +3015,9 @@ type OktaScimIntegration struct {
|
||||
// AuthToken SCIM API token (full on creation/regeneration, masked on retrieval)
|
||||
AuthToken string `json:"auth_token"`
|
||||
|
||||
// ConnectorId DEX connector ID for embedded IDP setups
|
||||
ConnectorId *string `json:"connector_id,omitempty"`
|
||||
|
||||
// Enabled Whether the integration is enabled
|
||||
Enabled bool `json:"enabled"`
|
||||
|
||||
@@ -3864,6 +3888,9 @@ type ScimIntegration struct {
|
||||
// AuthToken SCIM API token (full on creation, masked otherwise)
|
||||
AuthToken string `json:"auth_token"`
|
||||
|
||||
// ConnectorId DEX connector ID for embedded IDP setups
|
||||
ConnectorId *string `json:"connector_id,omitempty"`
|
||||
|
||||
// Enabled Whether the integration is enabled
|
||||
Enabled bool `json:"enabled"`
|
||||
|
||||
@@ -4341,6 +4368,9 @@ type UpdateAzureIntegrationRequest struct {
|
||||
// ClientSecret Base64-encoded Azure AD client secret
|
||||
ClientSecret *string `json:"client_secret,omitempty"`
|
||||
|
||||
// ConnectorId DEX connector ID for embedded IDP setups
|
||||
ConnectorId *string `json:"connector_id,omitempty"`
|
||||
|
||||
// Enabled Whether the integration is enabled
|
||||
Enabled *bool `json:"enabled,omitempty"`
|
||||
|
||||
@@ -4359,6 +4389,9 @@ type UpdateAzureIntegrationRequest struct {
|
||||
|
||||
// UpdateGoogleIntegrationRequest defines model for UpdateGoogleIntegrationRequest.
|
||||
type UpdateGoogleIntegrationRequest struct {
|
||||
// ConnectorId DEX connector ID for embedded IDP setups
|
||||
ConnectorId *string `json:"connector_id,omitempty"`
|
||||
|
||||
// CustomerId Customer ID from Google Workspace Account Settings
|
||||
CustomerId *string `json:"customer_id,omitempty"`
|
||||
|
||||
@@ -4380,6 +4413,9 @@ type UpdateGoogleIntegrationRequest struct {
|
||||
|
||||
// UpdateOktaScimIntegrationRequest defines model for UpdateOktaScimIntegrationRequest.
|
||||
type UpdateOktaScimIntegrationRequest struct {
|
||||
// ConnectorId DEX connector ID for embedded IDP setups
|
||||
ConnectorId *string `json:"connector_id,omitempty"`
|
||||
|
||||
// Enabled Whether the integration is enabled
|
||||
Enabled *bool `json:"enabled,omitempty"`
|
||||
|
||||
@@ -4392,6 +4428,9 @@ type UpdateOktaScimIntegrationRequest struct {
|
||||
|
||||
// UpdateScimIntegrationRequest defines model for UpdateScimIntegrationRequest.
|
||||
type UpdateScimIntegrationRequest struct {
|
||||
// ConnectorId DEX connector ID for embedded IDP setups
|
||||
ConnectorId *string `json:"connector_id,omitempty"`
|
||||
|
||||
// Enabled Whether the integration is enabled
|
||||
Enabled *bool `json:"enabled,omitempty"`
|
||||
|
||||
|
||||
Reference in New Issue
Block a user