Skip to content

CNF-23378: Migrate away from deprecated ioutil - #156

Open
sebrandon1 wants to merge 2 commits into
openshift:masterfrom
sebrandon1:ioutil_deprecation
Open

CNF-23378: Migrate away from deprecated ioutil#156
sebrandon1 wants to merge 2 commits into
openshift:masterfrom
sebrandon1:ioutil_deprecation

Conversation

@sebrandon1

@sebrandon1 sebrandon1 commented Nov 24, 2025

Copy link
Copy Markdown
Member

ioutil has been deprecated since Go 1.16: https://go.dev/doc/go1.16#ioutil

Tracking issue: redhat-best-practices-for-k8s/telco-bot#52

Migration from ioutil to os/io:

  • Replaced ioutil.TempFile with os.CreateTemp in integration.go for creating temporary kubeconfig files.
  • Replaced ioutil.TempDir with os.MkdirTemp in testserver.go for creating temporary directories.
  • Updated imports in integration.go, testserver.go, and tokenreviews.go to remove ioutil and add os or io as needed. [1] [2] [3]
  • Replaced ioutil.ReadAll with io.ReadAll in tokenreviews.go for reading HTTP response bodies. [1] [2]

Summary by CodeRabbit

  • Chores
    • Updated test infrastructure to use current standard-library APIs for temporary files, temporary directories, and response-body handling.
    • Preserved existing test behavior, error handling, and cleanup processes while reducing deprecation warnings and improving future compatibility.

@sebrandon1

Copy link
Copy Markdown
Member Author

/retest

@coderabbitai

coderabbitai Bot commented Apr 30, 2026

Copy link
Copy Markdown

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

Replaces deprecated ioutil APIs with os.CreateTemp, os.MkdirTemp, and io.ReadAll in test setup and token review response handling.

Changes

Go standard library API migration

Layer / File(s) Summary
Temporary resource creation
pkg/cmd/oauth-apiserver/testing/integration.go, pkg/cmd/oauth-apiserver/testing/testserver.go
Test helpers use os.CreateTemp and os.MkdirTemp. Related io/ioutil imports were removed.
Token review body reading
test/e2e/tokenreviews.go
Both token review response paths use io.ReadAll. The import was updated accordingly.

Estimated code review effort: 2 (Simple) | ~10 minutes

Suggested reviewers: sanchezl, deads2k

🚥 Pre-merge checks | ✅ 14 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (14 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: replacing deprecated Go ioutil usage with current standard-library APIs.
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 The PR changes only standard-library calls and imports. It adds or changes no It, Describe, Context, When, or other test title declarations.
Test Structure And Quality ✅ Passed PASS: No Ginkgo test code changed. The only test changes replace ioutil.ReadAll with io.ReadAll; existing cleanup and behavior remain unchanged.
Microshift Test Compatibility ✅ Passed The patch adds no Ginkgo tests. It only replaces deprecated ioutil calls, and the existing e2e test remains a standard TestTokenReviews function.
Single Node Openshift (Sno) Test Compatibility ✅ Passed The commit adds no Ginkgo e2e tests. It only changes ioutil calls and imports; existing TestTokenReviews is unchanged in behavior and adds no SNO-incompatible assumptions.
Topology-Aware Scheduling Compatibility ✅ Passed The commit changes only three Go test files to replace deprecated ioutil APIs; it adds no deployment manifests, operator/controller code, replicas, affinity, topology spread, node selectors, tolera...
Ote Binary Stdout Contract ✅ Passed PR changes only ioutil APIs; no process-level stdout writes were added. OTE main is unchanged, klog defaults to stderr, and os.Stdout is used only by a test helper.
Ipv6 And Disconnected Network Test Compatibility ✅ Passed PASS: The patch only replaces ioutil APIs. It adds no Ginkgo tests, IPv4 assumptions, or external connectivity requirements.
No-Weak-Crypto ✅ Passed The commit only replaces ioutil APIs with os.CreateTemp, os.MkdirTemp, and io.ReadAll; it adds no weak crypto, custom crypto, or secret comparison.
Container-Privileges ✅ Passed The PR only changes Go standard-library calls. No privileged, hostPID, hostNetwork, hostIPC, SYS_ADMIN, root, or allowPrivilegeEscalation settings appear in the diff or repository manifests.
No-Sensitive-Data-In-Logs ✅ Passed The diff only replaces deprecated APIs. It adds no logging, and existing logs expose only a local port and health-check status, not passwords, tokens, PII, hostnames, or customer data.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

@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.

Caution

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

⚠️ Outside diff range comments (3)
pkg/cmd/oauth-apiserver/testing/integration.go (2)

14-60: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Fix nil-pointer panic: storageConfig can be nil in StartDefaultTestServer.

StartDefaultIntegrationTestServer passes storageConfig=nil into StartDefaultTestServer, but StartDefaultTestServer unconditionally accesses storageConfig.EventsHistoryWindow (Line 40). This will panic at runtime.

🛠️ Proposed fix (make the EventsHistoryWindow override nil-safe)
-	fakeKubeConfig.Close()
-	storageConfig.EventsHistoryWindow = max(storageConfig.EventsHistoryWindow, storagebackend.DefaultEventsHistoryWindow)
+	fakeKubeConfig.Close()
+	if storageConfig != nil {
+		storageConfig.EventsHistoryWindow = max(storageConfig.EventsHistoryWindow, storagebackend.DefaultEventsHistoryWindow)
+	}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/cmd/oauth-apiserver/testing/integration.go` around lines 14 - 60,
StartDefaultTestServer dereferences storageConfig.EventsHistoryWindow which can
be nil; update StartDefaultTestServer to handle a nil storageConfig by creating
or using a local default storagebackend.Config when storageConfig == nil (or by
guarding the access) before calling max(storageConfig.EventsHistoryWindow,
storagebackend.DefaultEventsHistoryWindow) so the code never dereferences a nil
pointer; adjust any later use of storageConfig (passed into StartTestServer) to
pass the defaulted/local config instead of nil.

20-39: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Handle temp kubeconfig WriteString/Close errors instead of ignoring them.

Currently the return values from fakeKubeConfig.WriteString(...) (Lines 20-38) and fakeKubeConfig.Close() (Line 39) are not checked. If those operations fail, the subsequent server startup can fail in confusing ways.

🛠️ Proposed fix (check errors and clean up the temp file)
-	fakeKubeConfig.WriteString(`
+	if _, err := fakeKubeConfig.WriteString(`
 apiVersion: v1
 kind: Config
 clusters:
 - cluster:
     server: http://127.1.2.3:12345
   name: integration
 contexts:
 - context:
     cluster: integration
   user: test
   name: default-context
 current-context: default-context
 users:
 - name: test
   user:
     password: test
     username: test
 `)
-	fakeKubeConfig.Close()
+	); err != nil {
+		name := fakeKubeConfig.Name()
+		_ = fakeKubeConfig.Close()
+		_ = os.Remove(name)
+		return nil, nil, err
+	}
+
+	if err := fakeKubeConfig.Close(); err != nil {
+		name := fakeKubeConfig.Name()
+		_ = os.Remove(name)
+		return nil, nil, err
+	}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/cmd/oauth-apiserver/testing/integration.go` around lines 20 - 39, The
temporary kubeconfig file operations currently ignore errors from
fakeKubeConfig.WriteString(...) and fakeKubeConfig.Close(), which can mask
failures; update the setup to check the returned (n, err) from
fakeKubeConfig.WriteString and handle any error (fail the test or return the
error), and likewise check the error returned by fakeKubeConfig.Close(); on any
error ensure the temp file is cleaned up (remove it) and propagate/fail
appropriately so server startup won't proceed with a bad kubeconfig; reference
the fakeKubeConfig variable and its WriteString and Close calls when making
these changes.
test/e2e/tokenreviews.go (1)

51-80: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Add resp.StatusCode assertions to make failures more actionable.

After each insecureClient.Do(...), add a require.Equal(t, http.StatusOK, resp.StatusCode) before reading/unmarshalling the body. Otherwise, if the endpoint returns a non-200 (authn/authz/proxy issues), the test may fail later with JSON/unmarshal noise instead of an obvious HTTP status mismatch.

🛠️ Proposed fix
  resp, err := insecureClient.Do(failedReviewReq)
  require.NoError(t, err)
+	require.Equal(t, http.StatusOK, resp.StatusCode)
  defer resp.Body.Close()

  respBodyBytes, err := io.ReadAll(resp.Body)
  require.NoError(t, err)
  resp, err = insecureClient.Do(successfulReviewReq)
  require.NoError(t, err)
+	require.Equal(t, http.StatusOK, resp.StatusCode)
  defer resp.Body.Close()

  respBodyBytes, err = io.ReadAll(resp.Body)
  require.NoError(t, err)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/e2e/tokenreviews.go` around lines 51 - 80, After each call to
insecureClient.Do (used with createTokenReviewRequestForToken for both
"notaveryrandomnameforanything" and accessToken.Name) assert the HTTP status
code is OK before reading the body: check resp.StatusCode equals http.StatusOK
and fail the test early if not, so subsequent io.ReadAll and json.Unmarshal on
tokenReviewResp are only executed on successful 200 responses; add this
require.Equal(t, http.StatusOK, resp.StatusCode) immediately after each
insecureClient.Do and before resp.Body.Close()/io.ReadAll and unmarshalling.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@pkg/cmd/oauth-apiserver/testing/integration.go`:
- Around line 14-60: StartDefaultTestServer dereferences
storageConfig.EventsHistoryWindow which can be nil; update
StartDefaultTestServer to handle a nil storageConfig by creating or using a
local default storagebackend.Config when storageConfig == nil (or by guarding
the access) before calling max(storageConfig.EventsHistoryWindow,
storagebackend.DefaultEventsHistoryWindow) so the code never dereferences a nil
pointer; adjust any later use of storageConfig (passed into StartTestServer) to
pass the defaulted/local config instead of nil.
- Around line 20-39: The temporary kubeconfig file operations currently ignore
errors from fakeKubeConfig.WriteString(...) and fakeKubeConfig.Close(), which
can mask failures; update the setup to check the returned (n, err) from
fakeKubeConfig.WriteString and handle any error (fail the test or return the
error), and likewise check the error returned by fakeKubeConfig.Close(); on any
error ensure the temp file is cleaned up (remove it) and propagate/fail
appropriately so server startup won't proceed with a bad kubeconfig; reference
the fakeKubeConfig variable and its WriteString and Close calls when making
these changes.

In `@test/e2e/tokenreviews.go`:
- Around line 51-80: After each call to insecureClient.Do (used with
createTokenReviewRequestForToken for both "notaveryrandomnameforanything" and
accessToken.Name) assert the HTTP status code is OK before reading the body:
check resp.StatusCode equals http.StatusOK and fail the test early if not, so
subsequent io.ReadAll and json.Unmarshal on tokenReviewResp are only executed on
successful 200 responses; add this require.Equal(t, http.StatusOK,
resp.StatusCode) immediately after each insecureClient.Do and before
resp.Body.Close()/io.ReadAll and unmarshalling.

ℹ️ Review info
⚙️ Run configuration

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

Review profile: CHILL

Plan: Enterprise

Run ID: cec8a7f8-f929-4f6d-b92d-8a156dfe0928

📥 Commits

Reviewing files that changed from the base of the PR and between 160ac7f and 8264f7d.

📒 Files selected for processing (3)
  • pkg/cmd/oauth-apiserver/testing/integration.go
  • pkg/cmd/oauth-apiserver/testing/testserver.go
  • test/e2e/tokenreviews.go

@sebrandon1 sebrandon1 changed the title Migrate away from deprecated ioutil CNF-23378: Migrate away from deprecated ioutil Apr 30, 2026
@openshift-ci-robot openshift-ci-robot added the jira/valid-reference Indicates that this PR references a valid Jira ticket of any type. label Apr 30, 2026
@openshift-ci-robot

openshift-ci-robot commented Apr 30, 2026

Copy link
Copy Markdown
Contributor

@sebrandon1: This pull request references CNF-23378 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:

ioutil has been deprecated since Go 1.16: https://go.dev/doc/go1.16#ioutil

Tracking issue: redhat-best-practices-for-k8s/telco-bot#52

Migration from ioutil to os/io:

  • Replaced ioutil.TempFile with os.CreateTemp in integration.go for creating temporary kubeconfig files.
  • Replaced ioutil.TempDir with os.MkdirTemp in testserver.go for creating temporary directories.
  • Updated imports in integration.go, testserver.go, and tokenreviews.go to remove ioutil and add os or io as needed. [1] [2] [3]
  • Replaced ioutil.ReadAll with io.ReadAll in tokenreviews.go for reading HTTP response bodies. [1] [2]

Summary by CodeRabbit

  • Chores
  • Updated deprecated library function calls to current standard library equivalents across multiple components for improved code maintainability.

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.

@sebrandon1

Copy link
Copy Markdown
Member Author

/retest

@sebrandon1
sebrandon1 force-pushed the ioutil_deprecation branch from 8264f7d to b5d4ffc Compare May 13, 2026 21:27
@openshift-ci

openshift-ci Bot commented May 13, 2026

Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by:
Once this PR has been reviewed and has the lgtm label, please assign kaleemsiddiqu 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

@sebrandon1

Copy link
Copy Markdown
Member Author

/retest

@openshift-ci

openshift-ci Bot commented Jul 31, 2026

Copy link
Copy Markdown

@sebrandon1: The following tests failed, say /retest to rerun all failed tests or /retest-required to rerun all mandatory failed tests:

Test name Commit Details Required Rerun command
ci/prow/e2e-gcp-component-serial-disruptive-ote 66b8c3f link false /test e2e-gcp-component-serial-disruptive-ote
ci/prow/e2e-gcp-component-serial-ote 66b8c3f link false /test e2e-gcp-component-serial-ote

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.

@sebrandon1

Copy link
Copy Markdown
Member Author

Progress update: 5 of 19 PRs in this ioutil migration effort have merged! 🎉

Recently merged:

This PR has been rebased against the latest upstream and is ready for review.

Epic: CNF-23315

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.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants