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
24 changes: 21 additions & 3 deletions pkg/infrastructure/cluster.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
//
// Copyright (c) 2019-2025 Red Hat, Inc.
// Copyright (c) 2019-2026 Red Hat, Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
Expand Down Expand Up @@ -35,8 +35,9 @@ const (

var (
// current is the infrastructure that we're currently running on.
current Type
initialized = false
current Type
certManagerDetected bool
initialized = false
)

// Initialize attempts to determine the type of cluster its currently running on (OpenShift or Kubernetes). This function
Expand All @@ -57,6 +58,14 @@ func Initialize() error {
// InitializeForTesting is used to mock running on a specific type of cluster (Kubernetes, OpenShift) in testing code.
func InitializeForTesting(currentInfrastructure Type) {
current = currentInfrastructure
certManagerDetected = false
initialized = true
}

// InitializeForTestingWithCertManager is used to mock running on a cluster with cert-manager installed.
func InitializeForTestingWithCertManager(currentInfrastructure Type) {
current = currentInfrastructure
certManagerDetected = true
initialized = true
}

Expand All @@ -72,6 +81,14 @@ func IsOpenShift() bool {
return current == OpenShiftv4
}

// CertManagerDetected returns true if the cert-manager API group was detected on the cluster.
func CertManagerDetected() bool {
if !initialized {
panic("Attempting to determine information about the cluster without initializing first")
}
return certManagerDetected
}

func detect() (Type, error) {
kubeCfg, err := config.GetConfig()
if err != nil {
Expand All @@ -85,6 +102,7 @@ func detect() (Type, error) {
if err != nil {

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.

Does it make sense to move the certManagerDetected assignment into Initialize() alongside the detect() call, rather than inside detect() as a side effect? The function's name and (Type, error) return type suggest it only determines the cluster type, so the hidden side effect is a bit surprising. It also makes detect() harder to test in isolation and is architecturally inconsistent with how OpenShift detection works (returned as a value, not a side effect). One option: return a richer struct from detect() (e.g., DetectionResult{InfraType, CertManagerAvailable}) or call a separate function from Initialize().

return Unsupported, fmt.Errorf("could not read API groups: %w", err)
}
certManagerDetected = findAPIGroup(apiList.Groups, "cert-manager.io") != nil
if findAPIGroup(apiList.Groups, "route.openshift.io") == nil {
return Kubernetes, nil
} else {
Expand Down
58 changes: 58 additions & 0 deletions pkg/infrastructure/cluster_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
//
// Copyright (c) 2019-2026 Red Hat, Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

package infrastructure

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestCertManagerDetectedReturnsTrueWhenCertManagerInstalled(t *testing.T) {
InitializeForTestingWithCertManager(Kubernetes)
assert.True(t, CertManagerDetected())
}

func TestCertManagerDetectedReturnsFalseWhenCertManagerNotInstalled(t *testing.T) {
InitializeForTesting(Kubernetes)
assert.False(t, CertManagerDetected())
}

func TestCertManagerDetectedWithOpenShift(t *testing.T) {
InitializeForTestingWithCertManager(OpenShiftv4)
assert.True(t, CertManagerDetected())
}

func TestCertManagerDetectedPanicsWhenNotInitialized(t *testing.T) {
initialized = false
defer func() {

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.

Consider using t.Cleanup() to restore the global state after this test instead of (or in addition to) the defer. The defer resets to Kubernetes after the panic test, but if the test panics in an unexpected way before the deferred function runs, subsequent tests in the same package may see initialized = false. A t.Cleanup or a helper that captures and restores all three package-level variables (current, certManagerDetected, initialized) would make the test order-independent. Also worth noting in the file or test that these tests cannot use t.Parallel() due to shared mutable package state.

InitializeForTesting(Kubernetes)
}()
assert.Panics(t, func() {
CertManagerDetected()
})
}

func TestInitializeForTestingSetsCertManagerDetectedToFalse(t *testing.T) {
InitializeForTesting(OpenShiftv4)
assert.False(t, CertManagerDetected())
assert.True(t, IsOpenShift())
}

func TestInitializeForTestingWithCertManagerSetsDetectedToTrue(t *testing.T) {
InitializeForTestingWithCertManager(Kubernetes)
assert.True(t, CertManagerDetected())
}
32 changes: 32 additions & 0 deletions webhook/workspace/annotations.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
//
// Copyright (c) 2019-2026 Red Hat, Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

package workspace

import (
"fmt"

"github.com/devfile/devworkspace-operator/pkg/infrastructure"
)

func getWebhookAnnotations(namespace string) map[string]string {
annotations := map[string]string{}

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.

Consider adding a brief comment here explaining why cert-manager takes priority over the OpenShift Service CA annotation. The ordering is intentional and correct, but without a comment a future maintainer may read the else if as arbitrary ordering rather than a deliberate policy decision. Something like: // cert-manager takes precedence when installed on OpenShift; mixing both annotations can cause conflicts.

if infrastructure.CertManagerDetected() {
annotations["cert-manager.io/inject-ca-from"] = fmt.Sprintf("%s/devworkspace-controller-serving-cert", namespace)
} else if infrastructure.IsOpenShift() {

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.

Consider extracting devworkspace-controller-serving-cert to a named constant, similar to how MutateWebhookCfgName and ValidateWebhookCfgName are defined. This string is the post-kustomize composed name (from namePrefix: devworkspace-controller- applied to base name serving-cert in deploy/templates/components/cert-manager/self-signed-certificates.yaml). If the namePrefix changes, the kustomize-generated CRD webhook patches update automatically but this code silently breaks - cert-manager cainjector would find no Certificate and log errors without injecting the CA bundle. A constant (or at minimum a comment documenting the coupling and the kustomize file that must stay in sync) makes the contract explicit.

annotations["service.beta.openshift.io/inject-cabundle"] = "true"
}
return annotations
}
53 changes: 53 additions & 0 deletions webhook/workspace/annotations_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
//
// Copyright (c) 2019-2026 Red Hat, Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

package workspace

import (
"testing"

"github.com/devfile/devworkspace-operator/pkg/infrastructure"
"github.com/stretchr/testify/assert"
)

func TestGetWebhookAnnotationsWithCertManager(t *testing.T) {
infrastructure.InitializeForTestingWithCertManager(infrastructure.Kubernetes)
annotations := getWebhookAnnotations("test-namespace")
assert.Equal(t, map[string]string{
"cert-manager.io/inject-ca-from": "test-namespace/devworkspace-controller-serving-cert",
}, annotations)
}

func TestGetWebhookAnnotationsWithOpenShift(t *testing.T) {
infrastructure.InitializeForTesting(infrastructure.OpenShiftv4)
annotations := getWebhookAnnotations("test-namespace")
assert.Equal(t, map[string]string{
"service.beta.openshift.io/inject-cabundle": "true",
}, annotations)
}

func TestGetWebhookAnnotationsWithKubernetes(t *testing.T) {
infrastructure.InitializeForTesting(infrastructure.Kubernetes)
annotations := getWebhookAnnotations("test-namespace")
assert.Empty(t, annotations)
}

func TestGetWebhookAnnotationsWithCertManagerOnOpenShift(t *testing.T) {
infrastructure.InitializeForTestingWithCertManager(infrastructure.OpenShiftv4)
annotations := getWebhookAnnotations("test-namespace")
assert.Equal(t, map[string]string{
"cert-manager.io/inject-ca-from": "test-namespace/devworkspace-controller-serving-cert",
}, annotations)
}
7 changes: 4 additions & 3 deletions webhook/workspace/mutating_cfg.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
//
// Copyright (c) 2019-2025 Red Hat, Inc.
// Copyright (c) 2019-2026 Red Hat, Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
Expand Down Expand Up @@ -153,8 +153,9 @@ func BuildMutateWebhookCfg(namespace string) *admregv1.MutatingWebhookConfigurat

return &admregv1.MutatingWebhookConfiguration{
ObjectMeta: metav1.ObjectMeta{
Name: MutateWebhookCfgName,
Labels: server.WebhookServerAppLabels(),
Name: MutateWebhookCfgName,
Labels: server.WebhookServerAppLabels(),
Annotations: getWebhookAnnotations(namespace),

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.

When cert-manager or the OpenShift Service CA operator is active, the webhook config will have both an explicit CABundle (written from the cert file on disk by the caller) and a CA-injection annotation. During a cert rotation the operator may write a stale CABundle and the external controller will overwrite it - creating a brief window with a mismatched CA. Would it be possible to omit CABundle from WebhookClientConfig when CertManagerDetected() is true (or when using the OpenShift annotation), letting the external controller be the sole authority? The cert-manager CRD patch in deploy/templates/cert-manager/crd_webhooks_patch.yaml already follows this pattern, with a comment "caBundle will be filled by cert-manager on creation".

},
Webhooks: []admregv1.MutatingWebhook{
workspaceMutateWebhook,
Expand Down
7 changes: 4 additions & 3 deletions webhook/workspace/validating_cfg.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
//
// Copyright (c) 2019-2025 Red Hat, Inc.
// Copyright (c) 2019-2026 Red Hat, Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
Expand Down Expand Up @@ -34,8 +34,9 @@ func buildValidatingWebhookCfg(namespace string) *admregv1.ValidatingWebhookConf
sideEffectsNone := admregv1.SideEffectClassNone
return &admregv1.ValidatingWebhookConfiguration{
ObjectMeta: metav1.ObjectMeta{
Name: ValidateWebhookCfgName,
Labels: server.WebhookServerAppLabels(),
Name: ValidateWebhookCfgName,
Labels: server.WebhookServerAppLabels(),
Annotations: getWebhookAnnotations(namespace),
},
Webhooks: []admregv1.ValidatingWebhook{
{
Expand Down
Loading