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
70 changes: 70 additions & 0 deletions .golangci.bck.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# This file contains all available configuration options
# with their default values.

# options for analysis running
run:
# default concurrency is a available CPU number
concurrency: 4

# timeout for analysis, e.g. 30s, 5m, default is 1m
timeout: 5m

# exit code when at least one issue was found, default is 1
issues-exit-code: 1

# include test files or not, default is true
tests: true
# list of build tags, all linters use it. Default is empty list.
build-tags:
- e2e

# by default isn't set. If set we pass it to "go list -mod={option}". From "go help modules":
# If invoked with -mod=readonly, the go command is disallowed from the implicit
# automatic updating of go.mod described above. Instead, it fails when any changes
# to go.mod are needed. This setting is most useful to check that go.mod does
# not need updates, such as in a continuous integration and testing system.
# If invoked with -mod=vendor, the go command assumes that the vendor
# directory holds the correct copies of dependencies and ignores
# the dependency descriptions in go.mod.
modules-download-mode: vendor

# Allow multiple parallel golangci-lint instances running.
# If false (default) - golangci-lint acquires file lock on start.
allow-parallel-runners: false


# output configuration options
output:
# print lines of code with issue, default is true
print-issued-lines: true

# print linter name in the end of issue text, default is true
print-linter-name: true

# add a prefix to the output file references; default is no prefix
path-prefix: ""

# sorts results by: filepath, line and column
sort-results: false

linters:
disable-all: true
enable:
- errcheck
- gofmt
- goimports
- gosec
- gosimple
- govet
- ineffassign
- misspell
- staticcheck
- typecheck
- unused
fast: false

linters-settings:
goimports:
# put imports beginning with prefix after 3rd-party packages;
# it's a comma-separated list of prefixes
local-prefixes: github.com/openshift/cert-manager-operator
142 changes: 142 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Project Overview

This is the Cert Manager Operator for OpenShift. It deploys and manages the upstream cert-manager project on OpenShift clusters. The operator runs in the `cert-manager-operator` namespace and deploys its operand (cert-manager) in the `cert-manager` namespace - both namespaces are hardcoded.

## Common Commands

### Building and Running

```bash
# Build the operator binary
make build

# Build operator binary only (skip code generation and checks)
make build-operator

# Run operator locally (requires connection to OpenShift cluster)
make deploy # Install operator manifests and CRDs
oc scale --replicas=0 deploy --all -n cert-manager-operator # Scale down cluster operator
make local-run # Run operator locally

# Build and push container image
export IMG=<registry>/<repository>/cert-manager-operator:<tag>
make image-build image-push
```

### Testing

```bash
# Run unit tests
make test

# Run a single test
go test -v ./pkg/controller/deployment/... -run TestDeploymentOverrides

# Run e2e tests (requires deployed operator in cluster)
make test-e2e

# Run e2e tests with specific label filter
make test-e2e E2E_GINKGO_LABEL_FILTER="Platform: isSubsetOf {AWS}"
```

### Code Quality

```bash
# Run linter
make lint

# Format code
make fmt

# Run go vet
make vet

# Update generated code (deepcopy, clientgen, manifests, bindata)
make update

# Verify generated code is up to date
make verify
```

### Updating cert-manager Version

1. Update `CERT_MANAGER_VERSION` in the Makefile
2. Run `make update` to regenerate manifests and bindata

## Architecture

### Controller Structure

The operator uses OpenShift's library-go controller framework. The main entry point is `pkg/operator/starter.go` which initializes:

- **CertManagerControllerSet** (`pkg/controller/deployment/cert_manager_controller_set.go`): A collection of 8 controllers managing cert-manager components:
- Controller deployment + static resources
- Webhook deployment + static resources
- CAInjector deployment + static resources
- NetworkPolicy controllers (static and user-defined)

- **DefaultCertManagerController**: Ensures a cluster-scoped `CertManager` CR named `cluster` exists with defaults

### API Types

Located in `api/operator/v1alpha1/`:

- **CertManager**: Cluster-scoped singleton CR (must be named `cluster`) that configures cert-manager deployment. Supports customization of controller, webhook, and cainjector deployments via `controllerConfig`, `webhookConfig`, and `cainjectorConfig` fields.

- **IstioCSR**: Namespace-scoped singleton CR (must be named `default`) for deploying istio-csr agent. Only active when `IstioCSR` feature gate is enabled via `--unsupported-addon-features="IstioCSR=true"`.

### Generated Code

- **Bindata**: Static manifests in `bindata/` are compiled into `pkg/operator/assets/bindata.go` via `make update-bindata`
- **Client/Informers/Listers**: Generated in `pkg/operator/clientset/`, `pkg/operator/informers/`, `pkg/operator/listers/`
- **DeepCopy**: Generated via controller-gen for API types

### Deployment Manifests

- `bindata/cert-manager-crds/`: cert-manager CRDs
- `bindata/cert-manager-deployment/`: cert-manager deployment manifests split into controller/webhook/cainjector
- `config/`: Kustomize configuration for operator deployment
- `bundle/`: OLM bundle manifests

## Key Patterns

### Deployment Overrides

The operator supports overriding cert-manager deployment specs through the CertManager CR:
- `overrideArgs`: Additional CLI arguments
- `overrideEnv`: Environment variables
- `overrideLabels`: Pod labels
- `overrideResources`: Resource requests/limits
- `overrideReplicas`: Replica count
- `overrideScheduling`: NodeSelector and tolerations

Validation logic is in `pkg/controller/deployment/deployment_overrides_validation.go`.

### Feature Gates

Feature gates are defined in `api/operator/v1alpha1/features.go` and managed via `pkg/features/features.go`. Currently supports:
- `IstioCSR`: Enables istio-csr controller (Technology Preview)

### Environment Variables for Images

The operator uses `RELATED_IMAGE_*` environment variables to specify operand images:
- `RELATED_IMAGE_CERT_MANAGER_CONTROLLER`
- `RELATED_IMAGE_CERT_MANAGER_WEBHOOK`
- `RELATED_IMAGE_CERT_MANAGER_CA_INJECTOR`
- `RELATED_IMAGE_CERT_MANAGER_ACMESOLVER`
- `RELATED_IMAGE_CERT_MANAGER_ISTIOCSR`

## Testing

- Unit tests use standard Go testing with testify assertions
- E2E tests use Ginkgo/Gomega and require a running OpenShift cluster with the operator deployed
- E2E tests are tagged with `// +build e2e` and use platform labels for filtering (e.g., `Platform: AWS`)
- Test utilities are in `test/library/`

## Import Organization

Local imports should be separated from third-party packages using the prefix `github.com/openshift/cert-manager-operator` (configured in `.golangci.yaml`).
2 changes: 2 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -329,10 +329,12 @@ local-run: build ## Run the operator locally against the cluster configured in ~
RELATED_IMAGE_CERT_MANAGER_ACMESOLVER=quay.io/jetstack/cert-manager-acmesolver:$(CERT_MANAGER_VERSION) \
RELATED_IMAGE_CERT_MANAGER_ISTIOCSR=quay.io/jetstack/cert-manager-istio-csr:$(ISTIO_CSR_VERSION) \
RELATED_IMAGE_CERT_MANAGER_TRUST_MANAGER=quay.io/jetstack/trust-manager:$(TRUST_MANAGER_VERSION) \
RELATED_IMAGE_CERT_MANAGER_HTTP01PROXY=quay.io/bapalm/cert-mgr-http01-proxy:latest \
OPERATOR_NAME=cert-manager-operator \
OPERAND_IMAGE_VERSION=$(BUNDLE_VERSION) \
ISTIOCSR_OPERAND_IMAGE_VERSION=$(ISTIO_CSR_VERSION) \
TRUSTMANAGER_OPERAND_IMAGE_VERSION=$(TRUST_MANAGER_VERSION) \
HTTP01PROXY_OPERAND_IMAGE_VERSION=0.1.0 \
Comment thread
sebrandon1 marked this conversation as resolved.
OPERATOR_IMAGE_VERSION=$(BUNDLE_VERSION) \
./cert-manager-operator start \
--config=./hack/local-run-config.yaml \
Expand Down
39 changes: 39 additions & 0 deletions TODO-cleanup.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Cleanup Opportunities

Identified 2026-04-08 via codebase review. Grouped by effort level.

## Trivial (bundle into one PR)

- [ ] Typo: "name o the" → "name of the" in `istiocsr/constants.go:76`
- [ ] `fmt.Errorf("%s", msg)` → `errors.New(msg)` in `istiocsr/utils.go:501,547`
- [ ] `int32(420)` → `int32(0o644)` in `istiocsr/deployments.go`, `certmanager/deployment_overrides.go`
- [ ] Magic string `"Kubernetes"` → `defaultClusterID` constant in `istiocsr/deployments.go:140`
- [ ] Magic string `"default"` → `defaultIstioRevision` constant in `istiocsr/certificates.go:90`
- [ ] Duplicate constant `roleBindingSubjectKind` in `istiocsr/rbacs.go:17` and `trustmanager/constants.go:49` → move to common
- [ ] Duplicate constants `istiodCertificateCommonNameFmt` and `istiodCertificateDefaultDNSName` have same value `"istiod.%s.svc"` in `istiocsr/constants.go:52,55` → consolidate
- [ ] Remove redundant `sort.Strings` in `certmanager/deployment_overrides.go:103` (already sorted in `mergeContainerArgs`)
- [ ] `make(map[string]string, 0)` → `make(map[string]string)` in `certmanager/deployment_overrides_validation.go:89,138`

## Easy (individual PRs, mechanical changes)

- [ ] Replace 8 `decode*ObjBytes` functions in istiocsr with `common.DecodeObjBytes[T]` (~95 lines deleted)
- [ ] Move `updatePodTemplateLabels` to common (identical one-liner in istiocsr + trustmanager)
- [ ] Extract `UpdateContainerImage(deployment, envVar, containerName)` to common (shared pattern)
- [ ] Extract `BuildDefaultResourceLabels(appName, versionEnvVar)` to common (prevents label schema divergence)
- [ ] `IsEmptyString(interface{})` → `IsEmptyString(string)` in `test/library/utils.go:141` (unsafe type assertion)
- [ ] Duplicate `MustAsset` call in `certmanager/generic_deployment_controller.go:32,74` → call once, reuse
- [ ] Duplicate issuer API call in `istiocsr/deployments.go:247,371` → return from first call
- [ ] Decode YAML just to get SA name in `istiocsr/rbacs.go:21` → use a constant

## Medium (higher impact, needs design)

- [ ] Move `addFinalizer`/`removeFinalizer` to common (identical in istiocsr + trustmanager, ~80 lines)
- [ ] Move `updateStatus` to common (identical in istiocsr + trustmanager, needs generic interface)
- [ ] Extract create-or-update reconcile pattern (8+ copies in istiocsr → generic helper with callback)
- [ ] Batch status updates in istiocsr (5 separate API calls per reconcile → accumulate and flush once)
- [ ] Extract e2e `addOverride*` helpers (~400 lines of copy-paste in test utils → generic mutation helper)

## Open PRs (in flight)

- [x] CNF-22825 / PR #314 — Consolidate istiocsr logging around klog/v2 (CI: 7/9 green, e2e pending)
- [x] CNF-22826 / PR #242 — Consolidate context usage around context.TODO() (CI: 7/9 green, e2e pending)
10 changes: 10 additions & 0 deletions api/operator/v1alpha1/features.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,19 @@ var (
// For more details,
// https://github.com/openshift/enhancements/blob/master/enhancements/cert-manager/trust-manager-controller.md
FeatureTrustManager featuregate.Feature = "TrustManager"

// HTTP01Proxy enables the controller for http01proxies.operator.openshift.io resource,
// which extends cert-manager-operator to deploy and manage the HTTP01 challenge proxy.
// The proxy enables cert-manager to complete HTTP01 ACME challenges for the API endpoint
// on baremetal platforms where the API VIP is not exposed via OpenShift Ingress.
//
// For more details,
// https://github.com/openshift/enhancements/pull/1929
FeatureHTTP01Proxy featuregate.Feature = "HTTP01Proxy"
)

var OperatorFeatureGates = map[featuregate.Feature]featuregate.FeatureSpec{
FeatureIstioCSR: {Default: true, PreRelease: featuregate.GA},
FeatureTrustManager: {Default: false, PreRelease: "TechPreview"},
FeatureHTTP01Proxy: {Default: false, PreRelease: featuregate.Alpha},
}
109 changes: 109 additions & 0 deletions api/operator/v1alpha1/http01proxy_types.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
package v1alpha1

import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

func init() {
SchemeBuilder.Register(&HTTP01Proxy{}, &HTTP01ProxyList{})
}

// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// +kubebuilder:object:root=true

// HTTP01ProxyList is a list of HTTP01Proxy objects.
type HTTP01ProxyList struct {
metav1.TypeMeta `json:",inline"`

// metadata is the standard list's metadata.
// More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
metav1.ListMeta `json:"metadata"`
Items []HTTP01Proxy `json:"items"`
}

// +genclient
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// +kubebuilder:object:root=true
// +kubebuilder:subresource:status
// +kubebuilder:resource:path=http01proxies,scope=Namespaced,categories={cert-manager-operator},shortName=http01proxy
// +kubebuilder:printcolumn:name="Mode",type="string",JSONPath=".spec.mode"
// +kubebuilder:printcolumn:name="Ready",type="string",JSONPath=".status.conditions[?(@.type=='Ready')].status"
// +kubebuilder:printcolumn:name="Message",type="string",JSONPath=".status.conditions[?(@.type=='Ready')].message"
// +kubebuilder:printcolumn:name="Age",type="date",JSONPath=".metadata.creationTimestamp"
// +kubebuilder:metadata:labels={"app.kubernetes.io/name=http01proxy", "app.kubernetes.io/part-of=cert-manager-operator"}

// HTTP01Proxy describes the configuration for the HTTP01 challenge proxy
// that redirects traffic from the API endpoint on port 80 to ingress routers.
// This enables cert-manager to perform HTTP01 ACME challenges for API endpoint certificates.
// The name must be `default` to make HTTP01Proxy a singleton.
//
// When an HTTP01Proxy is created, the proxy DaemonSet is deployed on control plane nodes.
//
// +kubebuilder:validation:XValidation:rule="self.metadata.name == 'default'",message="http01proxy is a singleton, .metadata.name must be 'default'"
Comment thread
sebrandon1 marked this conversation as resolved.
// +operator-sdk:csv:customresourcedefinitions:displayName="HTTP01Proxy"
type HTTP01Proxy struct {
metav1.TypeMeta `json:",inline"`

// metadata is the standard object's metadata.
// More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
metav1.ObjectMeta `json:"metadata,omitempty"`

// spec is the specification of the desired behavior of the HTTP01Proxy.
// +kubebuilder:validation:Required
// +required
Spec HTTP01ProxySpec `json:"spec"`

// status is the most recently observed status of the HTTP01Proxy.
// +kubebuilder:validation:Optional
// +optional
Status HTTP01ProxyStatus `json:"status,omitempty"`
}

// HTTP01ProxyMode controls how the HTTP01 challenge proxy is deployed.
// +kubebuilder:validation:Enum=DefaultDeployment;CustomDeployment
type HTTP01ProxyMode string

const (
// HTTP01ProxyModeDefault enables the proxy with default configuration.
HTTP01ProxyModeDefault HTTP01ProxyMode = "DefaultDeployment"

// HTTP01ProxyModeCustom enables the proxy with user-specified configuration.
HTTP01ProxyModeCustom HTTP01ProxyMode = "CustomDeployment"
)

// HTTP01ProxySpec is the specification of the desired behavior of the HTTP01Proxy.
// +kubebuilder:validation:XValidation:rule="self.mode == 'CustomDeployment' ? has(self.customDeployment) : !has(self.customDeployment)",message="customDeployment is required when mode is CustomDeployment and forbidden otherwise"
type HTTP01ProxySpec struct {
// mode controls whether the HTTP01 challenge proxy is active and how it should be deployed.
// DefaultDeployment enables the proxy with default configuration.
// CustomDeployment enables the proxy with user-specified configuration.
// +kubebuilder:validation:Required
// +required
Mode HTTP01ProxyMode `json:"mode"`

// customDeployment contains configuration options when mode is CustomDeployment.
// This field is only valid when mode is CustomDeployment.
// +kubebuilder:validation:Optional
// +optional
CustomDeployment *HTTP01ProxyCustomDeploymentSpec `json:"customDeployment,omitempty"`
}

// HTTP01ProxyCustomDeploymentSpec contains configuration for custom proxy deployment.
type HTTP01ProxyCustomDeploymentSpec struct {
// internalPort specifies the internal port used by the proxy service.
// Valid values are 1024-65535.
// +kubebuilder:validation:Minimum=1024
// +kubebuilder:validation:Maximum=65535
// +kubebuilder:default=8888
// +optional
InternalPort int32 `json:"internalPort,omitempty"`
}

// HTTP01ProxyStatus is the most recently observed status of the HTTP01Proxy.
type HTTP01ProxyStatus struct {
// conditions holds information about the current state of the HTTP01 proxy deployment.
ConditionalStatus `json:",inline,omitempty"`

// proxyImage is the name of the image and the tag used for deploying the proxy.
ProxyImage string `json:"proxyImage,omitempty"`
}
Loading