Added basic client functionality

This commit is contained in:
Samuel Hawksby-Robinson 2022-05-03 15:50:40 +01:00
parent a4beca7f55
commit ddd990b645
3 changed files with 64 additions and 22 deletions

46
server/client.go Normal file
View File

@ -0,0 +1,46 @@
package server
import (
"crypto/tls"
"crypto/x509"
"fmt"
"net/http"
"net/url"
)
type Client struct {
*http.Client
baseAddress *url.URL
certPEM []byte
}
func NewClient(c *ConnectionParams) (*Client, error) {
u, certPem, err := c.Generate()
if err != nil {
return nil, err
}
rootCAs, err := x509.SystemCertPool()
if err != nil {
return nil, err
}
if ok := rootCAs.AppendCertsFromPEM(certPem); !ok {
return nil, fmt.Errorf("failed to append certPem to rootCAs")
}
tr := &http.Transport{
TLSClientConfig: &tls.Config{
MinVersion: tls.VersionTLS12,
InsecureSkipVerify: false, // MUST BE FALSE
RootCAs: rootCAs,
},
}
return &Client{
Client: &http.Client{Transport: tr},
baseAddress: u,
certPEM: certPem,
}, nil
}

View File

@ -182,6 +182,11 @@ func (cp *ConnectionParams) validateServerMode() error {
// Generate returns a *url.URL and encoded pem.Block generated from ConnectionParams set fields
func (cp *ConnectionParams) Generate() (*url.URL, []byte, error) {
err := cp.validate()
if err != nil {
return nil, nil, err
}
u := &url.URL{
Scheme: "https",
Host: fmt.Sprintf("%s:%d", cp.netIP, cp.port),

View File

@ -4,8 +4,6 @@ import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"encoding/hex"
"io/ioutil"
"net/http"
@ -29,6 +27,16 @@ func testHandler(t *testing.T) func(w http.ResponseWriter, r *http.Request) {
}
}
func makeThingToSay() (string, error) {
b := make([]byte, 32)
_, err := rand.Read(b)
if err != nil {
return "", err
}
return hex.EncodeToString(b), nil
}
func TestGetOutboundIPWithFullServerE2e(t *testing.T) {
// Get 3 key components for tls.cert generation
// 1) Ephemeral private key
@ -68,30 +76,13 @@ func TestGetOutboundIPWithFullServerE2e(t *testing.T) {
err = ccp.FromString(qr)
require.NoError(t, err)
u, certPem, err := ccp.Generate()
c, err := NewClient(ccp)
require.NoError(t, err)
rootCAs, err := x509.SystemCertPool()
thing, err := makeThingToSay()
require.NoError(t, err)
ok := rootCAs.AppendCertsFromPEM(certPem)
require.True(t, ok)
tr := &http.Transport{
TLSClientConfig: &tls.Config{
MinVersion: tls.VersionTLS12,
InsecureSkipVerify: false, // MUST BE FALSE, or the test is meaningless
RootCAs: rootCAs,
},
}
client := &http.Client{Transport: tr}
b := make([]byte, 32)
_, err = rand.Read(b)
require.NoError(t, err)
thing := hex.EncodeToString(b)
response, err := client.Get(u.String() + "/hello?say=" + thing)
response, err := c.Get(c.baseAddress.String() + "/hello?say=" + thing)
require.NoError(t, err)
defer response.Body.Close()