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

Add option UseTLS UseTLSWithCertificates #7

Merged
merged 1 commit into from
Feb 2, 2023
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
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
coverage.out
testdata/*.pem
testdata/*.srl
coverage.out
10 changes: 9 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,20 @@ default: test

ci: depsdev test

test:
test: cert
go test ./... -coverprofile=coverage.out -covermode=count

lint:
golangci-lint run ./...

cert:
mkdir -p testdata
rm -f testdata/*.pem testdata/*.srl
openssl req -x509 -newkey rsa:4096 -days 365 -nodes -sha256 -keyout testdata/cakey.pem -out testdata/cacert.pem -subj "/C=UK/ST=Test State/L=Test Location/O=Test Org/OU=Test Unit/CN=*.example.com/emailAddress=k1lowxb@gmail.com"
openssl req -newkey rsa:4096 -nodes -keyout testdata/key.pem -out testdata/csr.pem -subj "/C=JP/ST=Test State/L=Test Location/O=Test Org/OU=Test Unit/CN=*.example.com/emailAddress=k1lowxb@gmail.com"
openssl x509 -req -sha256 -in testdata/csr.pem -days 60 -CA testdata/cacert.pem -CAkey testdata/cakey.pem -CAcreateserial -out testdata/cert.pem -extfile testdata/openssl.cnf
openssl verify -CAfile testdata/cacert.pem testdata/cert.pem

depsdev:
go install github.com/Songmu/ghch/cmd/ghch@latest
go install github.com/Songmu/gocredits/cmd/gocredits@latest
Expand Down
82 changes: 62 additions & 20 deletions httpstub.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package httpstub

import (
"bytes"
"crypto/tls"
"crypto/x509"
"io"
"net/http"
"net/http/httptest"
Expand All @@ -16,12 +18,14 @@ import (
var _ http.Handler = (*Router)(nil)

type Router struct {
matchers []*matcher
server *httptest.Server
middlewares middlewareFuncs
requests []*http.Request
t *testing.T
mu sync.RWMutex
matchers []*matcher
server *httptest.Server
middlewares middlewareFuncs
requests []*http.Request
t *testing.T
useTLS bool
cacert, cert, key []byte
mu sync.RWMutex
}

type matcher struct {
Expand Down Expand Up @@ -73,23 +77,36 @@ func (rt *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}

// NewRouter returns a new router with methods for stubbing.
func NewRouter(t *testing.T) *Router {
func NewRouter(t *testing.T, opts ...Option) *Router {
t.Helper()
return &Router{t: t}
c := &config{}
for _, opt := range opts {
if err := opt(c); err != nil {
t.Fatal(err)
}
}
return &Router{
t: t,
useTLS: c.useTLS,
cacert: c.cacert,
cert: c.cert,
key: c.key,
}
}

// NewServer returns a new router including *httptest.Server.
func NewServer(t *testing.T) *Router {
func NewServer(t *testing.T, opts ...Option) *Router {
t.Helper()
rt := &Router{t: t}
rt := NewRouter(t, opts...)
_ = rt.Server()
return rt
}

// NewTLSServer returns a new router including TLS *httptest.Server.
func NewTLSServer(t *testing.T) *Router {
func NewTLSServer(t *testing.T, opts ...Option) *Router {
t.Helper()
rt := &Router{t: t}
rt := NewRouter(t, opts...)
rt.useTLS = true
_ = rt.TLSServer()
return rt
}
Expand All @@ -106,7 +123,37 @@ func (rt *Router) Client() *http.Client {
// Server returns *httptest.Server with *Router set.
func (rt *Router) Server() *httptest.Server {
if rt.server == nil {
rt.server = httptest.NewServer(rt)
if rt.useTLS {
rt.server = httptest.NewUnstartedServer(rt)
if len(rt.cert) > 0 && len(rt.key) > 0 {
cert, err := tls.X509KeyPair(rt.cert, rt.key)
if err != nil {
panic(err)
}
existingConfig := rt.server.TLS
if existingConfig != nil {
rt.server.TLS = existingConfig.Clone()
} else {
rt.server.TLS = new(tls.Config)
}
rt.server.TLS.Certificates = []tls.Certificate{cert}
}
rt.server.StartTLS()
if len(rt.cacert) > 0 {
certpool, err := x509.SystemCertPool()
if err != nil {
// for Windows
certpool = x509.NewCertPool()
}
if !certpool.AppendCertsFromPEM(rt.cacert) {
panic("failed to add cacert")
}
client := rt.server.Client()
client.Transport.(*http.Transport).TLSClientConfig.RootCAs = certpool
}
} else {
rt.server = httptest.NewServer(rt)
}
}
client := rt.server.Client()
tp := client.Transport.(*http.Transport)
Expand All @@ -116,13 +163,8 @@ func (rt *Router) Server() *httptest.Server {

// TLSServer returns TLS *httptest.Server with *Router set.
func (rt *Router) TLSServer() *httptest.Server {
if rt.server == nil {
rt.server = httptest.NewTLSServer(rt)
}
client := rt.server.Client()
tp := client.Transport.(*http.Transport)
client.Transport = newTransport(rt.server.URL, tp)
return rt.server
rt.useTLS = true
return rt.Server()
}

// Close shuts down *httptest.Server
Expand Down
56 changes: 56 additions & 0 deletions httpstub_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package httpstub
import (
"io"
"net/http"
"os"
"testing"
)

Expand Down Expand Up @@ -334,3 +335,58 @@ func TestTLSServer(t *testing.T) {
}
}
}

func TestUseTLSWithCertificates(t *testing.T) {
cacert, err := os.ReadFile("testdata/cacert.pem")
if err != nil {
t.Fatal(err)
}
cert, err := os.ReadFile("testdata/cert.pem")
if err != nil {
t.Fatal(err)
}
key, err := os.ReadFile("testdata/key.pem")
if err != nil {
t.Fatal(err)
}
r := NewRouter(t, UseTLSWithCertificates(cacert, cert, key))
r.Method(http.MethodGet).Path("/api/v1/users/1").Header("Content-Type", "application/json").ResponseString(http.StatusOK, `{"name":"alice"}`)
ts := r.Server()
t.Cleanup(func() {
ts.Close()
})
tc := ts.Client()
res, err := tc.Get("http://example.com/api/v1/users/1")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
res.Body.Close()
})
body, err := io.ReadAll(res.Body)
if err != nil {
t.Fatal(err)
}

{
got := res.StatusCode
want := http.StatusOK
if got != want {
t.Errorf("got %v\nwant %v", got, want)
}
}
{
got := res.Header.Get("Content-Type")
want := "application/json"
if got != want {
t.Errorf("got %v\nwant %v", got, want)
}
}
{
got := string(body)
want := `{"name":"alice"}`
if got != want {
t.Errorf("got %v\nwant %v", got, want)
}
}
}
25 changes: 25 additions & 0 deletions option.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package httpstub

type config struct {
useTLS bool
cacert, cert, key []byte
}

type Option func(*config) error

func UseTLS() Option {
return func(c *config) error {
c.useTLS = true
return nil
}
}

func UseTLSWithCertificates(cacert, cert, key []byte) Option {
return func(c *config) error {
c.useTLS = true
c.cacert = cacert
c.cert = cert
c.key = key
return nil
}
}
1 change: 1 addition & 0 deletions testdata/openssl.cnf
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
subjectAltName=DNS:*.example.com,IP:0.0.0.0,IP:127.0.0.1