Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

OCM-5952: Server name inference for regionalized OCM redirects #958

Merged
merged 1 commit into from
May 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 71 additions & 0 deletions examples/regionalized_current_account.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/*
Copyright (c) 2024 Red Hat, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package main

import (
"context"
"fmt"
"os"

sdk "github.com/openshift-online/ocm-sdk-go"
"github.com/openshift-online/ocm-sdk-go/logging"
)

func main() {
// Create a context:
ctx := context.Background()

// Create a logger that has the debug level enabled:
logger, err := logging.NewGoLoggerBuilder().
Debug(true).
Build()
if err != nil {
fmt.Fprintf(os.Stderr, "Can't build logger: %v\n", err)
os.Exit(1)
}

regValue, err := sdk.GetRhRegion("https://api.stage.openshift.com", "ap-southeast-1")
if err != nil {
fmt.Fprintf(os.Stderr, "Can't find region: %v", err)
os.Exit(1)
}
token := os.Getenv("OCM_TOKEN")

// Build a regionalized connection based on the desired shard
connection, err := sdk.NewConnectionBuilder().
Client("ocm-cli", "").
Logger(logger).
Tokens(token).
URL(fmt.Sprintf("https://%s", regValue.URL)). // Apply the region URL
Insecure(false).
BuildContext(ctx)
if err != nil {
fmt.Fprintf(os.Stderr, "Can't build connection: %v\n", err)
os.Exit(1)
}
defer connection.Close()

collection := connection.AccountsMgmt().V1().CurrentAccount()

// Even though we've provided a regional url, the SDK should redirect to the global API for AccountMgmt
_, err = collection.Get().
SendContext(ctx)
if err != nil {
fmt.Fprintf(os.Stderr, "Can't retrieve current account : %s\n", err)
os.Exit(1)
}
}
5 changes: 4 additions & 1 deletion internal/client_selector.go
Original file line number Diff line number Diff line change
Expand Up @@ -323,7 +323,8 @@ func (s *ClientSelector) createTransport(ctx context.Context,
// Prepare the TLS configuration:
// #nosec 402
config := &tls.Config{
ServerName: address.Host,
// ServerName is not included to allow the tls library to set it based on the hostname
// provided in the request. This is necessary to support OCM region redirects.
InsecureSkipVerify: s.insecure,
RootCAs: s.trustedCAs,
}
Expand Down Expand Up @@ -351,6 +352,8 @@ func (s *ClientSelector) createTransport(ctx context.Context,
}
transport.DialTLSContext = func(ctx context.Context, _, _ string) (net.Conn,
error) {
// Append server name manually for TLS with sockets
config.ServerName = address.Host
dialer := tls.Dialer{
Config: config,
}
Expand Down
71 changes: 71 additions & 0 deletions internal/client_selector_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@ package internal

import (
"context"
"crypto/x509"
"fmt"
"net/http"
"net/http/httptest"
"strings"

. "github.com/onsi/ginkgo/v2/dsl/core" // nolint
. "github.com/onsi/gomega" // nolint
Expand Down Expand Up @@ -106,3 +111,69 @@ var _ = Describe("Select client", func() {
Expect(secondClient == firstClient).To(BeFalse())
})
})

var _ = Describe("Redirect Behavior", func() {
var (
ctx context.Context
selector *ClientSelector
originServer *httptest.Server
responseServer *httptest.Server
expectedResponseBody string
)

BeforeEach(func() {
var err error

// Create a context:
ctx = context.Background()

expectedResponseBody = "myServerDotComRedirect"

responseServer = httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
//nolint
fmt.Fprintf(w, expectedResponseBody)
}))

// simulate a redirect to a different domain by responding with a localhost url rather than a 127.0.0.1 url
redirectURL := strings.Replace(responseServer.URL, "127.0.0.1", "localhost", 1)
originServer = httptest.NewTLSServer(http.RedirectHandler(redirectURL, http.StatusMovedPermanently))

cas := x509.NewCertPool()
cas.AddCert(responseServer.Certificate())
cas.AddCert(originServer.Certificate())

// Create the selector:
selector, err = NewClientSelector().
TrustedCAs(cas).
Insecure(true). //need insecure when using "localhost" to connect or you get TLS verification errors
Logger(logger).
Build(ctx)
Expect(err).ToNot(HaveOccurred())
Expect(selector).ToNot(BeNil())
})

AfterEach(func() {
defer responseServer.Close()
defer originServer.Close()

// Close the selector:
err := selector.Close()
Expect(err).ToNot(HaveOccurred())
})

It("Doesn't re-use origin host for redirect", func() {
address, err := ParseServerAddress(ctx, originServer.URL)
Expect(err).ToNot(HaveOccurred())

client, err := selector.Select(ctx, address)
Expect(err).ToNot(HaveOccurred())

resp, err := client.Get(originServer.URL)
Expect(err).ToNot(HaveOccurred())
Expect(resp.TLS.ServerName).To(Equal("localhost"))

body := make([]byte, len(expectedResponseBody))
_, _ = resp.Body.Read(body)
Expect(string(body)).To(Equal("myServerDotComRedirect"))
})
})
Loading