Repository navigation
chore(SREP-4482, SREP-4486, SREP-4800: Boilerplate Update for Agentic SDLC Rollout) - #284
charlesgong wants to merge 1 commit into
Conversation
|
@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. DetailsIn response to this:
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. |
WalkthroughThis 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. ChangesContext-aware DMS API Client
Estimated code review effort🎯 2 (Simple) | ⏱️ ~12 minutes Important Pre-merge checks failedPlease resolve all errors before merging. Addressing warnings is optional. ❌ Failed checks (1 error, 1 warning)
✅ Passed checks (10 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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.
Built for teams:
One agent for your entire SDLC. Right inside Slack. 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. Comment |
Codecov Report❌ Patch coverage is Additional details and impacted files@@ 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
🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
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 winAdd proper non-root user setup before switching to non-root USER directive.
The runtime stage (lines 7–13) has no
USERdirective and will run as root by default, weakening runtime hardening. While addingUSER 1001is the right goal, the proposed fix is incomplete forubi-minimal: UID 1001 doesn't exist in the base image and will cause a runtime failure.For
ubi-minimal, create the user first usingshadow-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
WORKDIRto 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 winFix nil pointer dereference: check
errbefore accessingresp.StatusCode.
http.Client.Domay return a nil response alongside an error for transport-level failures (DNS, connection refused, context cancellation, etc.). The current code accessesresp.StatusCodebefore checkingerr, 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 winFail 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. Prefert.Fatalfimmediately 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 winInconsistent decode-error handling in
Update.
ListAll,List,Create, andDeleteall wrap their decode failures with operation-specific messages (fmt.Errorf("error ...: %w", decodeErr)).Updatejust returns the rawjsonerror 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 liftThread
context.Contextthrough the publicClientinterface.The PR threads
ctxthrough the controller and utility layers, but every DMS call site passescontext.Background()because theClientinterface methods (ListAll,List,Create,Delete,Update,CheckIn,FindSnitchesByName) don't accept actx. This causes reconciliation cancellation/deadlines to stop at the DMS API boundary—outbound HTTP calls can outlive the Reconcile invocation.The internal
newRequestmethod already accepts and forwardsctxtohttp.NewRequestWithContext, so the plumbing exists. Consider acceptingctxin the interface methods and forwarding it intonewRequest/http.NewRequestWithContextto 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
createSnitchsilently swallows non-NotFound errors from the SyncSet Get.On line 309
r.Client.Get(...)is called; theif err != nilblock only branches onIsNotFound. Any other API error (timeout, transient 5xx, permission error) falls through, skips snitch creation, and the function returnsnil— 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 valueDeletion loop aborts on first CD failure — finalizer removal never happens.
If
deleteDMSClusterDeploymentfails for any CD inallCDs.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., viaerrors.Joinor aggregating with amultierr) 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 valueOptional: surface a warning when no timeout binary is available.
The portable timeout wrapper
${T:+$T 30s}silently falls back to runninggo build ./...(andgo mod tidyat line 117) with no timeout when neithertimeoutnorgtimeoutis onPATH. The header comment tells macOS users tobrew 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 whenTis 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
⛔ Files ignored due to path filters (8)
boilerplate/_data/backing-image-tagis excluded by!boilerplate/**boilerplate/_data/last-boilerplate-commitis excluded by!boilerplate/**boilerplate/openshift/golang-osd-operator/.codecov.ymlis excluded by!boilerplate/**boilerplate/openshift/golang-osd-operator/OWNERS_ALIASESis excluded by!boilerplate/**boilerplate/openshift/golang-osd-operator/golangci.ymlis excluded by!boilerplate/**boilerplate/openshift/golang-osd-operator/pre-commit-config.yamlis excluded by!boilerplate/**boilerplate/openshift/golang-osd-operator/standard.mkis excluded by!boilerplate/**boilerplate/openshift/golang-osd-operator/updateis excluded by!boilerplate/**
📒 Files selected for processing (15)
.ci-operator.yaml.claude/commands/pre-commit.md.codecov.yml.pre-commit-config.yamlOWNERS_ALIASESbuild/Dockerfilebuild/Dockerfile.olm-registrycontrollers/deadmanssnitchintegration/deadmanssnitchintegration_controller.gocontrollers/deadmanssnitchintegration/deadmanssnitchintegration_controller_test.gofips.gopkg/dmsclient/dmsclient.gopkg/localmetrics/localmetrics.gopkg/pko/template_test.gopkg/utils/secrets.gopkg/utils/utils.go
💤 Files with no reviewable changes (1)
- OWNERS_ALIASES
| ``` | ||
| 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 | ||
| ``` |
There was a problem hiding this comment.
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.
| ``` | |
| 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.
| - 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) |
There was a problem hiding this comment.
🧩 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/nullRepository: openshift/deadmanssnitch-operator
Length of output: 2071
🏁 Script executed:
cat -n boilerplate/openshift/golang-osd-operator/ensure.sh | head -50Repository: 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.
|
/label tide/merge-method-squash |
|
[APPROVALNOTIFIER] This PR is NOT APPROVED This pull-request has been approved by: charlesgong The full list of commands accepted by this bot can be found here. DetailsNeeds approval from an approver in each of these files:Approvers can indicate their approval by writing |
| "fmt" | ||
| "strings" | ||
|
|
||
| "github.com/go-logr/logr" |
There was a problem hiding this comment.
Why are there changes to the controller code as part of this PR?
There was a problem hiding this comment.
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%
|
@charlesgong: all tests passed! Full PR test history. Your PR dashboard. DetailsInstructions 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. |
There was a problem hiding this comment.
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 winPossible nil-pointer dereference and response-body leak in
do.Two defects on this path:
- When
c.httpClient.Do(req)returns a non-nil error,respis typically nil. The unconditionalresp.StatusCode == 401check on line 113 will panic before reaching theif err != nilbranch on line 117.- When the request succeeds but the API returns 401,
erris set on line 114 and the function returns the response witherr != nil. All callers follow the patternif err != nil { return ... }before setting updefer 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 winInconsistent error wrapping in
Update.
ListAll,List, andCreateall wrap JSON decode failures with an operation-specific message via%w, butUpdatereturns the rawjson.Decoder.Decodeerror 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 winReplace HTTP magic numbers with
net/httpconstants.
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
CheckInignores 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
Deletesilently 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
⛔ Files ignored due to path filters (2)
boilerplate/_data/last-boilerplate-commitis excluded by!boilerplate/**boilerplate/openshift/golang-osd-operator/OWNERS_ALIASESis excluded by!boilerplate/**
📒 Files selected for processing (12)
.claude/commands/pre-commit.mdOWNERS_ALIASESbuild/Dockerfilebuild/Dockerfile.olm-registrycontrollers/deadmanssnitchintegration/deadmanssnitchintegration_controller.gocontrollers/deadmanssnitchintegration/deadmanssnitchintegration_controller_test.gofips.gopkg/dmsclient/dmsclient.gopkg/localmetrics/localmetrics.gopkg/pko/template_test.gopkg/utils/secrets.gopkg/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>` |
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
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.
| 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` |
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
🛠️ 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.
| 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) |
There was a problem hiding this comment.
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.
|
closed in favour of #285 |
|
/close |
|
@devppratik: Closed this PR. DetailsIn response to this:
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. |
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):
Summary by CodeRabbit
Release Notes
Chores
Tests
Documentation