Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion internal/controller/tcp/cira/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ func (h *APFHandler) OnGlobalRequest(request apf.GlobalRequest) bool {
}

// ShouldSendKeepAlive returns whether keep-alive should be sent based on global request count.
// Returns true only once, when the threshold is exactly reached, to avoid sending duplicate requests.
func (h *APFHandler) ShouldSendKeepAlive() bool {
return h.globalRequestCount >= globalRequestThreshold
return h.globalRequestCount == globalRequestThreshold
}
27 changes: 27 additions & 0 deletions internal/controller/tcp/cira/tunnel.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package cira

import (
"bytes"
"context"
"crypto/tls"
"encoding/binary"
"encoding/hex"
Expand Down Expand Up @@ -122,6 +123,7 @@ type connectionContext struct {
session *apf.Session
authenticated bool
device *wsman.ConnectionEntry
devices devices.Feature
log logger.Interface
}

Expand All @@ -141,6 +143,7 @@ func (s *Server) handleConnection(conn net.Conn) {
conn: conn,
tlsConn: tlsConn,
handler: NewAPFHandler(s.devices, s.log),
devices: s.devices,
session: &apf.Session{
Timer: time.NewTimer(apfSessionTimeout),
},
Expand All @@ -156,6 +159,10 @@ func (s *Server) handleConnection(conn net.Conn) {
func (ctx *connectionContext) cleanup() {
deviceID := ctx.handler.DeviceID()
if ctx.authenticated && deviceID != "" {
if err := ctx.devices.UpdateConnectionStatus(context.Background(), deviceID, false); err != nil {
ctx.log.Error("Failed to update disconnection status for device %s: %v", deviceID, err)
}

wsman.RemoveConnection(deviceID)
}

Expand Down Expand Up @@ -211,12 +218,28 @@ func (ctx *connectionContext) processNextMessage() (shouldReturn bool) {
}

if err := ctx.sendKeepAliveIfNeeded(messageType); err != nil {
ctx.log.Error("Keep-alive failed for device %s: %v", ctx.handler.DeviceID(), err)

return true
}

ctx.updateLastSeenIfKeepAlive(messageType)

return false
}

func (ctx *connectionContext) updateLastSeenIfKeepAlive(messageType byte) {
if !ctx.authenticated || messageType != apf.APF_KEEPALIVE_REQUEST {
return
}

deviceID := ctx.handler.DeviceID()

if err := ctx.devices.UpdateLastSeen(context.Background(), deviceID); err != nil {
ctx.log.Error("Failed to update last seen for device %s: %v", deviceID, err)
}
}

func (ctx *connectionContext) readData() ([]byte, error) {
buf := make([]byte, readBufferSize)

Expand Down Expand Up @@ -279,6 +302,10 @@ func (ctx *connectionContext) registerDevice() {

wsman.SetConnectionEntry(deviceID, ctx.device)

if err := ctx.devices.UpdateConnectionStatus(context.Background(), deviceID, true); err != nil {
ctx.log.Error("Failed to update connection status for device %s: %v", deviceID, err)
}

ctx.log.Info("Device authenticated and registered: %s", deviceID)
}

Expand Down
115 changes: 111 additions & 4 deletions internal/controller/tcp/cira/tunnel_test.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
package cira

import (
"errors"
"net"
"testing"
"time"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/mock/gomock"

"github.com/device-management-toolkit/go-wsman-messages/v2/pkg/apf"

"github.com/device-management-toolkit/console/internal/mocks"
"github.com/device-management-toolkit/console/internal/usecase/devices"
"github.com/device-management-toolkit/console/internal/usecase/devices/wsman"
"github.com/device-management-toolkit/console/pkg/logger"
)
Expand Down Expand Up @@ -96,6 +101,35 @@ var cleanupTests = []cleanupTestCase{
},
}

func TestConnectionContext_cleanup_UpdateConnectionStatusError(t *testing.T) {
t.Parallel()

ctrl := gomock.NewController(t)
mockDevices := mocks.NewMockDeviceManagementFeature(ctrl)
mockDevices.EXPECT().UpdateConnectionStatus(gomock.Any(), "test-device", false).Return(errors.New("db error"))

log := logger.New("error")
handler := NewAPFHandler(mockDevices, log)
handler.deviceID = "test-device"

session := &apf.Session{Timer: time.NewTimer(10 * time.Second)}
ctx := &connectionContext{
session: session,
authenticated: true,
handler: handler,
devices: mockDevices,
log: log,
}

wsman.SetConnectionEntry("test-device", &wsman.ConnectionEntry{})

require.NotPanics(t, func() {
ctx.cleanup()
})

assert.Nil(t, wsman.GetConnectionEntry("test-device"), "Connection should still be removed even on status update failure")
}

func TestConnectionContext_cleanup(t *testing.T) {
t.Parallel()

Expand All @@ -112,9 +146,19 @@ func TestConnectionContext_cleanup(t *testing.T) {
func runCleanupTest(t *testing.T, tt cleanupTestCase) {
t.Helper()

ctrl := gomock.NewController(t)
mockDevices := mocks.NewMockDeviceManagementFeature(ctrl)

var devicesFeature devices.Feature

if tt.authenticated && tt.deviceID != "" {
mockDevices.EXPECT().UpdateConnectionStatus(gomock.Any(), tt.deviceID, false).Return(nil)
devicesFeature = mockDevices
}

// Setup
session := tt.setupSession()
ctx := setupConnectionContext(t, session, tt.authenticated, tt.deviceID)
ctx := setupConnectionContext(t, session, tt.authenticated, tt.deviceID, devicesFeature)

setupConnectionsMap(t, tt.authenticated, tt.deviceID)

Expand All @@ -128,18 +172,19 @@ func runCleanupTest(t *testing.T, tt cleanupTestCase) {
verifyConnectionRemoved(t, tt.authenticated, tt.deviceID)
}

func setupConnectionContext(t *testing.T, session *apf.Session, authenticated bool, deviceID string) *connectionContext {
func setupConnectionContext(t *testing.T, session *apf.Session, authenticated bool, deviceID string, devicesFeature devices.Feature) *connectionContext {
t.Helper()

// Create a proper APFHandler with mock deviceID
log := logger.New("error")
handler := NewAPFHandler(nil, log) // devices.Feature can be nil for cleanup test
handler.deviceID = deviceID // Set deviceID directly for test
handler := NewAPFHandler(devicesFeature, log)
handler.deviceID = deviceID

return &connectionContext{
session: session,
authenticated: authenticated,
handler: handler,
devices: devicesFeature,
}
}

Expand Down Expand Up @@ -173,3 +218,65 @@ func verifyConnectionRemoved(t *testing.T, authenticated bool, deviceID string)
assert.False(t, exists, "Connection should be removed from map")
}
}

// fakeConn is a minimal net.Conn implementation for tests.
type fakeConn struct{ net.Conn }

func TestConnectionContext_registerDevice(t *testing.T) {
t.Parallel()

t.Run("successful registration updates connection status", func(t *testing.T) {
t.Parallel()

ctrl := gomock.NewController(t)

mockDevices := mocks.NewMockDeviceManagementFeature(ctrl)
mockDevices.EXPECT().UpdateConnectionStatus(gomock.Any(), "dev-123", true).Return(nil)

log := logger.New("error")
handler := NewAPFHandler(mockDevices, log)
handler.deviceID = "dev-123"

ctx := &connectionContext{
conn: &fakeConn{},
handler: handler,
devices: mockDevices,
log: log,
}

ctx.registerDevice()

assert.True(t, ctx.authenticated)
assert.NotNil(t, ctx.device)
assert.NotNil(t, wsman.GetConnectionEntry("dev-123"))

t.Cleanup(func() { wsman.RemoveConnection("dev-123") })
})

t.Run("registration continues when UpdateConnectionStatus fails", func(t *testing.T) {
t.Parallel()

ctrl := gomock.NewController(t)

mockDevices := mocks.NewMockDeviceManagementFeature(ctrl)
mockDevices.EXPECT().UpdateConnectionStatus(gomock.Any(), "dev-456", true).Return(errors.New("db error"))

log := logger.New("error")
handler := NewAPFHandler(mockDevices, log)
handler.deviceID = "dev-456"

ctx := &connectionContext{
conn: &fakeConn{},
handler: handler,
devices: mockDevices,
log: log,
}

ctx.registerDevice()

assert.True(t, ctx.authenticated)
assert.NotNil(t, wsman.GetConnectionEntry("dev-456"))

t.Cleanup(func() { wsman.RemoveConnection("dev-456") })
})
}
2 changes: 2 additions & 0 deletions internal/controller/ws/v1/interface.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ type Feature interface {
GetCount(context.Context, string) (int, error)
Get(ctx context.Context, top, skip int, tenantID string) ([]dto.Device, error)
GetByID(ctx context.Context, guid, tenantID string, includeSecrets bool) (*dto.Device, error)
UpdateConnectionStatus(ctx context.Context, guid string, status bool) error
UpdateLastSeen(ctx context.Context, guid string) error
GetDistinctTags(ctx context.Context, tenantID string) ([]string, error)
GetByTags(ctx context.Context, tags, method string, limit, offset int, tenantID string) ([]dto.Device, error)
Delete(ctx context.Context, guid, tenantID string) error
Expand Down
56 changes: 56 additions & 0 deletions internal/mocks/devicemanagement_mocks.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

28 changes: 28 additions & 0 deletions internal/mocks/wsv1_mocks.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions internal/usecase/devices/interfaces.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,16 @@ type (
Update(ctx context.Context, d *entity.Device) (bool, error)
Insert(ctx context.Context, d *entity.Device) (string, error)
GetByColumn(ctx context.Context, columnName, queryValue, tenantID string) ([]entity.Device, error)
UpdateConnectionStatus(ctx context.Context, guid string, status bool) error
UpdateLastSeen(ctx context.Context, guid string) error
}
Feature interface {
// Repository/Database Calls
GetCount(context.Context, string) (int, error)
Get(ctx context.Context, top, skip int, tenantID string) ([]dto.Device, error)
GetByID(ctx context.Context, guid, tenantID string, includeSecrets bool) (*dto.Device, error)
UpdateConnectionStatus(ctx context.Context, guid string, status bool) error
UpdateLastSeen(ctx context.Context, guid string) error
GetDistinctTags(ctx context.Context, tenantID string) ([]string, error)
GetByTags(ctx context.Context, tags, method string, limit, offset int, tenantID string) ([]dto.Device, error)
Delete(ctx context.Context, guid, tenantID string) error
Expand Down
18 changes: 18 additions & 0 deletions internal/usecase/devices/repo.go
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,24 @@ func (uc *UseCase) GetByTags(ctx context.Context, tags, method string, limit, of
return d1, nil
}

func (uc *UseCase) UpdateConnectionStatus(ctx context.Context, guid string, status bool) error {
err := uc.repo.UpdateConnectionStatus(ctx, strings.ToLower(guid), status)
if err != nil {
return ErrDatabase.Wrap("UpdateConnectionStatus", "uc.repo.UpdateConnectionStatus", err)
}

return nil
}

func (uc *UseCase) UpdateLastSeen(ctx context.Context, guid string) error {
err := uc.repo.UpdateLastSeen(ctx, strings.ToLower(guid))
if err != nil {
return ErrDatabase.Wrap("UpdateLastSeen", "uc.repo.UpdateLastSeen", err)
}

return nil
}

func (uc *UseCase) Delete(ctx context.Context, guid, tenantID string) error {
isSuccessful, err := uc.repo.Delete(ctx, strings.ToLower(guid), tenantID)
if err != nil {
Expand Down
Loading
Loading