Skip to content

NO-JIRA: Add --proxy-url support to oc login - #2360

Open
kchawlani19 wants to merge 4 commits into
openshift:mainfrom
kchawlani19:feature/oc-login-proxy-url
Open

NO-JIRA: Add --proxy-url support to oc login#2360
kchawlani19 wants to merge 4 commits into
openshift:mainfrom
kchawlani19:feature/oc-login-proxy-url

Conversation

@kchawlani19

@kchawlani19 kchawlani19 commented Aug 11, 2026

Copy link
Copy Markdown

Summary

  • Add --proxy-url to oc login so login uses a per-cluster proxy and persists it to kubeconfig cluster.proxy-url.
  • Reuse an existing cluster proxy-url when the flag is omitted, so re-login no longer drops it (including when HTTPS_PROXY is set).
  • Leave rest.Config.Proxy unset when neither flag nor kubeconfig proxy is present, so env proxies still apply without being written into kubeconfig.

Fixes #2314

Test plan

  • Unit: --proxy-url flag accepted and validated (http/https/socks5; reject invalid schemes)
  • Unit: login client uses --proxy-url during dial
  • Unit: existing cluster proxy-url is reused when flag is omitted
  • Unit: --proxy-url overrides an existing cluster proxy
  • Unit: SaveConfig / CreateConfig persist proxy-url; unrelated clusters keep distinct proxies
  • Unit: HTTPS_PROXY alone is not written into kubeconfig
  • CI: unit / verify / verify-deps green
  • Manual (optional): oc login --proxy-url=http://<proxy>:3128 ... and confirm kubeconfig clusters.*.proxy-url

Summary by CodeRabbit

  • New Features

    • Added --proxy-url support to the login command.
    • Supports HTTP, HTTPS, and SOCKS5 proxy URLs.
    • Reuses existing cluster proxy settings when no new proxy is specified.
    • Saves explicitly configured proxy settings to the login configuration.
  • Bug Fixes

    • Invalid or unsupported proxy URLs now produce clear validation errors.
    • Proxy settings are preserved correctly when configurations are merged.

Allow login to use and persist a per-cluster kubeconfig proxy-url so re-login no longer drops existing proxy settings when HTTPS_PROXY is used.

Co-authored-by: Cursor <cursoragent@cursor.com>
@openshift-merge-bot

Copy link
Copy Markdown
Contributor

Pipeline controller notification
This repo is configured to use the pipeline controller. Second-stage tests will be triggered either automatically or after lgtm label is added, depending on the repository configuration. The pipeline controller will automatically detect which contexts are required and will utilize /test Prow commands to trigger the second stage.

For optional jobs, comment /test ? to see a list of all defined jobs. To trigger manually all jobs from second stage use /pipeline required command.

This repository is configured in: LGTM mode

@coderabbitai

coderabbitai Bot commented Aug 11, 2026

Copy link
Copy Markdown

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository YAML (base), Central YAML (inherited)

Review profile: CHILL

Plan: Pro Plus

Run ID: 7e04e022-a2cb-4306-8fe5-2302b0b652c9

📥 Commits

Reviewing files that changed from the base of the PR and between 21c96da and ec5b7e7.

📒 Files selected for processing (1)
  • pkg/cli/login/loginoptions_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/cli/login/loginoptions_test.go

Walkthrough

The login command accepts validated http, https, and socks5 proxy URLs. It applies explicit or existing cluster proxies to the REST client and preserves cluster-specific proxy settings in kubeconfig.

Changes

Login proxy support

Layer / File(s) Summary
Proxy contract and cluster selection
pkg/cli/login/helpers.go, pkg/cli/login/login.go, pkg/cli/login/loginoptions.go, pkg/cli/login/loginoptions_test.go
The login command registers --proxy-url. Proxy parsing accepts http, https, and socks5 schemes with required hosts. Invalid values return validation errors. Cluster lookup checks the canonical server-derived nickname before the existing fallback.
REST client proxy configuration
pkg/cli/login/loginoptions.go, pkg/cli/login/loginoptions_test.go
Client configuration applies an explicit proxy or reuses the matching cluster proxy. Explicit values override existing values. rest.Config.Proxy remains nil when no proxy is configured. TLS fallback behavior remains unchanged.
Kubeconfig proxy persistence
pkg/cli/login/loginoptions_test.go, pkg/helpers/kubeconfig/smart_merge_test.go
Persistence tests verify proxy retention, distinct cluster proxies, omission of unset proxies, and exclusion of environment-derived proxies.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant LoginCommand
  participant LoginOptions
  participant RESTClient
  participant Kubeconfig
  User->>LoginCommand: provide --proxy-url
  LoginCommand->>LoginOptions: validate ProxyURL
  LoginOptions->>RESTClient: configure rest.Config.Proxy
  LoginOptions->>Kubeconfig: persist cluster proxy
  Kubeconfig-->>User: updated kubeconfig
Loading

Suggested reviewers: atiratree, ardaguclu


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
No-Sensitive-Data-In-Logs ❌ Error New validation errors interpolate raw proxyURL, while net/url accepts user:password@host; CheckErr prints these errors, exposing proxy credentials in CLI diagnostics. Do not include raw proxyURL in errors. Return generic validation messages or use URL.Redacted() after parsing, and redact input in parse failures.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (13 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the primary change: adding --proxy-url support to oc login.
Linked Issues check ✅ Passed The changes implement --proxy-url support, proxy validation and use, kubeconfig persistence, proxy reuse, and distinct per-cluster proxy behavior required by [#2314].
Out of Scope Changes check ✅ Passed All implementation and test changes directly support proxy handling for oc login and kubeconfig persistence, with no unrelated code changes.
Stable And Deterministic Test Names ✅ Passed The PR adds only static Go Test names and literal table-driven t.Run labels; no Ginkgo It/Describe/Context/When titles or dynamic test-title values were found.
Test Structure And Quality ✅ Passed Changed tests use Go testing (Test/t.Run), not Ginkgo; they contain no It, Eventually, or cluster resources, so this Ginkgo-specific check is not applicable.
Microshift Test Compatibility ✅ Passed The complete PR range adds only standard Go testing.T unit tests; no Ginkgo tests or MicroShift-sensitive APIs, namespaces, or assumptions were added.
Single Node Openshift (Sno) Test Compatibility ✅ Passed The feature history changes only Go implementation and standard testing unit tests; no new Ginkgo e2e declarations or multi-node assumptions are present.
Topology-Aware Scheduling Compatibility ✅ Passed The PR changes only CLI login and kubeconfig helpers/tests; searches found no deployment, controller, manifest, replica, affinity, topology, node-selector, taint, or PDB scheduling changes.
Ote Binary Stdout Contract ✅ Passed No OTE process-level stdout write is introduced; klog v2 defaults to stderr, and OTE configures GinkgoWriter to os.Stderr. Test logs use GinkgoWriter or klog.
Ipv6 And Disconnected Network Test Compatibility ✅ Passed The PR adds only standard Go Test functions, not Ginkgo e2e tests; its HTTP coverage uses local httptest servers and no public network services.
No-Weak-Crypto ✅ Passed The feature diff adds proxy URL parsing and HTTP proxy wiring only. It introduces no MD5, SHA1, DES, RC4, Blowfish, ECB, custom crypto, or non-constant-time secret/token comparisons; existing bytes...
Container-Privileges ✅ Passed The cumulative PR diff changes only five Go files and adds no privileged, host namespace, SYS_ADMIN, or allowPrivilegeEscalation settings in manifests.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@kchawlani19

Copy link
Copy Markdown
Author

/test

@openshift-ci

openshift-ci Bot commented Aug 11, 2026

Copy link
Copy Markdown
Contributor

@kchawlani19: The /test command needs one or more targets.
The following commands are available to trigger required jobs:

/test build-rpms-from-tar
/test e2e-agnostic-ovn-cmd
/test e2e-aws-ovn
/test e2e-aws-ovn-serial-1of2
/test e2e-aws-ovn-serial-2of2
/test e2e-aws-ovn-upgrade
/test images
/test okd-scos-images
/test rpm-build
/test unit
/test verify
/test verify-deps

The following commands are available to trigger optional jobs:

/test e2e-agent-compact-ipv4
/test e2e-aws-certrotation
/test e2e-aws-oc-ote
/test e2e-aws-oc-ote-serial
/test e2e-aws-ovn-builds
/test e2e-metal-ipi-ovn-ipv6
/test okd-scos-e2e-aws-ovn
/test security

Use /test all to run the following jobs that were automatically triggered:

pull-ci-openshift-oc-main-build-rpms-from-tar
pull-ci-openshift-oc-main-images
pull-ci-openshift-oc-main-okd-scos-images
pull-ci-openshift-oc-main-rpm-build
pull-ci-openshift-oc-main-security
pull-ci-openshift-oc-main-unit
pull-ci-openshift-oc-main-verify
pull-ci-openshift-oc-main-verify-deps
Details

In response to this:

/test

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.

@openshift-ci
openshift-ci Bot requested review from ardaguclu and atiratree August 11, 2026 05:07
@openshift-ci

openshift-ci Bot commented Aug 11, 2026

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is NOT APPROVED

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

@kchawlani19 kchawlani19 changed the title Add --proxy-url support to oc login. NO-JIRA: Add --proxy-url support to oc login Aug 11, 2026
@kchawlani19

Copy link
Copy Markdown
Author

Updated the PR title to NO-JIRA: so Tide can pick up jira/valid-reference (this change tracks GitHub issue #2314 rather than an OCPBUGS ticket). The description now links the issue and includes a test plan.

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

Copy link
Copy Markdown

@kchawlani19: This pull request explicitly references no jira issue.

Details

In response to this:

Summary

  • Add --proxy-url to oc login so login uses a per-cluster proxy and persists it to kubeconfig cluster.proxy-url.
  • Reuse an existing cluster proxy-url when the flag is omitted, so re-login no longer drops it (including when HTTPS_PROXY is set).
  • Leave rest.Config.Proxy unset when neither flag nor kubeconfig proxy is present, so env proxies still apply without being written into kubeconfig.

Fixes #2314

Test plan

  • Unit: --proxy-url flag accepted and validated (http/https/socks5; reject invalid schemes)
  • Unit: login client uses --proxy-url during dial
  • Unit: existing cluster proxy-url is reused when flag is omitted
  • Unit: --proxy-url overrides an existing cluster proxy
  • Unit: SaveConfig / CreateConfig persist proxy-url; unrelated clusters keep distinct proxies
  • Unit: HTTPS_PROXY alone is not written into kubeconfig
  • CI: unit / verify / verify-deps green
  • Manual (optional): oc login --proxy-url=http://<proxy>:3128 ... and confirm kubeconfig clusters.*.proxy-url

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

🧹 Nitpick comments (2)
pkg/cli/login/helpers.go (1)

23-26: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Wrap the URL parse error.

Line 25 discards err. Return contextual error text with %w so callers retain the parse cause.

Proposed fix
 if err != nil {
-	return nil, fmt.Errorf("could not parse: %v", proxyURL)
+	return nil, fmt.Errorf("parse proxy URL %q: %w", proxyURL, err)
 }

As per coding guidelines, “Wrap errors with meaningful context before returning or logging them.”

🤖 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/cli/login/helpers.go` around lines 23 - 26, Update the error return in
the proxy URL parsing flow around url.Parse to wrap the original err with %w
while retaining meaningful context; do not substitute proxyURL for the parse
error, so callers can inspect the underlying cause.

Source: Coding guidelines

pkg/cli/login/loginoptions_test.go (1)

661-661: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Add descriptive comments to the new test functions.

  • pkg/cli/login/loginoptions_test.go#L661-L661: add a comment for TestLoginProxyURLFlagAccepted.
  • pkg/cli/login/loginoptions_test.go#L672-L672: add a comment for TestValidateProxyURL.
  • pkg/cli/login/loginoptions_test.go#L731-L731: add a comment for TestGetClientConfigUsesProxyURL.
  • pkg/cli/login/loginoptions_test.go#L789-L789: add a comment for TestGetClientConfigPreservesExistingClusterProxyURL.
  • pkg/cli/login/loginoptions_test.go#L835-L835: add a comment for TestGetClientConfigProxyURLFlagOverridesExisting.
  • pkg/cli/login/loginoptions_test.go#L889-L889: add a comment for TestGetClientConfigLeavesProxyNilWithoutFlagOrClusterProxy.
  • pkg/cli/login/loginoptions_test.go#L909-L909: add a comment for TestSaveConfigPersistsAndPreservesProxyURL.
  • pkg/cli/login/loginoptions_test.go#L981-L981: add a comment for TestSaveConfigDoesNotPersistEnvProxyWhenUnset.
  • pkg/helpers/kubeconfig/smart_merge_test.go#L102-L102: add a comment for TestCreateConfigPersistsProxyURL.
  • pkg/helpers/kubeconfig/smart_merge_test.go#L126-L126: add a comment for TestCreateConfigDoesNotPersistProxyWhenUnset.
  • pkg/helpers/kubeconfig/smart_merge_test.go#L144-L144: add a comment for TestMergeConfigKeepsDistinctClusterProxyURLs.

As per coding guidelines, “Add descriptive comments to all exported and unexported Go types, functions, and methods.”

🤖 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/cli/login/loginoptions_test.go` at line 661, Each listed test function
lacks the required descriptive Go comment. Add a concise comment immediately
before every named function in pkg/cli/login/loginoptions_test.go at lines
661-661, 672-672, 731-731, 789-789, 835-835, 889-889, 909-909, and 981-981, and
in pkg/helpers/kubeconfig/smart_merge_test.go at lines 102-102, 126-126, and
144-144, describing the behavior or scenario that test verifies; make each
comment begin with its corresponding function name.

Source: Coding guidelines

🤖 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 `@pkg/cli/login/helpers.go`:
- Around line 22-33: Update parseProxyURL to reject parsed URLs with an empty
u.Host, returning an appropriate validation error before the scheme-based
success path; extend TestValidateProxyURL to cover both http:// and http:/proxy
as invalid inputs.

In `@pkg/cli/login/loginoptions.go`:
- Around line 171-180: Update the cluster lookup used by the proxy-selection
flow around findCluster and CreateConfig so it resolves the stable canonical
cluster identity that will be replaced or required by CreateConfig, rather than
an arbitrary entry sharing the same host. Preserve explicit --proxy-url
precedence, and add coverage for duplicate server entries with different
ProxyURL values to verify the selected proxy belongs to the canonical cluster.

---

Nitpick comments:
In `@pkg/cli/login/helpers.go`:
- Around line 23-26: Update the error return in the proxy URL parsing flow
around url.Parse to wrap the original err with %w while retaining meaningful
context; do not substitute proxyURL for the parse error, so callers can inspect
the underlying cause.

In `@pkg/cli/login/loginoptions_test.go`:
- Line 661: Each listed test function lacks the required descriptive Go comment.
Add a concise comment immediately before every named function in
pkg/cli/login/loginoptions_test.go at lines 661-661, 672-672, 731-731, 789-789,
835-835, 889-889, 909-909, and 981-981, and in
pkg/helpers/kubeconfig/smart_merge_test.go at lines 102-102, 126-126, and
144-144, describing the behavior or scenario that test verifies; make each
comment begin with its corresponding function name.
🪄 Autofix

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 YAML (base), Central YAML (inherited)

Review profile: CHILL

Plan: Pro Plus

Run ID: 7e90dc3f-4365-41e6-a3a3-de209af6b73f

📥 Commits

Reviewing files that changed from the base of the PR and between 77a4a5a and 88497f6.

📒 Files selected for processing (5)
  • pkg/cli/login/helpers.go
  • pkg/cli/login/login.go
  • pkg/cli/login/loginoptions.go
  • pkg/cli/login/loginoptions_test.go
  • pkg/helpers/kubeconfig/smart_merge_test.go

Comment thread pkg/cli/login/helpers.go
Comment thread pkg/cli/login/loginoptions.go
Address review feedback so invalid proxy URLs fail early and duplicate server entries reuse the CreateConfig cluster nickname.

Co-authored-by: Cursor <cursoragent@cursor.com>

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

♻️ Duplicate comments (1)
pkg/cli/login/helpers.go (1)

34-36: 🎯 Functional Correctness | 🟡 Minor

Reject proxy URLs with a port but no hostname.

len(u.Host) != 0 does not prove that the URL has a hostname. url.Parse("http://:8080") produces u.Host == ":8080" and u.Hostname() == "", so this invalid value passes validation and reaches proxy configuration. Check u.Hostname() == "" instead. Add regression cases for http://:8080 and socks5://:1080.

Proposed fix
-	if len(u.Host) == 0 {
+	if u.Hostname() == "" {
 		return nil, fmt.Errorf("host must be specified")
 	}
#!/bin/bash
set -euo pipefail

cat >/tmp/proxy_host_probe.go <<'EOF'
package main

import (
	"fmt"
	"net/url"
)

func main() {
	for _, raw := range []string{"http://:8080", "socks5://:1080"} {
		u, err := url.Parse(raw)
		fmt.Printf("%q: err=%v host=%q hostname=%q\n", raw, err, u.Host, u.Hostname())
	}
}
EOF

go run /tmp/proxy_host_probe.go
🤖 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/cli/login/helpers.go` around lines 34 - 36, Update the proxy URL
validation in the visible helper to check u.Hostname() rather than len(u.Host),
rejecting URLs with a port but no hostname. Add regression coverage for
http://:8080 and socks5://:1080, while preserving acceptance of valid proxy
URLs.
🤖 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.

Duplicate comments:
In `@pkg/cli/login/helpers.go`:
- Around line 34-36: Update the proxy URL validation in the visible helper to
check u.Hostname() rather than len(u.Host), rejecting URLs with a port but no
hostname. Add regression coverage for http://:8080 and socks5://:1080, while
preserving acceptance of valid proxy URLs.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository YAML (base), Central YAML (inherited)

Review profile: CHILL

Plan: Pro Plus

Run ID: 78349c43-4015-4b14-8a53-ce07e23b7f07

📥 Commits

Reviewing files that changed from the base of the PR and between 88497f6 and b807546.

📒 Files selected for processing (2)
  • pkg/cli/login/helpers.go
  • pkg/cli/login/loginoptions_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/cli/login/loginoptions_test.go

@kchawlani19

Copy link
Copy Markdown
Author

Hi @ardaguclu @atiratree — could you take a look when you have a chance?

This adds oc login --proxy-url (fixes #2314):

  • uses the proxy for the login client
  • persists it to kubeconfig cluster.proxy-url
  • preserves an existing proxy-url when the flag is omitted

First-stage CI is green. Happy to address any feedback.
/cc @ardaguclu @atiratree

@ardaguclu

Copy link
Copy Markdown
Member

Thanks for spending time on this. But I think, we don't have any capacity to review these changes for now.

@kchawlani19

Copy link
Copy Markdown
Author

Thanks @ardaguclu for the update — understood. Happy to keep the PR open and follow up later when you have bandwidth. Please let me know if there's a better time or another reviewer I should ping.

Comment thread pkg/cli/login/loginoptions_test.go Outdated
func TestGetClientConfigUsesProxyURL(t *testing.T) {
apiHit := make(chan struct{}, 1)
apiServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
apiHit <- struct{}{}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I don't have time to review all of this right now, so I may continue later, but you could use an atomic type here so that you don't have to do select at the end, but just load a value and compare.

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.

Thanks @tchap — updated in the latest commit to use atomic.Bool / atomic.Value instead of channel+select.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The cast to string will panic, though, if the value is not there. Not too great. Use atomic.Pointer[string] or check the cast worked and fail if not. Thanks.

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.

Good catch — switched to atomic.Pointer[string] and nil-check on Load(). Thanks!

kchawlani19 and others added 2 commits August 11, 2026 18:39
Address review feedback by replacing channel/select hit tracking with atomic loads for clearer assertions.

Co-authored-by: Cursor <cursoragent@cursor.com>
Avoid type-asserting an unset atomic.Value when checking that dial went through the proxy.

Co-authored-by: Cursor <cursoragent@cursor.com>
@openshift-ci

openshift-ci Bot commented Aug 11, 2026

Copy link
Copy Markdown
Contributor

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

Comment thread pkg/cli/login/helpers.go
if cluster, ok := kubeconfig.Clusters[nick]; ok && cluster.Server == host {
return cluster
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I am not sure this is needed, strictly speaking, but it also doesn't hurt...

Comment thread pkg/cli/login/login.go

if len(o.ProxyURL) > 0 {
if _, err := parseProxyURL(o.ProxyURL); err != nil {
return fmt.Errorf("invalid --proxy-url %q: %w", o.ProxyURL, err)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I would improve the error messages in parseProxyURL so that we don't have to wrap here. The same goes for setClientConfigProxy call below. Wrapping it down there with invalid proxy URL leaks internals of setClientConfigProxy. How can you know the error is related to proxy URL? Better to generate meaningful and complete errors in parseProxyURL and just return it without wrapping...

// ProxyURL, when set, is used for the login HTTP client and persisted to the
// kubeconfig cluster's proxy-url field. When empty, an existing cluster
// proxy-url is preserved; otherwise HTTPS_PROXY/HTTP_PROXY may still apply
// via the default transport when rest.Config.Proxy is nil.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

We should rather be sure the usual HTTPS_PROXY/HTTP_PROXY still works. Does it still work? We should make the docstring more exact.

}
if err := cmd.Flags().Set("proxy-url", "http://squid.example.com:3128"); err != nil {
t.Fatalf("expected --proxy-url to accept a value: %v", err)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Is this really testing anything useful? I mean the Set part...

testCases := []struct {
name string
proxyURL string
expectErrSubstr string

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I think that we know the exact full error message, so let's match against the full error message exactly and rename this to expectedErrMsg or something like that.

t.Fatalf("expected proxy %q, got %v", proxyServer.URL, got)
}

// dialToServer requests the API root; absolute form may include a trailing slash.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pls extend this to mention that getClientConfig is actually making the real request.

}
if got == nil || got.String() != proxyServer.URL {
t.Fatalf("expected proxy %q, got %v", proxyServer.URL, got)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

IMO this whole section can be dropped, it's not really testing anything relevant that is not tested by the following check.

}
}

func TestGetClientConfigPrefersCanonicalClusterProxyURL(t *testing.T) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This is not a particularly robust test, because even if we just iterate as we did before, we can accidentally find the right cluster since map iteration is non-deterministic.

}
if got == nil || got.String() != proxyServer.URL {
t.Fatalf("expected preserved proxy %q, got %v", proxyServer.URL, got)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I don't really like that we are sending the real request in getClientConfig and then also calling Proxy directly and checking the result. We can store what server was called in the request handlers and then just check that, we don't need to create another request and call Proxy. We should simplify this in all tests where possible.

}
}

func TestSaveConfigPersistsAndPreservesProxyURL(t *testing.T) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I reviewed up until here for now. Can we pls restructure the tests so that we have a top-level wrapper TestProxyURL or TestProxyURLFlag and then we can use t.Run() for each test that is now a top-level thing? So that we can see these are all related.

Also pls add a doc comment to each test quickly explaining what that test is testing. This really helps with review.

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.

oc login should support proxy-url option

4 participants