Skip to content

chore(SREP-4482, SREP-4486, SREP-4800: Boilerplate Update for Agentic SDLC Rollout) - #284

Closed
charlesgong wants to merge 1 commit into
openshift:masterfrom
charlesgong:SREP-4485
Closed

charlesgong wants to merge 1 commit into
openshift:masterfrom
charlesgong:SREP-4485

Conversation

@charlesgong

@charlesgong charlesgong commented May 11, 2026 •

Copy link
Copy Markdown

What type of PR is this?
boilerplate

What this PR does / why we need it?
This PR moves the changes introduced in boilerplate for Agentic SDLC Rollout into MVP for ocm-agent-operator.
Related BP MRs

Which Jira/Github issue(s) this PR fixes?
Part of Rollout for Agentic SDLC -

Special notes for your reviewer:
Pre-checks (if applicable):

  • Tested latest changes against a cluster
  • Ran make generate command locally to validate code changes
  • Included documentation changes with PR

Summary by CodeRabbit

Release Notes

  • Chores

    • Updated base container images to latest versions for enhanced security and stability.
  • Tests

    • Improved test assertions and error handling for better reliability.
  • Documentation

    • Added pre-commit hook configuration documentation.

@openshift-ci-robot openshift-ci-robot added the jira/valid-reference Indicates that this PR references a valid Jira ticket of any type. label May 11, 2026
@openshift-ci-robot

openshift-ci-robot commented May 11, 2026 •

Copy link
Copy Markdown

@charlesgong: This pull request references SREP-4482 which is a valid jira issue.

Warning: The referenced jira issue has an invalid target version for the target branch this PR targets: expected the story to target the "5.0.0" version, but no target version was set.

This pull request references SREP-4486 which is a valid jira issue.

Warning: The referenced jira issue has an invalid target version for the target branch this PR targets: expected the story to target the "5.0.0" version, but no target version was set.

This pull request references SREP-4800 which is a valid jira issue.

Warning: The referenced jira issue has an invalid target version for the target branch this PR targets: expected the story to target the "5.0.0" version, but no target version was set.

Details

In response to this:

What type of PR is this?
boilerplate

What this PR does / why we need it?
This PR moves the changes introduced in boilerplate for Agentic SDLC Rollout into MVP for ocm-agent-operator.
Related BP MRs

Which Jira/Github issue(s) this PR fixes?
Part of Rollout for Agentic SDLC -

Special notes for your reviewer:
Pre-checks (if applicable):

  • Tested latest changes against a cluster
  • Ran make generate command locally to validate code changes
  • Included documentation changes with PR

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the openshift-eng/jira-lifecycle-plugin repository.

@coderabbitai

coderabbitai Bot commented May 11, 2026 •

Copy link
Copy Markdown

Walkthrough

This PR refactors the DMS API client to be context-aware throughout all HTTP operations, ensuring proper request lifecycle management and resource cleanup. An ownership alias is also added to OWNERS_ALIASES.

Changes

Context-aware DMS API Client

Layer / File(s) Summary
Context integration and URL resolution
pkg/dmsclient/dmsclient.go
The newRequest method now accepts context.Context and uses http.NewRequestWithContext to bind requests to that context. The stored BaseURL field is removed from the dmsClient struct; request paths are now resolved directly against apiEndpoint.
Error handling and response lifecycle
pkg/dmsclient/dmsclient.go
All client methods (ListAll, List, Create, Delete, Update, CheckIn) now defer resp.Body.Close() for proper cleanup. The do helper wraps API errors consistently, and List/Create/ListAll wrap JSON decode failures with operation-specific error messages. Delete checks only for HTTP 204 status and skips JSON decoding.
Team ownership metadata
OWNERS_ALIASES
The BATMAN-JD alias is added to the srep-functional-team-aurora team entry.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes


Important

Pre-merge checks failed

Please resolve all errors before merging. Addressing warnings is optional.

❌ Failed checks (1 error, 1 warning)

Check name Status Explanation Resolution
Ote Binary Stdout Contract ❌ Error fips.go introduces fmt.Println() in package main's init() function, writing to stdout. This violates OTE Binary Stdout Contract: non-JSON stdout from main process corrupts test listing and breaks CI. Change fmt.Println to write to stderr: fmt.Fprintln(os.Stderr, "***** Starting with FIPS crypto enabled *****")
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (10 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly references the specific Jira tickets (SREP-4482, SREP-4486, SREP-4800) and describes the primary change as a boilerplate update for the Agentic SDLC rollout, which aligns with the changeset containing pre-commit configuration, Dockerfile updates, linting fixes, and context propagation changes.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Stable And Deterministic Test Names ✅ Passed All test names in the PR are stable and deterministic. Test case names use static descriptive strings; file-based subtests use fixed template filenames that don't change between runs.
Test Structure And Quality ✅ Passed The custom check requires reviewing Ginkgo test code, but this repository uses standard Go testing package exclusively. No Ginkgo tests exist in the codebase. The check is not applicable to this PR.
Microshift Test Compatibility ✅ Passed This check is not applicable. The repository does not use Ginkgo e2e tests (zero Ginkgo imports, not in go.mod), and the PR adds no new Ginkgo tests. All test files use standard Go testing package.
Single Node Openshift (Sno) Test Compatibility ✅ Passed No new Ginkgo e2e tests were added in this PR. Test changes are linting/maintenance fixes to existing unit tests using Go's standard testing package.
Topology-Aware Scheduling Compatibility ✅ Passed No deployment manifests modified. All changes are to Go source, Dockerfiles, and documentation. No scheduling constraints, affinity rules, or topology assumptions introduced.
Ipv6 And Disconnected Network Test Compatibility ✅ Passed No new Ginkgo e2e tests are added in this PR. The check is not applicable as it specifically targets new e2e tests, and this PR only modifies existing unit tests and source code.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov-commenter

codecov-commenter commented May 11, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 51.42857% with 51 lines in your changes missing coverage. Please review.
✅ Project coverage is 43.54%. Comparing base (77b341a) to head (e929af2).

Files with missing lines Patch % Lines
...ntegration/deadmanssnitchintegration_controller.go 62.16% 19 Missing and 9 partials ⚠️
pkg/dmsclient/dmsclient.go 0.00% 22 Missing ⚠️
fips.go 0.00% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##           master     #284      +/-   ##
==========================================
+ Coverage   43.28%   43.54%   +0.26%     
==========================================
  Files          11       11              
  Lines         834      829       -5     
==========================================
  Hits          361      361              
+ Misses        424      421       -3     
+ Partials       49       47       -2     
Files with missing lines Coverage Δ
pkg/localmetrics/localmetrics.go 30.30% <ø> (ø)
pkg/utils/secrets.go 55.55% <100.00%> (ø)
pkg/utils/utils.go 50.76% <100.00%> (ø)
fips.go 0.00% <0.00%> (ø)
pkg/dmsclient/dmsclient.go 4.91% <0.00%> (+0.03%) ⬆️
...ntegration/deadmanssnitchintegration_controller.go 63.30% <62.16%> (+0.76%) ⬆️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
build/Dockerfile (1)

7-14: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Add proper non-root user setup before switching to non-root USER directive.

The runtime stage (lines 7–13) has no USER directive and will run as root by default, weakening runtime hardening. While adding USER 1001 is the right goal, the proposed fix is incomplete for ubi-minimal: UID 1001 doesn't exist in the base image and will cause a runtime failure.

For ubi-minimal, create the user first using shadow-utils:

🔧 Proper fix
 FROM registry.access.redhat.com/ubi9/ubi-minimal:9.7-1778072020
 ENV OPERATOR_BIN=deadmanssnitch-operator
 
+RUN microdnf install -y shadow-utils && \
+    useradd -u 1001 -r -g 0 -s /sbin/nologin operator && \
+    microdnf remove -y shadow-utils && \
+    microdnf clean all
+
 WORKDIR /root/
 COPY --from=builder /go/src/github.com/openshift/deadmanssnitch-operator/build/_output/bin/${OPERATOR_BIN} /usr/local/bin/${OPERATOR_BIN}
+RUN chmod 0755 /usr/local/bin/${OPERATOR_BIN}
+USER 1001
 LABEL io.openshift.managed.name="deadmanssnitch-operator" \
       io.openshift.managed.description="Operator to manage Dead Man Snitches"

Note: Consider moving WORKDIR to a location with appropriate permissions for UID 1001, or explicitly setting ownership of /root/ if it's needed.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@build/Dockerfile` around lines 7 - 14, The Dockerfile runtime stage currently
runs as root and adding USER 1001 will fail because the ubi-minimal base image
lacks that UID; update the runtime stage so it creates a non-root user before
switching: install shadow-utils (or use existing package manager in
registry.access.redhat.com/ubi9/ubi-minimal), add a dedicated user/group (e.g.,
user with UID 1001) and set ownership of the runtime WORKDIR or choose a
directory with proper permissions, then invoke USER for that created account;
reference the OPERATOR_BIN/COPY step and ensure the created user's home or the
WORKDIR (/root/ or alternate) is chown'd so the operator binary can execute.
pkg/dmsclient/dmsclient.go (1)

116-126: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Fix nil pointer dereference: check err before accessing resp.StatusCode.

http.Client.Do may return a nil response alongside an error for transport-level failures (DNS, connection refused, context cancellation, etc.). The current code accesses resp.StatusCode before checking err, which will panic when the HTTP call fails in these ways. This is a pre-existing bug; since you're touching the surrounding lines, fixing it now is low-risk and necessary.

Proposed fix
-	resp, err := c.httpClient.Do(req) //nolint:gosec // G704: URL is always built from the hardcoded apiEndpoint base URL
-
-	// raise an error if unable to authenticate to DMS service
-	if resp.StatusCode == 401 {
-		err = fmt.Errorf("unauthorized error: please check the deadmanssnitch credentials")
-	}
-
-	if err != nil {
-		c.metricsCollector.ObserveSnitchCallError()
-		return resp, fmt.Errorf("error calling the API endpoint: %w", err)
-	}
-
-	return resp, nil
+	resp, err := c.httpClient.Do(req) //nolint:gosec // G704: URL is always built from the hardcoded apiEndpoint base URL
+	if err != nil {
+		c.metricsCollector.ObserveSnitchCallError()
+		return resp, fmt.Errorf("error calling the API endpoint: %w", err)
+	}
+
+	// raise an error if unable to authenticate to DMS service
+	if resp.StatusCode == 401 {
+		c.metricsCollector.ObserveSnitchCallError()
+		return resp, fmt.Errorf("unauthorized error: please check the deadmanssnitch credentials")
+	}
+
+	return resp, nil
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/dmsclient/dmsclient.go` around lines 116 - 126, The code calls
c.httpClient.Do(req) and inspects resp.StatusCode before checking err, which can
panic if resp is nil; change the control flow to first check if err != nil (from
c.httpClient.Do(req)), call c.metricsCollector.ObserveSnitchCallError() and
return the wrapped error immediately, then only access resp and check
resp.StatusCode for 401 and return the unauthorized fmt.Errorf; ensure you
handle a nil resp defensively if you keep any later logic that accesses it and
use the existing symbols resp, err, c.httpClient.Do(req),
c.metricsCollector.ObserveSnitchCallError(), and the unauthorized error
fmt.Errorf in the updated order.
🧹 Nitpick comments (6)
pkg/pko/template_test.go (1)

113-113: ⚡ Quick win

Fail fast on failed type assertions instead of ignoring ok.

The current v, _ := ... pattern avoids panics, but it can mask the root cause and produce noisy downstream assertions. Prefer t.Fatalf immediately when expected YAML structure is missing/wrong type.

Proposed refactor (helper-based fail-fast assertions)
+func mustMap(t *testing.T, v interface{}, field string) map[string]interface{} {
+	t.Helper()
+	m, ok := v.(map[string]interface{})
+	if !ok {
+		t.Fatalf("expected %s to be map[string]interface{}, got %T", field, v)
+	}
+	return m
+}
+
+func mustSlice(t *testing.T, v interface{}, field string) []interface{} {
+	t.Helper()
+	s, ok := v.([]interface{})
+	if !ok {
+		t.Fatalf("expected %s to be []interface{}, got %T", field, v)
+	}
+	return s
+}
- metadata, _ := doc["metadata"].(map[string]interface{})
+ metadata := mustMap(t, doc["metadata"], "metadata")

- annotations, _ := metadata["annotations"].(map[string]interface{})
+ annotations := mustMap(t, metadata["annotations"], "metadata.annotations")

- spec, _ := doc["spec"].(map[string]interface{})
- selector, _ := spec["clusterDeploymentSelector"].(map[string]interface{})
- expressions, _ := selector["matchExpressions"].([]interface{})
+ spec := mustMap(t, doc["spec"], "spec")
+ selector := mustMap(t, spec["clusterDeploymentSelector"], "spec.clusterDeploymentSelector")
+ expressions := mustSlice(t, selector["matchExpressions"], "spec.clusterDeploymentSelector.matchExpressions")

- e, _ := expr.(map[string]interface{})
+ e := mustMap(t, expr, "matchExpressions[]")

Also applies to: 121-121, 158-158, 163-163, 206-206, 211-211, 218-220, 224-224, 238-238

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/pko/template_test.go` at line 113, Replace all unchecked type assertions
in pkg/pko/template_test.go (e.g., metadata, _ :=
doc["metadata"].(map[string]interface{}) and the other occurrences at the
locations called out) with fail-fast checks that call t.Fatalf (or a small
helper like requireMap or mustGetMap(t, ...)) when the assertion fails; for each
occurrence verify the value exists and the type assertion returns ok, and if not
call t.Fatalf with a clear message naming the key and expected type (or factor
this into a helper and use it from places such as the assertions around
"metadata", the entries at the other listed spots, and any
map[string]interface{} or []interface{} expectations).
pkg/dmsclient/dmsclient.go (2)

244-249: ⚡ Quick win

Inconsistent decode-error handling in Update.

ListAll, List, Create, and Delete all wrap their decode failures with operation-specific messages (fmt.Errorf("error ...: %w", decodeErr)). Update just returns the raw json error without context, which makes log triage harder and diverges from the new convention this PR establishes.

♻️ Align with sibling methods
 	defer func() { _ = resp.Body.Close() }()
-	err = json.NewDecoder(resp.Body).Decode(&snitch)
+	if decodeErr := json.NewDecoder(resp.Body).Decode(&snitch); decodeErr != nil {
+		err = fmt.Errorf("error updating snitch: %w", decodeErr)
+	}

 	return snitch, err
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/dmsclient/dmsclient.go` around lines 244 - 249, The Update method
currently returns the raw json decode error from
json.NewDecoder(resp.Body).Decode(&snitch); change this to wrap the decode
failure with an operation-specific message consistent with
ListAll/List/Create/Delete (e.g., use fmt.Errorf("error decoding update
response: %w", err)) so callers get contextualized errors; locate the Decode
call in Update (json.NewDecoder(resp.Body).Decode(&snitch)) and replace its
direct return with a wrapped fmt.Errorf return while preserving the defer
resp.Body.Close() behavior.

21-29: 🏗️ Heavy lift

Thread context.Context through the public Client interface.

The PR threads ctx through the controller and utility layers, but every DMS call site passes context.Background() because the Client interface methods (ListAll, List, Create, Delete, Update, CheckIn, FindSnitchesByName) don't accept a ctx. This causes reconciliation cancellation/deadlines to stop at the DMS API boundary—outbound HTTP calls can outlive the Reconcile invocation.

The internal newRequest method already accepts and forwards ctx to http.NewRequestWithContext, so the plumbing exists. Consider accepting ctx in the interface methods and forwarding it into newRequest / http.NewRequestWithContext to propagate cancellation end-to-end. This requires updating all callers and the mock, so a follow-up PR is reasonable if you'd prefer to defer.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/dmsclient/dmsclient.go` around lines 21 - 29, The public Client interface
methods (ListAll, List, Create, Delete, Update, CheckIn, FindSnitchesByName)
must accept a context.Context to propagate cancellation; update the Client
interface to add ctx as the first parameter for each method, then update all
concrete implementations of Client to accept that ctx and pass it down into the
existing newRequest helper (which uses http.NewRequestWithContext) so outbound
HTTP calls are created with the provided context; also update all call sites and
the test/mock implementations to pass through the caller's ctx (or
context.Background() where appropriate) to avoid breaking callers.
controllers/deadmanssnitchintegration/deadmanssnitchintegration_controller.go (2)

309-358: ⚡ Quick win

createSnitch silently swallows non-NotFound errors from the SyncSet Get.

On line 309 r.Client.Get(...) is called; the if err != nil block only branches on IsNotFound. Any other API error (timeout, transient 5xx, permission error) falls through, skips snitch creation, and the function returns nil — so the controller wrongly treats it as success and never retries. Pre-existing, but if you're already restructuring this method for ctx it's worth tightening.

🐛 Proposed fix
 	err = r.Client.Get(ctx, types.NamespacedName{Name: ssName, Namespace: cd.Namespace}, &hivev1.SyncSet{})
-	if err != nil {
-		if k8errors.IsNotFound(err) {
+	if err != nil {
+		if !k8errors.IsNotFound(err) {
+			return err
+		}
 			logger.V(1).Info(fmt.Sprint("Checking if snitch already exists SnitchName:", snitchName))
 			...
-		}
 	}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@controllers/deadmanssnitchintegration/deadmanssnitchintegration_controller.go`
around lines 309 - 358, The SyncSet GET call (r.Client.Get) currently only
handles IsNotFound and silently ignores other errors; change the error handling
so that after calling r.Client.Get(ctx, types.NamespacedName{Name: ssName,
Namespace: cd.Namespace}, &hivev1.SyncSet{}), if err != nil then if
k8errors.IsNotFound(err) run the existing snitch-creation/checkin logic, else
immediately return the err (and optionally log it) so transient or permission
errors are propagated and the reconcile will retry; update the error branch
around r.Client.Get to return non-NotFound errors instead of falling through.

134-152: 💤 Low value

Deletion loop aborts on first CD failure — finalizer removal never happens.

If deleteDMSClusterDeployment fails for any CD in allCDs.Items, the loop returns immediately, the DMSI finalizer-removal block at lines 143–150 is skipped, and the DMSI stays around. That's correct (next reconcile will retry), but if a single CD is permanently stuck this also blocks cleanup of all healthy CDs behind it. Consider collecting errors (e.g., via errors.Join or aggregating with a multierr) and still attempting the others before returning. Optional — the current behavior is safe, just potentially noisy.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@controllers/deadmanssnitchintegration/deadmanssnitchintegration_controller.go`
around lines 134 - 152, In handleDMSIDeletion, don't return on the first
deleteDMSClusterDeployment error; instead iterate all clusterDeployments and
collect errors (e.g., using errors.Join or a multierr) so every CD is attempted,
then after the loop still run the finalizer-removal block (utils.DeleteFinalizer
+ r.Client.Update) and if that update returns an error join it into the
aggregate; finally return the aggregated error (or nil) so callers get all
failure information while ensuring all items were processed.
.pre-commit-config.yaml (1)

88-105: 💤 Low value

Optional: surface a warning when no timeout binary is available.

The portable timeout wrapper ${T:+$T 30s} silently falls back to running go build ./... (and go mod tidy at line 117) with no timeout when neither timeout nor gtimeout is on PATH. The header comment tells macOS users to brew install coreutils, but on a machine missing it the hook still appears to "succeed" within the timing target via no enforcement at all. Consider echoing a one-line stderr warning when T is empty so the missing dependency is visible, e.g.:

♻️ Suggested portable timeout helper
-      - id: go-build
-        name: go build
-        language: system
-        entry: bash -c 'T=$(command -v timeout || command -v gtimeout || echo); ${T:+$T 30s} go build ./...'
+      - id: go-build
+        name: go build
+        language: system
+        entry: bash -c 'T=$(command -v timeout || command -v gtimeout); [ -z "$T" ] && echo "warning: no timeout binary (install coreutils on macOS)" >&2; ${T:+$T 30s} go build ./...'
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.pre-commit-config.yaml around lines 88 - 105, The hook uses the local
variable T in the entry shell (T=$(command -v timeout || command -v gtimeout ||
echo) and then ${T:+$T 30s} ...) which silently runs without a timeout when T is
empty; update the entry for the go-build hook (id: go-build) and the similar go
mod tidy hook to detect empty T and print a one-line warning to stderr before
running the command (e.g., test -z "$T" && echo "warning: timeout not found;
running without enforced timeout" >&2), then proceed with the existing ${T:+$T
30s} go build ./... (and the go mod tidy command) so the missing dependency is
visible while preserving current behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In @.claude/commands/pre-commit.md:
- Around line 77-85: The fenced code block that starts with PRE-COMMIT SUMMARY
is missing a language hint; update the opening triple-backtick for that block to
include a language (e.g., add "text" so it becomes ```text) to satisfy
markdownlint MD040 and keep the file lint-clean. Ensure only the opening fence
is changed and the block content and closing fence remain unchanged.

In @.pre-commit-config.yaml:
- Around line 77-83: Update the golangci-lint pin in .pre-commit-config.yaml so
the rev value under the golangci-lint repo is v2.7.2 (replacing v2.0.2) to match
the version pinned in ensure.sh; verify the hook args remain unchanged and that
the pre-commit config and ensure.sh both reference the same golangci-lint
version to avoid local/CI drift.

---

Outside diff comments:
In `@build/Dockerfile`:
- Around line 7-14: The Dockerfile runtime stage currently runs as root and
adding USER 1001 will fail because the ubi-minimal base image lacks that UID;
update the runtime stage so it creates a non-root user before switching: install
shadow-utils (or use existing package manager in
registry.access.redhat.com/ubi9/ubi-minimal), add a dedicated user/group (e.g.,
user with UID 1001) and set ownership of the runtime WORKDIR or choose a
directory with proper permissions, then invoke USER for that created account;
reference the OPERATOR_BIN/COPY step and ensure the created user's home or the
WORKDIR (/root/ or alternate) is chown'd so the operator binary can execute.

In `@pkg/dmsclient/dmsclient.go`:
- Around line 116-126: The code calls c.httpClient.Do(req) and inspects
resp.StatusCode before checking err, which can panic if resp is nil; change the
control flow to first check if err != nil (from c.httpClient.Do(req)), call
c.metricsCollector.ObserveSnitchCallError() and return the wrapped error
immediately, then only access resp and check resp.StatusCode for 401 and return
the unauthorized fmt.Errorf; ensure you handle a nil resp defensively if you
keep any later logic that accesses it and use the existing symbols resp, err,
c.httpClient.Do(req), c.metricsCollector.ObserveSnitchCallError(), and the
unauthorized error fmt.Errorf in the updated order.

---

Nitpick comments:
In @.pre-commit-config.yaml:
- Around line 88-105: The hook uses the local variable T in the entry shell
(T=$(command -v timeout || command -v gtimeout || echo) and then ${T:+$T 30s}
...) which silently runs without a timeout when T is empty; update the entry for
the go-build hook (id: go-build) and the similar go mod tidy hook to detect
empty T and print a one-line warning to stderr before running the command (e.g.,
test -z "$T" && echo "warning: timeout not found; running without enforced
timeout" >&2), then proceed with the existing ${T:+$T 30s} go build ./... (and
the go mod tidy command) so the missing dependency is visible while preserving
current behavior.

In
`@controllers/deadmanssnitchintegration/deadmanssnitchintegration_controller.go`:
- Around line 309-358: The SyncSet GET call (r.Client.Get) currently only
handles IsNotFound and silently ignores other errors; change the error handling
so that after calling r.Client.Get(ctx, types.NamespacedName{Name: ssName,
Namespace: cd.Namespace}, &hivev1.SyncSet{}), if err != nil then if
k8errors.IsNotFound(err) run the existing snitch-creation/checkin logic, else
immediately return the err (and optionally log it) so transient or permission
errors are propagated and the reconcile will retry; update the error branch
around r.Client.Get to return non-NotFound errors instead of falling through.
- Around line 134-152: In handleDMSIDeletion, don't return on the first
deleteDMSClusterDeployment error; instead iterate all clusterDeployments and
collect errors (e.g., using errors.Join or a multierr) so every CD is attempted,
then after the loop still run the finalizer-removal block (utils.DeleteFinalizer
+ r.Client.Update) and if that update returns an error join it into the
aggregate; finally return the aggregated error (or nil) so callers get all
failure information while ensuring all items were processed.

In `@pkg/dmsclient/dmsclient.go`:
- Around line 244-249: The Update method currently returns the raw json decode
error from json.NewDecoder(resp.Body).Decode(&snitch); change this to wrap the
decode failure with an operation-specific message consistent with
ListAll/List/Create/Delete (e.g., use fmt.Errorf("error decoding update
response: %w", err)) so callers get contextualized errors; locate the Decode
call in Update (json.NewDecoder(resp.Body).Decode(&snitch)) and replace its
direct return with a wrapped fmt.Errorf return while preserving the defer
resp.Body.Close() behavior.
- Around line 21-29: The public Client interface methods (ListAll, List, Create,
Delete, Update, CheckIn, FindSnitchesByName) must accept a context.Context to
propagate cancellation; update the Client interface to add ctx as the first
parameter for each method, then update all concrete implementations of Client to
accept that ctx and pass it down into the existing newRequest helper (which uses
http.NewRequestWithContext) so outbound HTTP calls are created with the provided
context; also update all call sites and the test/mock implementations to pass
through the caller's ctx (or context.Background() where appropriate) to avoid
breaking callers.

In `@pkg/pko/template_test.go`:
- Line 113: Replace all unchecked type assertions in pkg/pko/template_test.go
(e.g., metadata, _ := doc["metadata"].(map[string]interface{}) and the other
occurrences at the locations called out) with fail-fast checks that call
t.Fatalf (or a small helper like requireMap or mustGetMap(t, ...)) when the
assertion fails; for each occurrence verify the value exists and the type
assertion returns ok, and if not call t.Fatalf with a clear message naming the
key and expected type (or factor this into a helper and use it from places such
as the assertions around "metadata", the entries at the other listed spots, and
any map[string]interface{} or []interface{} expectations).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository: openshift/coderabbit/.coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: df11be12-0f92-4721-b842-95392e1935ad

📥 Commits

Reviewing files that changed from the base of the PR and between 0a3ca8d and 3de5bcb.

⛔ Files ignored due to path filters (8)
  • boilerplate/_data/backing-image-tag is excluded by !boilerplate/**
  • boilerplate/_data/last-boilerplate-commit is excluded by !boilerplate/**
  • boilerplate/openshift/golang-osd-operator/.codecov.yml is excluded by !boilerplate/**
  • boilerplate/openshift/golang-osd-operator/OWNERS_ALIASES is excluded by !boilerplate/**
  • boilerplate/openshift/golang-osd-operator/golangci.yml is excluded by !boilerplate/**
  • boilerplate/openshift/golang-osd-operator/pre-commit-config.yaml is excluded by !boilerplate/**
  • boilerplate/openshift/golang-osd-operator/standard.mk is excluded by !boilerplate/**
  • boilerplate/openshift/golang-osd-operator/update is excluded by !boilerplate/**
📒 Files selected for processing (15)
  • .ci-operator.yaml
  • .claude/commands/pre-commit.md
  • .codecov.yml
  • .pre-commit-config.yaml
  • OWNERS_ALIASES
  • build/Dockerfile
  • build/Dockerfile.olm-registry
  • controllers/deadmanssnitchintegration/deadmanssnitchintegration_controller.go
  • controllers/deadmanssnitchintegration/deadmanssnitchintegration_controller_test.go
  • fips.go
  • pkg/dmsclient/dmsclient.go
  • pkg/localmetrics/localmetrics.go
  • pkg/pko/template_test.go
  • pkg/utils/secrets.go
  • pkg/utils/utils.go
💤 Files with no reviewable changes (1)
  • OWNERS_ALIASES

Comment on lines +77 to +85
```
PRE-COMMIT SUMMARY
==================
Passed: <list of hook IDs>
Auto-fixed: <list of hook IDs> → files staged
Fixed: <list of hook IDs> → changes applied
Failed: <list of hook IDs> → escalated to human
Attempts: <N> of 2 maximum
```

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Add a language hint to the summary code fence (markdownlint MD040).

Static analysis flags this fenced block as missing a language. Use text (or similar) to silence the warning and keep the file lint-clean.

📝 Proposed fix
-```
+```text
 PRE-COMMIT SUMMARY
 ==================
 Passed:     <list of hook IDs>
 Auto-fixed: <list of hook IDs> → files staged
 Fixed:      <list of hook IDs> → changes applied
 Failed:     <list of hook IDs> → escalated to human
 Attempts:   <N> of 2 maximum
 ```
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
```
PRE-COMMIT SUMMARY
==================
Passed: <list of hook IDs>
Auto-fixed: <list of hook IDs> → files staged
Fixed: <list of hook IDs> → changes applied
Failed: <list of hook IDs> → escalated to human
Attempts: <N> of 2 maximum
```
🧰 Tools
🪛 markdownlint-cli2 (0.22.1)

[warning] 77-77: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.claude/commands/pre-commit.md around lines 77 - 85, The fenced code block
that starts with PRE-COMMIT SUMMARY is missing a language hint; update the
opening triple-backtick for that block to include a language (e.g., add "text"
so it becomes ```text) to satisfy markdownlint MD040 and keep the file
lint-clean. Ensure only the opening fence is changed and the block content and
closing fence remain unchanged.

Comment thread .pre-commit-config.yaml
Comment on lines +77 to +83
- repo: https://github.com/golangci/golangci-lint
rev: v2.0.2 # pinned immutable tag — must match CI (golden rule 15)
hooks:
- id: golangci-lint
args:
- --config=boilerplate/openshift/golang-osd-operator/golangci.yml
- --timeout=120s # graceful timeout (golden rule 3)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check the golangci-lint version pinned in boilerplate config and Makefiles.
fd -t f 'golangci' --exec rg -nH 'version|GOLANGCI|golangci-lint' {}
rg -nH 'golangci' --type=mk
rg -nH 'golangci-lint' Makefile standard.mk boilerplate 2>/dev/null

Repository: openshift/deadmanssnitch-operator

Length of output: 2071


🏁 Script executed:

cat -n boilerplate/openshift/golang-osd-operator/ensure.sh | head -50

Repository: openshift/deadmanssnitch-operator

Length of output: 1944


🏁 Script executed:

rg -nH 'GOLANGCI_LINT_VERSION' boilerplate/openshift/golang-osd-operator/

Repository: openshift/deadmanssnitch-operator

Length of output: 596


🏁 Script executed:

rg -nH 'golangci-lint.*v[0-9]' boilerplate/

Repository: openshift/deadmanssnitch-operator

Length of output: 59


🏁 Script executed:

fd -t f '\.yml|\.yaml' .github/ | xargs rg -l 'golangci' 2>/dev/null || echo "No .github CI files with golangci found"

Repository: openshift/deadmanssnitch-operator

Length of output: 117


🏁 Script executed:

rg -nH 'golangci.*2\.[0-9]' .

Repository: openshift/deadmanssnitch-operator

Length of output: 59


Update pre-commit golangci-lint version to match CI.

Version mismatch found: .pre-commit-config.yaml pins v2.0.2 (line 78), but boilerplate/openshift/golang-osd-operator/ensure.sh pins 2.7.2 (line 11). Since the config comment requires matching CI versions (golden rule 15) and ensure.sh is sourced by standard.mk for CI linting, the pre-commit rev must be updated to v2.7.2 to prevent lint result drift between local and CI.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.pre-commit-config.yaml around lines 77 - 83, Update the golangci-lint pin
in .pre-commit-config.yaml so the rev value under the golangci-lint repo is
v2.7.2 (replacing v2.0.2) to match the version pinned in ensure.sh; verify the
hook args remain unchanged and that the pre-commit config and ensure.sh both
reference the same golangci-lint version to avoid local/CI drift.

@tnierman

Copy link
Copy Markdown

/label tide/merge-method-squash

@openshift-ci openshift-ci Bot added tide/merge-method-squash Denotes a PR that should be squashed by tide when it merges. needs-rebase Indicates a PR cannot be merged because it has merge conflicts with HEAD. and removed needs-rebase Indicates a PR cannot be merged because it has merge conflicts with HEAD. labels May 11, 2026
@openshift-ci

openshift-ci Bot commented May 13, 2026

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: charlesgong
Once this PR has been reviewed and has the lgtm label, please assign sam-nguyen7 for approval. For more information see the Code Review Process.

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

Comment thread .claude/commands/pre-commit.md Resolved
"fmt"
"strings"

"github.com/go-logr/logr"

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Why are there changes to the controller code as part of this PR?

@charlesgong charlesgong May 14, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

CMIIW, like https://github.com/charlesgong/deadmanssnitch-operator/blob/83ac598f0c95e6be5e0a7e99b44b096c0571e3eb/controllers/deadmanssnitchintegration/deadmanssnitchintegration_controller.go#L134
here is to explicitly declare reqLogger as a logr.Logger type in the function signature, the file had to import the github.com/go-logr/logr package
I found this as part of compile error when breaking the complex function into a few helpers

- Fix cyclomatic complexity and context propagation lint errors

- Update boilerplate configurations and base images

- Fix gosec SSRF false positive with nolint

- Update pre-commit AI instructions to not automatically run pip install

- Lower codecov patch target to 10%
@openshift-ci

openshift-ci Bot commented May 14, 2026

Copy link
Copy Markdown
Contributor

@charlesgong: all tests passed!

Full PR test history. Your PR dashboard.

Details

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository. I understand the commands that are listed here.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 5

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
pkg/dmsclient/dmsclient.go (1)

110-123: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Possible nil-pointer dereference and response-body leak in do.

Two defects on this path:

  1. When c.httpClient.Do(req) returns a non-nil error, resp is typically nil. The unconditional resp.StatusCode == 401 check on line 113 will panic before reaching the if err != nil branch on line 117.
  2. When the request succeeds but the API returns 401, err is set on line 114 and the function returns the response with err != nil. All callers follow the pattern if err != nil { return ... } before setting up defer resp.Body.Close(), so the body is leaked on every unauthorized response.
🛠️ Proposed fix
 func (c *dmsClient) do(req *http.Request, operation string) (*http.Response, error) {
 	start := time.Now()
 	defer func() {
 		c.metricsCollector.ObserveSnitchCallDuration(time.Since(start).Seconds(), operation)
 	}()
-	resp, err := c.httpClient.Do(req) // `#nosec` G107 G704
-
-	// raise an error if unable to authenticate to DMS service
-	if resp.StatusCode == 401 {
-		err = fmt.Errorf("unauthorized error: please check the deadmanssnitch credentials")
-	}
-
-	if err != nil {
-		c.metricsCollector.ObserveSnitchCallError()
-		return resp, fmt.Errorf("error calling the API endpoint: %w", err)
-	}
-
-	return resp, nil
+	resp, err := c.httpClient.Do(req) // `#nosec` G107
+	if err != nil {
+		c.metricsCollector.ObserveSnitchCallError()
+		return nil, fmt.Errorf("error calling the API endpoint: %w", err)
+	}
+
+	// raise an error if unable to authenticate to DMS service
+	if resp.StatusCode == http.StatusUnauthorized {
+		_ = resp.Body.Close()
+		c.metricsCollector.ObserveSnitchCallError()
+		return nil, fmt.Errorf("unauthorized error: please check the deadmanssnitch credentials")
+	}
+
+	return resp, nil
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/dmsclient/dmsclient.go` around lines 110 - 123, The do function currently
checks resp.StatusCode before verifying err from c.httpClient.Do(req), which can
cause a nil-pointer panic when Do returns an error, and it also sets err on 401
responses without closing resp.Body causing a leak; fix by first checking if err
!= nil after c.httpClient.Do(req) and return with metrics on error, and for
non-nil resp with a 401 status set a wrapped error but ensure resp.Body is
closed before returning (call resp.Body.Close or defer immediately after
verifying resp != nil) and keep the metrics call to
c.metricsCollector.ObserveSnitchCallError when returning an error.
🧹 Nitpick comments (4)
pkg/dmsclient/dmsclient.go (4)

228-243: ⚡ Quick win

Inconsistent error wrapping in Update.

ListAll, List, and Create all wrap JSON decode failures with an operation-specific message via %w, but Update returns the raw json.Decoder.Decode error verbatim. Either this is intentional (worth a comment) or it’s an oversight from the refactor — given the stack summary explicitly calls out wrapping decode errors consistently, this looks like the latter.

♻️ Proposed fix
 	defer func() { _ = resp.Body.Close() }()
-	err = json.NewDecoder(resp.Body).Decode(&snitch)
-
-	return snitch, err
+	if decodeErr := json.NewDecoder(resp.Body).Decode(&snitch); decodeErr != nil {
+		return snitch, fmt.Errorf("error updating snitch: %w", decodeErr)
+	}
+	return snitch, nil
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/dmsclient/dmsclient.go` around lines 228 - 243, The Update method on
dmsClient returns the raw json.Decoder.Decode error while ListAll/List/Create
wrap decode failures with an operation-specific message; change Update to wrap
the decode error consistently (e.g., after calling
json.NewDecoder(resp.Body).Decode(&snitch) return a fmt.Errorf or wrap with %w)
so the error becomes something like "update: decode response: %w"; keep the
existing resp.Body.Close defer and error return shape but replace the direct err
return with the wrapped error to match the other methods.

113-113: ⚡ Quick win

Replace HTTP magic numbers with net/http constants.

401 → http.StatusUnauthorized, 204 → http.StatusNoContent. Same behavior, more readable, and consistent with the rest of the standard library you’re already using.

♻️ Proposed fix
-	if resp.StatusCode == 401 {
+	if resp.StatusCode == http.StatusUnauthorized {
-	if resp.StatusCode == 204 {
+	if resp.StatusCode == http.StatusNoContent {
 		return true, nil
 	}

Also applies to: 202-202

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/dmsclient/dmsclient.go` at line 113, Replace numeric HTTP status code
literals with net/http constants in the response handling in dmsclient.go:
change checks like resp.StatusCode == 401 to resp.StatusCode ==
http.StatusUnauthorized and resp.StatusCode == 204 to resp.StatusCode ==
http.StatusNoContent (also update the second occurrence noted at the other
location). Ensure the file imports "net/http" (or already uses it) and update
any related comparisons in functions/methods that reference resp.StatusCode so
behavior remains identical but uses http.StatusUnauthorized and
http.StatusNoContent for readability and consistency.

246-261: ⚡ Quick win

CheckIn ignores non-2xx responses.

After c.do(...) succeeds (i.e. err == nil), the response status is never inspected, so a 5xx from the check-in URL is reported as success. Given the only purpose of this call is to confirm the snitch was pinged, validating the status code seems worthwhile:

 	defer func() { _ = resp.Body.Close() }()
-
-	return nil
+	if resp.StatusCode >= 200 && resp.StatusCode < 300 {
+		return nil
+	}
+	return fmt.Errorf("unexpected check-in status code: %d", resp.StatusCode)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/dmsclient/dmsclient.go` around lines 246 - 261, The CheckIn function
currently ignores the HTTP response status after calling c.do; update CheckIn
(in pkg/dmsclient, function CheckIn) to validate resp.StatusCode is in the 2xx
range and return an error when it's not; include the status code (and optionally
a short excerpt of resp.Body) in the returned error to aid debugging, ensuring
resp.Body is still closed via the existing defer and that any body read for the
error message does not panic on large bodies.

191-207: ⚡ Quick win

Delete silently swallows non-204 responses.

Any non-204 status (404, 5xx, etc.) currently returns (false, nil), which is indistinguishable from a successful “not deleted” signal and hides real API failures from callers. Consider returning an error for unexpected status codes:

 	if resp.StatusCode == http.StatusNoContent {
 		return true, nil
 	}
-
-	return false, nil
+	return false, fmt.Errorf("unexpected status code deleting snitch: %d", resp.StatusCode)

If this “best-effort delete” semantics is intentional and relied upon by the controller, a short comment to that effect would prevent future re-litigation.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/dmsclient/dmsclient.go` around lines 191 - 207, The Delete method on
dmsClient currently returns (false, nil) for any non-204 response which hides
API errors; update dmsClient.Delete to treat unexpected HTTP statuses as errors:
after calling c.do (and closing resp.Body), if resp.StatusCode != 204 then read
the response body (safely, limited length), and return (false,
fmt.Errorf("delete snitch %s: unexpected status %d: %s", snitchToken,
resp.StatusCode, string(body))) so callers can distinguish failures; reference
the Delete method and the existing newRequest/do call flow when making the
change (or, if "best-effort delete" is intentional, add a clear comment above
Delete documenting this semantic).
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In @.claude/commands/pre-commit.md:
- Line 41: Replace the unsafe instruction "git add <auto-fixed files>" with a
safer workflow: recommend running a preflight check to ensure target files have
no other unstaged changes, and offer options such as using interactive/patch
staging or explicitly documenting that the agent must verify only the auto-fix
hunks are being staged; update the single line that currently reads "git add
<auto-fixed files>" in .claude/commands/pre-commit.md to describe these safer
alternatives and require verification before staging.
- Around line 49-52: Update the guideline line "Apply the fix (edit the file,
run the suggested command)" to include explicit safety constraints: restrict
automated edits to non-destructive transformations (formatting, whitespace,
import sorting, lint fixes), only allow safe commands (e.g., pre-commit run, git
add/stage) without human approval, require human approval and a documented
justification before running any command that modifies state outside the current
file or could be destructive, and explicitly prohibit commands that delete
files, alter system state, or perform network operations (e.g., no rm, no
curl/wget, no git push) unless approved; also require the agent to log the
proposed fix and rationale before applying changes.
- Around line 47-57: The documentation is inconsistent about whether the counter
is attempts or retries: the logic uses attempt_count starting at 1 and stopping
at 3, but the summary text says "2 maximum" which can be read as attempts;
update the wording for clarity by changing the summary line(s) that read "2
maximum" to either "Attempts: <N> of 3" to match attempt_count semantics or to
"Retries: <N> of 2 maximum" to explicitly indicate retries; search for and
update every occurrence of the ambiguous summary (the string "2 maximum" and any
lines summarizing attempts/retries) so that the displayed label matches the
implementation and is consistent across the document.

In `@pkg/dmsclient/dmsclient.go`:
- Line 127: The callers currently pass context.Background() into c.newRequest,
neutralizing the context refactor; update the Client API to accept a
context.Context on each public method (e.g., change ListAll, List, Create,
Delete, FindSnitchesByName, Update, CheckIn to signatures like ListAll(ctx
context.Context) ([]Snitch, error)), update their implementations to accept that
ctx and pass it into newRequest(ctx, ...), and then update all call sites
(controller/reconcilers and any other callers) to forward their incoming context
instead of using context.Background(), ensuring cancellations/deadlines
propagate into newRequest and the HTTP calls.
- Around line 79-82: The code in newRequest uses base.ResolveReference with
rel.Path set to an absolute path (e.g. "/v1/snitches"), which discards the base
URL's path (apiEndpoint "/v1"); fix newRequest by building the relative URL
correctly: either trim the leading slash from the supplied path (rel :=
&url.URL{Path: strings.TrimPrefix(path, "/")}) before calling
base.ResolveReference, or explicitly join base.Path and the supplied path (e.g.
base.Path = pathpkg.Join(base.Path, path) then use base) so the apiEndpoint's
path component (apiEndpoint) is preserved; update references to rel, base and
ResolveReference in newRequest and add the required import (strings or path)
accordingly.

---

Outside diff comments:
In `@pkg/dmsclient/dmsclient.go`:
- Around line 110-123: The do function currently checks resp.StatusCode before
verifying err from c.httpClient.Do(req), which can cause a nil-pointer panic
when Do returns an error, and it also sets err on 401 responses without closing
resp.Body causing a leak; fix by first checking if err != nil after
c.httpClient.Do(req) and return with metrics on error, and for non-nil resp with
a 401 status set a wrapped error but ensure resp.Body is closed before returning
(call resp.Body.Close or defer immediately after verifying resp != nil) and keep
the metrics call to c.metricsCollector.ObserveSnitchCallError when returning an
error.

---

Nitpick comments:
In `@pkg/dmsclient/dmsclient.go`:
- Around line 228-243: The Update method on dmsClient returns the raw
json.Decoder.Decode error while ListAll/List/Create wrap decode failures with an
operation-specific message; change Update to wrap the decode error consistently
(e.g., after calling json.NewDecoder(resp.Body).Decode(&snitch) return a
fmt.Errorf or wrap with %w) so the error becomes something like "update: decode
response: %w"; keep the existing resp.Body.Close defer and error return shape
but replace the direct err return with the wrapped error to match the other
methods.
- Line 113: Replace numeric HTTP status code literals with net/http constants in
the response handling in dmsclient.go: change checks like resp.StatusCode == 401
to resp.StatusCode == http.StatusUnauthorized and resp.StatusCode == 204 to
resp.StatusCode == http.StatusNoContent (also update the second occurrence noted
at the other location). Ensure the file imports "net/http" (or already uses it)
and update any related comparisons in functions/methods that reference
resp.StatusCode so behavior remains identical but uses http.StatusUnauthorized
and http.StatusNoContent for readability and consistency.
- Around line 246-261: The CheckIn function currently ignores the HTTP response
status after calling c.do; update CheckIn (in pkg/dmsclient, function CheckIn)
to validate resp.StatusCode is in the 2xx range and return an error when it's
not; include the status code (and optionally a short excerpt of resp.Body) in
the returned error to aid debugging, ensuring resp.Body is still closed via the
existing defer and that any body read for the error message does not panic on
large bodies.
- Around line 191-207: The Delete method on dmsClient currently returns (false,
nil) for any non-204 response which hides API errors; update dmsClient.Delete to
treat unexpected HTTP statuses as errors: after calling c.do (and closing
resp.Body), if resp.StatusCode != 204 then read the response body (safely,
limited length), and return (false, fmt.Errorf("delete snitch %s: unexpected
status %d: %s", snitchToken, resp.StatusCode, string(body))) so callers can
distinguish failures; reference the Delete method and the existing newRequest/do
call flow when making the change (or, if "best-effort delete" is intentional,
add a clear comment above Delete documenting this semantic).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository: openshift/coderabbit/.coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 07ab49b0-b84a-44a5-8d87-2e89f69af412

📥 Commits

Reviewing files that changed from the base of the PR and between 3de5bcb and e929af2.

⛔ Files ignored due to path filters (2)
  • boilerplate/_data/last-boilerplate-commit is excluded by !boilerplate/**
  • boilerplate/openshift/golang-osd-operator/OWNERS_ALIASES is excluded by !boilerplate/**
📒 Files selected for processing (12)
  • .claude/commands/pre-commit.md
  • OWNERS_ALIASES
  • build/Dockerfile
  • build/Dockerfile.olm-registry
  • controllers/deadmanssnitchintegration/deadmanssnitchintegration_controller.go
  • controllers/deadmanssnitchintegration/deadmanssnitchintegration_controller_test.go
  • fips.go
  • pkg/dmsclient/dmsclient.go
  • pkg/localmetrics/localmetrics.go
  • pkg/pko/template_test.go
  • pkg/utils/secrets.go
  • pkg/utils/utils.go
✅ Files skipped from review due to trivial changes (3)
  • pkg/localmetrics/localmetrics.go
  • fips.go
  • build/Dockerfile
🚧 Files skipped from review as they are similar to previous changes (6)
  • build/Dockerfile.olm-registry
  • pkg/utils/secrets.go
  • pkg/utils/utils.go
  • controllers/deadmanssnitchintegration/deadmanssnitchintegration_controller_test.go
  • pkg/pko/template_test.go
  • controllers/deadmanssnitchintegration/deadmanssnitchintegration_controller.go

### Step 4 — Handle auto-fixes (idempotency loop, golden rule 9)

If any hooks auto-fixed files:
1. Stage the modified files: `git add <auto-fixed files>`

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Risk of staging unrelated changes with auto-fixed files.

Using git add <auto-fixed files> will stage all changes in those files, including any unrelated uncommitted modifications that existed before the hook ran. This could inadvertently commit debugging code, work-in-progress changes, or other unintended content.

Consider one of these safer approaches:

  • Add a preflight check that verifies files have no unstaged changes before running hooks
  • Use git add -p <auto-fixed files> to allow selective staging (though this requires human interaction)
  • Document that the agent should verify only auto-fix changes are being staged
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.claude/commands/pre-commit.md at line 41, Replace the unsafe instruction
"git add <auto-fixed files>" with a safer workflow: recommend running a
preflight check to ensure target files have no other unstaged changes, and offer
options such as using interactive/patch staging or explicitly documenting that
the agent must verify only the auto-fix hunks are being staged; update the
single line that currently reads "git add <auto-fixed files>" in
.claude/commands/pre-commit.md to describe these safer alternatives and require
verification before staging.

Comment on lines +47 to +57
Track `attempt_count` starting at 1.

For each non-security failure with an identifiable fix:
1. Apply the fix (edit the file, run the suggested command)
2. Stage the changes
3. Re-run `pre-commit run`
4. Increment `attempt_count`

**Stop retrying when:**
- All hooks pass → report success
- `attempt_count` reaches 3 → stop, escalate to human (see Step 6)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Clarify attempt count terminology for consistency.

The retry logic starts attempt_count at 1 and stops at 3 (line 57), but the summary reports "2 maximum" (line 84). While "2 maximum retries" is technically accurate, the phrasing is ambiguous and could be read as "2 maximum attempts."

For clarity, consider using one of:

  • "Attempts: of 3" (matches the implementation)
  • "Retries: of 2 maximum" (clarifies it means retries, not total attempts)

Also applies to: 84-84

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.claude/commands/pre-commit.md around lines 47 - 57, The documentation is
inconsistent about whether the counter is attempts or retries: the logic uses
attempt_count starting at 1 and stopping at 3, but the summary text says "2
maximum" which can be read as attempts; update the wording for clarity by
changing the summary line(s) that read "2 maximum" to either "Attempts: <N> of
3" to match attempt_count semantics or to "Retries: <N> of 2 maximum" to
explicitly indicate retries; search for and update every occurrence of the
ambiguous summary (the string "2 maximum" and any lines summarizing
attempts/retries) so that the displayed label matches the implementation and is
consistent across the document.

Comment on lines +49 to +52
For each non-security failure with an identifiable fix:
1. Apply the fix (edit the file, run the suggested command)
2. Stage the changes
3. Re-run `pre-commit run`

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Add safety constraints for fix application.

The instruction to "Apply the fix (edit the file, run the suggested command)" lacks guardrails for what fixes and commands are safe for the agent to execute. Without constraints, the agent might apply inappropriate fixes or execute commands that could be destructive.

Consider adding guidelines such as:

  • Limit file edits to specific safe transformations (formatting, whitespace, import sorting)
  • Specify which commands are permitted vs. require human approval
  • Require the agent to explain and justify each fix before applying it
  • Prohibit execution of commands that modify state outside the current file (e.g., no rm, no network calls)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.claude/commands/pre-commit.md around lines 49 - 52, Update the guideline
line "Apply the fix (edit the file, run the suggested command)" to include
explicit safety constraints: restrict automated edits to non-destructive
transformations (formatting, whitespace, import sorting, lint fixes), only allow
safe commands (e.g., pre-commit run, git add/stage) without human approval,
require human approval and a documented justification before running any command
that modifies state outside the current file or could be destructive, and
explicitly prohibit commands that delete files, alter system state, or perform
network operations (e.g., no rm, no curl/wget, no git push) unless approved;
also require the agent to log the proposed fix and rationale before applying
changes.

Comment on lines +79 to +82
func (c *dmsClient) newRequest(ctx context.Context, method, path string, body interface{}) (*http.Request, error) {
base, _ := url.Parse(apiEndpoint)
rel := &url.URL{Path: path}
u := c.BaseURL.ResolveReference(rel)
u := base.ResolveReference(rel)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

base.ResolveReference with an absolute path makes apiEndpoint’s path component dead.

apiEndpoint is "https://api.deadmanssnitch.com/v1" and every caller passes paths like /v1/snitches. Because the relative URL’s Path is absolute, ResolveReference discards the base path entirely and the /v1 in apiEndpoint is never used — the URL only works by accident because the callers happen to also prefix /v1. If anyone normalizes apiEndpoint (e.g. drops the version) or normalizes the call sites (drops /v1), all requests silently break.

Pick one source of truth — either keep the version in apiEndpoint and strip it from call sites, or drop it from apiEndpoint and let the paths supply it:

♻️ One option: keep version in the base URL
-func (c *dmsClient) newRequest(ctx context.Context, method, path string, body interface{}) (*http.Request, error) {
-	base, _ := url.Parse(apiEndpoint)
-	rel := &url.URL{Path: path}
-	u := base.ResolveReference(rel)
+func (c *dmsClient) newRequest(ctx context.Context, method, path string, body interface{}) (*http.Request, error) {
+	u, err := url.Parse(apiEndpoint + path)
+	if err != nil {
+		return nil, fmt.Errorf("invalid request URL: %w", err)
+	}

…and update call sites to pass "/snitches" instead of "/v1/snitches".

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func (c *dmsClient) newRequest(ctx context.Context, method, path string, body interface{}) (*http.Request, error) {
base, _ := url.Parse(apiEndpoint)
rel := &url.URL{Path: path}
u := c.BaseURL.ResolveReference(rel)
u := base.ResolveReference(rel)
func (c *dmsClient) newRequest(ctx context.Context, method, path string, body interface{}) (*http.Request, error) {
u, err := url.Parse(apiEndpoint + path)
if err != nil {
return nil, fmt.Errorf("invalid request URL: %w", err)
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/dmsclient/dmsclient.go` around lines 79 - 82, The code in newRequest uses
base.ResolveReference with rel.Path set to an absolute path (e.g.
"/v1/snitches"), which discards the base URL's path (apiEndpoint "/v1"); fix
newRequest by building the relative URL correctly: either trim the leading slash
from the supplied path (rel := &url.URL{Path: strings.TrimPrefix(path, "/")})
before calling base.ResolveReference, or explicitly join base.Path and the
supplied path (e.g. base.Path = pathpkg.Join(base.Path, path) then use base) so
the apiEndpoint's path component (apiEndpoint) is preserved; update references
to rel, base and ResolveReference in newRequest and add the required import
(strings or path) accordingly.

// ListAll snitches
func (c *dmsClient) ListAll() ([]Snitch, error) {
req, err := c.newRequest("GET", "/v1/snitches", nil)
req, err := c.newRequest(context.Background(), "GET", "/v1/snitches", nil)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

context.Background() everywhere defeats the purpose of the context refactor.

newRequest now takes a context.Context, but every caller hard-codes context.Background(). That means request cancellation, deadlines, and timeouts from controller reconciliation cannot propagate into the DMS HTTP calls — which is presumably the reason the parameter was introduced.

Consider plumbing context through the Client interface itself so callers can pass their reconcile/request context:

type Client interface {
    ListAll(ctx context.Context) ([]Snitch, error)
    List(ctx context.Context, snitchToken string) (Snitch, error)
    Create(ctx context.Context, newSnitch Snitch) (Snitch, error)
    Delete(ctx context.Context, snitchToken string) (bool, error)
    FindSnitchesByName(ctx context.Context, snitchName string) ([]Snitch, error)
    Update(ctx context.Context, updateSnitch Snitch) (Snitch, error)
    CheckIn(ctx context.Context, s Snitch) error
}

This is an interface-shape change with caller fan-out in the controller, but it’s the change that actually delivers the value being aimed at here. Otherwise the new parameter on newRequest is effectively dead.

Also applies to: 151-151, 172-172, 192-192, 230-230, 247-247

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/dmsclient/dmsclient.go` at line 127, The callers currently pass
context.Background() into c.newRequest, neutralizing the context refactor;
update the Client API to accept a context.Context on each public method (e.g.,
change ListAll, List, Create, Delete, FindSnitchesByName, Update, CheckIn to
signatures like ListAll(ctx context.Context) ([]Snitch, error)), update their
implementations to accept that ctx and pass it into newRequest(ctx, ...), and
then update all call sites (controller/reconcilers and any other callers) to
forward their incoming context instead of using context.Background(), ensuring
cancellations/deadlines propagate into newRequest and the HTTP calls.

@devppratik

devppratik commented May 15, 2026 •

Copy link
Copy Markdown
Contributor

closed in favour of #285

@devppratik

Copy link
Copy Markdown
Contributor

/close

@openshift-ci openshift-ci Bot closed this May 15, 2026
@openshift-ci

openshift-ci Bot commented May 15, 2026

Copy link
Copy Markdown
Contributor

@devppratik: Closed this PR.

Details

In response to this:

/close

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

jira/valid-reference Indicates that this PR references a valid Jira ticket of any type. tide/merge-method-squash Denotes a PR that should be squashed by tide when it merges.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants