Skip to content
Open
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
56 changes: 56 additions & 0 deletions central/cluster/service/convert.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package service

import (
v1 "github.com/stackrox/rox/generated/api/v1"
"github.com/stackrox/rox/generated/storage"
clusterutil "github.com/stackrox/rox/pkg/cluster"
)

// convertStorageClusterToAPI delegates to the shared conversion in pkg/cluster.
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (complexity): Consider removing the package-level conversion vars and centralizing both directions of cluster conversion in pkg/cluster so this service just calls the shared helpers directly.

You can simplify this by:

  1. Removing the package-level function variables and calling the shared conversion directly.
  2. Centralizing the API→storage conversion in pkg/cluster alongside the existing storage→API helpers, so we only have one implementation per direction.

1. Inline the function variables

Instead of:

// convertStorageClusterToAPI delegates to the shared conversion in pkg/cluster.
var convertStorageClusterToAPI = clusterutil.StorageClusterToAPIClusterConfig

// convertStorageClustersToAPI delegates to the shared conversion in pkg/cluster.
var convertStorageClustersToAPI = clusterutil.StorageClustersToAPIClusterConfigs

Call the shared helpers directly where used:

cfg := clusterutil.StorageClusterToAPIClusterConfig(sc)
// or
cfgs := clusterutil.StorageClustersToAPIClusterConfigs(storageClusters)

If you need test seams, define a small interface on the consumer side rather than package-level vars, e.g.:

type ClusterConverter interface {
    ToAPI(*storage.Cluster) *v1.ClusterConfig
}

type defaultClusterConverter struct{}

func (defaultClusterConverter) ToAPI(c *storage.Cluster) *v1.ClusterConfig {
    return clusterutil.StorageClusterToAPIClusterConfig(c)
}

and inject a ClusterConverter in tests.

2. Move convertAPIClusterToStorage to pkg/cluster

To avoid having a third independent conversion implementation, move the inverse logic into pkg/cluster (or extend the existing one there) and call it from this service.

In pkg/cluster/convert.go:

func APIClusterConfigToStorage(config *v1.ClusterConfig) *storage.Cluster {
    if config == nil {
        return nil
    }
    return &storage.Cluster{
        Id:                             config.GetId(),
        Name:                           config.GetName(),
        Type:                           config.GetType(),
        Labels:                         config.GetLabels(),
        MainImage:                      config.GetMainImage(),
        CollectorImage:                 config.GetCollectorImage(),
        CentralApiEndpoint:             config.GetCentralApiEndpoint(),
        CollectionMethod:               config.GetCollectionMethod(),
        AdmissionController:            config.GetAdmissionController(),
        AdmissionControllerUpdates:     config.GetAdmissionControllerUpdates(),
        AdmissionControllerEvents:      config.GetAdmissionControllerEvents(),
        AdmissionControllerFailOnError: config.GetAdmissionControllerFailOnError(),
        DynamicConfig:                  config.GetDynamicConfig(),
        TolerationsConfig:              config.GetTolerationsConfig(),
        SlimCollector:                  config.GetSlimCollector(),
        Priority:                       config.GetPriority(),
        ManagedBy:                      config.GetManagedBy(),
        // intentionally omit server-managed fields here
    }
}

Then in this service:

func convertAPIClusterToStorage(config *v1.ClusterConfig) *storage.Cluster {
    return clusterutil.APIClusterConfigToStorage(config)
}

or even skip the local wrapper entirely and call clusterutil.APIClusterConfigToStorage directly.

This keeps all behavior (including the “server-managed fields are ignored” policy) in one place, reducing divergence risk and making the conversion story easier to understand.

var convertStorageClusterToAPI = clusterutil.StorageClusterToAPIClusterConfig

// convertStorageClustersToAPI delegates to the shared conversion in pkg/cluster.
var convertStorageClustersToAPI = clusterutil.StorageClustersToAPIClusterConfigs

// convertAPIClusterToStorage converts an API ClusterConfig to storage.Cluster for persistence.
//
// Server-managed fields (status, health_status, most_recent_sensor_id,
// sensor_capabilities, audit_log_state, helm_config, init_bundle_id) are
// intentionally NOT copied from the API request. If a client sends values
// for these fields, they are silently ignored. This preserves backward
// compatibility with older clients that may send the full object on update,
// while ensuring server-authoritative fields are never overwritten by clients.
// The server always populates these fields from its own state.
func convertAPIClusterToStorage(config *v1.ClusterConfig) *storage.Cluster {
if config == nil {
return nil
}
return &storage.Cluster{
Id: config.GetId(),
Name: config.GetName(),
Type: config.GetType(),
Labels: config.GetLabels(),
MainImage: config.GetMainImage(),
CollectorImage: config.GetCollectorImage(),
CentralApiEndpoint: config.GetCentralApiEndpoint(),
CollectionMethod: config.GetCollectionMethod(),
AdmissionController: config.GetAdmissionController(),
AdmissionControllerUpdates: config.GetAdmissionControllerUpdates(),
AdmissionControllerEvents: config.GetAdmissionControllerEvents(),
AdmissionControllerFailOnError: config.GetAdmissionControllerFailOnError(),
DynamicConfig: config.GetDynamicConfig(),
TolerationsConfig: config.GetTolerationsConfig(),
SlimCollector: config.GetSlimCollector(),
Priority: config.GetPriority(),
ManagedBy: config.GetManagedBy(),
// Server-managed fields below are intentionally omitted.
// Values sent by clients for these fields are silently discarded:
// - Status
// - HealthStatus
// - HelmConfig
// - MostRecentSensorId
// - AuditLogState
// - InitBundleId
// - SensorCapabilities
}
}
97 changes: 97 additions & 0 deletions central/cluster/service/convert_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
package service

import (
"testing"

v1 "github.com/stackrox/rox/generated/api/v1"
"github.com/stackrox/rox/generated/storage"
"github.com/stackrox/rox/pkg/protoassert"
"github.com/stretchr/testify/assert"
)

func TestConvertAPIClusterToStorage_Nil(t *testing.T) {
assert.Nil(t, convertAPIClusterToStorage(nil))
}

func TestConvertAPIClusterToStorage_UserSettableFields(t *testing.T) {
config := &v1.ClusterConfig{
Id: "test-id",
Name: "test-cluster",
Type: storage.ClusterType_KUBERNETES_CLUSTER,
Labels: map[string]string{"env": "dev"},
MainImage: "quay.io/stackrox/main:latest",
CollectorImage: "quay.io/stackrox/collector:latest",
CentralApiEndpoint: "central.stackrox:443",
CollectionMethod: storage.CollectionMethod_CORE_BPF,
AdmissionController: true,
AdmissionControllerUpdates: true,
AdmissionControllerEvents: true,
AdmissionControllerFailOnError: true,
DynamicConfig: &storage.DynamicClusterConfig{
DisableAuditLogs: true,
},
TolerationsConfig: &storage.TolerationsConfig{
Disabled: true,
},
SlimCollector: true,
Priority: 5,
ManagedBy: storage.ManagerType_MANAGER_TYPE_HELM_CHART,
}

result := convertAPIClusterToStorage(config)

assert.Equal(t, config.GetId(), result.GetId())
assert.Equal(t, config.GetName(), result.GetName())
assert.Equal(t, config.GetType(), result.GetType())
assert.Equal(t, config.GetLabels(), result.GetLabels())
assert.Equal(t, config.GetMainImage(), result.GetMainImage())
assert.Equal(t, config.GetCollectorImage(), result.GetCollectorImage())
assert.Equal(t, config.GetCentralApiEndpoint(), result.GetCentralApiEndpoint())
assert.Equal(t, config.GetCollectionMethod(), result.GetCollectionMethod())
assert.Equal(t, config.GetAdmissionController(), result.GetAdmissionController())
assert.Equal(t, config.GetAdmissionControllerUpdates(), result.GetAdmissionControllerUpdates())
assert.Equal(t, config.GetAdmissionControllerEvents(), result.GetAdmissionControllerEvents())
assert.Equal(t, config.GetAdmissionControllerFailOnError(), result.GetAdmissionControllerFailOnError())
protoassert.Equal(t, config.GetDynamicConfig(), result.GetDynamicConfig())
protoassert.Equal(t, config.GetTolerationsConfig(), result.GetTolerationsConfig())
assert.Equal(t, config.GetSlimCollector(), result.GetSlimCollector())
assert.Equal(t, config.GetPriority(), result.GetPriority())
assert.Equal(t, config.GetManagedBy(), result.GetManagedBy())
}

func TestConvertAPIClusterToStorage_ServerManagedFieldsIgnored(t *testing.T) {
config := &v1.ClusterConfig{
Id: "test-id",
Name: "test-cluster",
// Server-managed fields that should be silently discarded
Status: &storage.ClusterStatus{
SensorVersion: "3.0.0",
},
HealthStatus: &storage.ClusterHealthStatus{
SensorHealthStatus: storage.ClusterHealthStatus_HEALTHY,
},
HelmConfig: &storage.CompleteClusterConfig{
ClusterLabels: map[string]string{"helm": "true"},
},
MostRecentSensorId: &storage.SensorDeploymentIdentification{
SystemNamespaceId: "ns-id",
},
AuditLogState: map[string]*storage.AuditLogFileState{
"node1": {CollectLogsSince: nil},
},
InitBundleId: "init-bundle-123",
SensorCapabilities: []string{"cap1", "cap2"},
}

result := convertAPIClusterToStorage(config)

assert.Equal(t, "test-id", result.GetId())
assert.Equal(t, "test-cluster", result.GetName())
assert.Nil(t, result.GetStatus())
assert.Nil(t, result.GetHealthStatus())
assert.Nil(t, result.GetHelmConfig())
assert.Nil(t, result.GetMostRecentSensorId())
assert.Nil(t, result.GetAuditLogState())
assert.Empty(t, result.GetInitBundleId())
assert.Nil(t, result.GetSensorCapabilities())
}
17 changes: 9 additions & 8 deletions central/cluster/service/service_impl.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,24 +69,25 @@ func (s *serviceImpl) AuthFuncOverride(ctx context.Context, fullMethodName strin
}

// PostCluster creates a new cluster.
func (s *serviceImpl) PostCluster(ctx context.Context, request *storage.Cluster) (*v1.ClusterResponse, error) {
func (s *serviceImpl) PostCluster(ctx context.Context, request *v1.ClusterConfig) (*v1.ClusterResponse, error) {
if request.GetId() != "" {
return nil, errors.Wrap(errox.InvalidArgs, "Id field should be empty when posting a new cluster")
}
id, err := s.datastore.AddCluster(ctx, request)
cluster := convertAPIClusterToStorage(request)
id, err := s.datastore.AddCluster(ctx, cluster)
if err != nil {
return nil, err
}
request.Id = id
return s.getCluster(ctx, request.GetId())
return s.getCluster(ctx, id)
}

// PutCluster updates an existing cluster.
func (s *serviceImpl) PutCluster(ctx context.Context, request *storage.Cluster) (*v1.ClusterResponse, error) {
func (s *serviceImpl) PutCluster(ctx context.Context, request *v1.ClusterConfig) (*v1.ClusterResponse, error) {
if request.GetId() == "" {
return nil, errors.Wrap(errox.InvalidArgs, "Id must be provided")
}
err := s.datastore.UpdateCluster(ctx, request)
cluster := convertAPIClusterToStorage(request)
err := s.datastore.UpdateCluster(ctx, cluster)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -116,7 +117,7 @@ func (s *serviceImpl) getCluster(ctx context.Context, id string) (*v1.ClusterRes
}

return &v1.ClusterResponse{
Cluster: cluster,
Cluster: convertStorageClusterToAPI(cluster),
ClusterRetentionInfo: clusterRetentionInfo,
}, nil
}
Expand Down Expand Up @@ -190,7 +191,7 @@ func (s *serviceImpl) GetClusters(ctx context.Context, req *v1.GetClustersReques
}

return &v1.ClustersList{
Clusters: clusters,
Clusters: convertStorageClustersToAPI(clusters),
ClusterIdToRetentionInfo: clusterIDToRetentionInfoMap,
}, nil
}
Expand Down
6 changes: 3 additions & 3 deletions config-controller/pkg/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ type CentralClient interface {
PutPolicy(context.Context, *storage.Policy) error
DeletePolicy(ctx context.Context, id string) error
ListNotifiers(ctx context.Context) ([]*storage.Notifier, error)
ListClusters(ctx context.Context) ([]*storage.Cluster, error)
ListClusters(ctx context.Context) ([]*v1.ClusterConfig, error)
TokenExchange(ctx context.Context) error
}

Expand Down Expand Up @@ -165,10 +165,10 @@ func (gc *grpcClient) ListNotifiers(ctx context.Context) ([]*storage.Notifier, e
return allNotifiers.GetNotifiers(), nil
}

func (gc *grpcClient) ListClusters(ctx context.Context) ([]*storage.Cluster, error) {
func (gc *grpcClient) ListClusters(ctx context.Context) ([]*v1.ClusterConfig, error) {
allClusters, err := gc.clusterSvc.GetClusters(ctx, &v1.GetClustersRequest{})
if err != nil {
return []*storage.Cluster{}, errors.Wrap(err, "Failed to list clusters from grpc client")
return []*v1.ClusterConfig{}, errors.Wrap(err, "Failed to list clusters from grpc client")
}

return allClusters.GetClusters(), nil
Expand Down
5 changes: 3 additions & 2 deletions config-controller/pkg/client/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"time"

"github.com/stackrox/rox/config-controller/pkg/client/mocks"
v1 "github.com/stackrox/rox/generated/api/v1"
"github.com/stackrox/rox/generated/storage"
"github.com/stackrox/rox/pkg/protoassert"
"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -69,8 +70,8 @@ func listNotifiers() []*storage.Notifier {
}
}

func listClusters() []*storage.Cluster {
return []*storage.Cluster{
func listClusters() []*v1.ClusterConfig {
return []*v1.ClusterConfig{
{
Id: "cluster-1",
Name: "Cluster1",
Expand Down
5 changes: 3 additions & 2 deletions config-controller/pkg/client/mocks/client.go

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

Loading
Loading