| 1 |
/* |
| 2 |
Copyright 2022 The Kubernetes Authors. |
| 3 |
|
| 4 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
you may not use this file except in compliance with the License. |
| 6 |
You may obtain a copy of the License at |
| 7 |
|
| 8 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
|
| 10 |
Unless required by applicable law or agreed to in writing, software |
| 11 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
See the License for the specific language governing permissions and |
| 14 |
limitations under the License. |
| 15 |
*/ |
| 16 |
|
| 17 |
package tests |
| 18 |
|
| 19 |
import ( |
| 20 |
"context" |
| 21 |
"crypto/tls" |
| 22 |
"encoding/pem" |
| 23 |
"net/http" |
| 24 |
"net/http/httptest" |
| 25 |
"os" |
| 26 |
"strings" |
| 27 |
"sync/atomic" |
| 28 |
"testing" |
| 29 |
|
| 30 |
"google.golang.org/grpc" |
| 31 |
"google.golang.org/grpc/credentials" |
| 32 |
"sigs.k8s.io/apiserver-network-proxy/konnectivity-client/proto/client" |
| 33 |
"sigs.k8s.io/apiserver-network-proxy/pkg/util" |
| 34 |
) |
| 35 |
|
| 36 |
func TestCustomALPN(t *testing.T) { |
| 37 |
const proto = "test-proto" |
| 38 |
protoUsed := int32(0) |
| 39 |
|
| 40 |
svr := httptest.NewUnstartedServer(http.DefaultServeMux) |
| 41 |
svr.TLS = &tls.Config{NextProtos: []string{proto}, MinVersion: tls.VersionTLS13} |
| 42 |
svr.Config.TLSNextProto = map[string]func(*http.Server, *tls.Conn, http.Handler){ |
| 43 |
proto: func(*http.Server, *tls.Conn, http.Handler) { |
| 44 |
atomic.AddInt32(&protoUsed, 1) |
| 45 |
}, |
| 46 |
} |
| 47 |
svr.StartTLS() |
| 48 |
|
| 49 |
ca, err := os.CreateTemp("", "") |
| 50 |
if err != nil { |
| 51 |
t.Fatal(err) |
| 52 |
} |
| 53 |
defer ca.Close() |
| 54 |
defer os.Remove(ca.Name()) |
| 55 |
|
| 56 |
err = pem.Encode(ca, &pem.Block{ |
| 57 |
Type: "CERTIFICATE", |
| 58 |
Bytes: svr.TLS.Certificates[0].Certificate[0], |
| 59 |
}) |
| 60 |
if err != nil { |
| 61 |
t.Fatal(err) |
| 62 |
} |
| 63 |
ca.Close() |
| 64 |
|
| 65 |
tlsConfig, err := util.GetClientTLSConfig(ca.Name(), "", "", "", []string{proto}) |
| 66 |
if err != nil { |
| 67 |
t.Fatal(err) |
| 68 |
} |
| 69 |
|
| 70 |
addr := strings.TrimPrefix(svr.URL, "https://") |
| 71 |
conn, err := grpc.Dial(addr, grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig))) |
| 72 |
if err != nil { |
| 73 |
t.Fatal(err) |
| 74 |
} |
| 75 |
grpcClient := client.NewProxyServiceClient(conn) |
| 76 |
|
| 77 |
grpcClient.Proxy(context.Background()) |
| 78 |
if atomic.LoadInt32(&protoUsed) != 1 { |
| 79 |
t.Error("expected custom ALPN protocol to have been used") |
| 80 |
} |
| 81 |
} |