Skip to content

Commit

Permalink
add unit tests for tls
Browse files Browse the repository at this point in the history
  • Loading branch information
fredcarle committed Oct 12, 2022
1 parent 2180acd commit 7fdc164
Show file tree
Hide file tree
Showing 3 changed files with 203 additions and 0 deletions.
3 changes: 3 additions & 0 deletions api/http/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,9 @@ func newHandler(db client.DB, opts serverOptions) *handler {

func (h *handler) handle(f http.HandlerFunc) http.HandlerFunc {
return func(rw http.ResponseWriter, req *http.Request) {
if h.options.tls {
rw.Header().Add("Strict-Transport-Security", "max-age=63072000; includeSubDomains")
}
ctx := context.WithValue(req.Context(), ctxDB{}, h.db)
if h.options.peerID != "" {
ctx = context.WithValue(ctx, ctxPeerID{}, h.options.peerID)
Expand Down
42 changes: 42 additions & 0 deletions api/http/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -268,3 +268,45 @@ func TestCORSRequest(t *testing.T) {
})
}
}

func TestTLSRequestResponseHeader(t *testing.T) {
cases := []struct {
name string
method string
reqHeaders map[string]string
resHeaders map[string]string
}{
{
"TLSHeader",
"GET",
map[string]string{},
map[string]string{
"Strict-Transport-Security": "max-age=63072000; includeSubDomains",
},
},
}
dir := t.TempDir()

s := NewServer(nil, WithAddress("example.com"), WithRootDir(dir))

for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
req, err := http.NewRequest(c.method, PingPath, nil)
if err != nil {
t.Fatal(err)
}

for header, value := range c.reqHeaders {
req.Header.Add(header, value)
}

rec := httptest.NewRecorder()

s.Handler.ServeHTTP(rec, req)

for header, value := range c.resHeaders {
assert.Equal(t, value, rec.Result().Header.Get(header))
}
})
}
}
158 changes: 158 additions & 0 deletions api/http/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,11 @@ package http
import (
"context"
"net/http"
"os"
"testing"

"github.com/stretchr/testify/assert"
"golang.org/x/crypto/acme/autocert"
)

func TestNewServerAndRunWithoutListener(t *testing.T) {
Expand Down Expand Up @@ -55,6 +57,132 @@ func TestNewServerAndRunWithListenerAndValidPort(t *testing.T) {
<-serverDone
}

func TestNewServerAndRunWithAutocert(t *testing.T) {
ctx := context.Background()
serverRunning := make(chan struct{})
serverDone := make(chan struct{})
dir := t.TempDir()
s := NewServer(nil, WithAddress("example.com"), WithRootDir(dir))
go func() {
close(serverRunning)
err := s.Listen(ctx)
assert.NoError(t, err)
err = s.Run(ctx)
assert.ErrorIs(t, http.ErrServerClosed, err)
defer close(serverDone)
}()

<-serverRunning

s.Shutdown(context.Background())

<-serverDone
}

func TestNewServerAndRunWithSelfSignedCertAndNoKeyFiles(t *testing.T) {
ctx := context.Background()
serverRunning := make(chan struct{})
serverDone := make(chan struct{})
dir := t.TempDir()
s := NewServer(nil, WithAddress("localhost:9181"), WithSelfSignedCert(dir+"/server.crt", dir+"/server.key"))
go func() {
close(serverRunning)
err := s.Listen(ctx)
assert.Contains(t, err.Error(), "no such file or directory")
defer close(serverDone)
}()

<-serverRunning

s.Shutdown(context.Background())

<-serverDone
}

const pubKey = `-----BEGIN EC PARAMETERS-----
BgUrgQQAIg==
-----END EC PARAMETERS-----
-----BEGIN EC PRIVATE KEY-----
MIGkAgEBBDD4VK0DRBRaeieXU9JaPJfSeegGYcXaX5+gEcwGKA0UJYI46QRHIlHC
IJMOjPsrUCmgBwYFK4EEACKhZANiAAQ3ltsFK8bZZpOYiJnvwpa7Ft+b0KFsDqpu
pS0gW/SYpAncHhRuz18RQ2ycuXlSN1S/PAryRZ5PK2xORKfwpguEDEMdVwbHorZO
K44P/h3dhyNyAyf8rcRoqKXcl/K/uew=
-----END EC PRIVATE KEY-----`

const privKey = `-----BEGIN CERTIFICATE-----
MIICQDCCAcUCCQDpMnN1gQ4fGTAKBggqhkjOPQQDAjCBiDELMAkGA1UEBhMCY2Ex
DzANBgNVBAgMBlF1ZWJlYzEQMA4GA1UEBwwHQ2hlbHNlYTEPMA0GA1UECgwGU291
cmNlMRAwDgYDVQQLDAdEZWZyYURCMQ8wDQYDVQQDDAZzb3VyY2UxIjAgBgkqhkiG
9w0BCQEWE2V4YW1wbGVAZXhhbXBsZS5jb20wHhcNMjIxMDA2MTgyMjE1WhcNMjMx
MDA2MTgyMjE1WjCBiDELMAkGA1UEBhMCY2ExDzANBgNVBAgMBlF1ZWJlYzEQMA4G
A1UEBwwHQ2hlbHNlYTEPMA0GA1UECgwGU291cmNlMRAwDgYDVQQLDAdEZWZyYURC
MQ8wDQYDVQQDDAZzb3VyY2UxIjAgBgkqhkiG9w0BCQEWE2V4YW1wbGVAZXhhbXBs
ZS5jb20wdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAQ3ltsFK8bZZpOYiJnvwpa7Ft+b
0KFsDqpupS0gW/SYpAncHhRuz18RQ2ycuXlSN1S/PAryRZ5PK2xORKfwpguEDEMd
VwbHorZOK44P/h3dhyNyAyf8rcRoqKXcl/K/uewwCgYIKoZIzj0EAwIDaQAwZgIx
AIfNQeo8syOb94ojF40jY+fY1ZBSbNNK6UUbFquwDMVEoSyXRJHHEU12NUKCVTUH
kgIxAKaEGC+lqp0aaN+yubYLRiTDxOlNpyiHox3nZiL4bG/CCdPDvbX63QcdI2yq
XPKczg==
-----END CERTIFICATE-----`

func TestNewServerAndRunWithSelfSignedCertAndInvalidPort(t *testing.T) {
ctx := context.Background()
serverRunning := make(chan struct{})
serverDone := make(chan struct{})
dir := t.TempDir()
err := os.WriteFile(dir+"/server.key", []byte(privKey), 0644)
if err != nil {
t.Fatal(err)
}
err = os.WriteFile(dir+"/server.crt", []byte(pubKey), 0644)
if err != nil {
t.Fatal(err)
}
s := NewServer(nil, WithAddress(":303000"), WithSelfSignedCert(dir+"/server.crt", dir+"/server.key"))
go func() {
close(serverRunning)
err := s.Listen(ctx)
assert.Contains(t, err.Error(), "invalid port")
defer close(serverDone)
}()

<-serverRunning

s.Shutdown(context.Background())

<-serverDone
}

func TestNewServerAndRunWithSelfSignedCert(t *testing.T) {
ctx := context.Background()
serverRunning := make(chan struct{})
serverDone := make(chan struct{})
dir := t.TempDir()
err := os.WriteFile(dir+"/server.key", []byte(privKey), 0644)
if err != nil {
t.Fatal(err)
}
err = os.WriteFile(dir+"/server.crt", []byte(pubKey), 0644)
if err != nil {
t.Fatal(err)
}
s := NewServer(nil, WithAddress("localhost:9181"), WithSelfSignedCert(dir+"/server.crt", dir+"/server.key"))
go func() {
close(serverRunning)
err := s.Listen(ctx)
assert.NoError(t, err)
err = s.Run(ctx)
assert.ErrorIs(t, http.ErrServerClosed, err)
defer close(serverDone)
}()

<-serverRunning

s.Shutdown(context.Background())

<-serverDone
}

func TestNewServerWithoutOptions(t *testing.T) {
s := NewServer(nil)
assert.Equal(t, "localhost:9181", s.Addr)
Expand All @@ -66,12 +194,42 @@ func TestNewServerWithAddress(t *testing.T) {
assert.Equal(t, "localhost:9999", s.Addr)
}

func TestNewServerWithDomainAddress(t *testing.T) {
s := NewServer(nil, WithAddress("example.com"))
assert.Equal(t, "example.com", s.options.domain)
assert.Equal(t, true, s.options.tls)
}

func TestNewServerWithAllowedOrigins(t *testing.T) {
s := NewServer(nil, WithAllowedOrigins("https://source.network", "https://app.source.network"))
assert.Equal(t, []string{"https://source.network", "https://app.source.network"}, s.options.allowedOrigins)
}

func TestNewServerWithCAEmail(t *testing.T) {
s := NewServer(nil, WithCAEmail("[email protected]"))
assert.Equal(t, "[email protected]", s.options.email)
}

func TestNewServerWithPeerID(t *testing.T) {
s := NewServer(nil, WithPeerID("12D3KooWFpi6VTYKLtxUftJKEyfX8jDfKi8n15eaygH8ggfYFZbR"))
assert.Equal(t, "12D3KooWFpi6VTYKLtxUftJKEyfX8jDfKi8n15eaygH8ggfYFZbR", s.options.peerID)
}

func TestNewServerWithRootDir(t *testing.T) {
dir := t.TempDir()
s := NewServer(nil, WithRootDir(dir))
assert.Equal(t, dir, s.options.rootDir)
}

func TestNewServerWithSelfSignedCert(t *testing.T) {
s := NewServer(nil, WithSelfSignedCert("pub.key", "priv.key"))
assert.Equal(t, "pub.key", s.options.pubKey)
assert.Equal(t, "priv.key", s.options.privKey)
assert.Equal(t, true, s.options.tls)
}

func TestNewHTTPRedirServer(t *testing.T) {
m := &autocert.Manager{}
s := newHTTPRedirServer(m)
assert.Equal(t, ":80", s.Addr)
}

0 comments on commit 7fdc164

Please sign in to comment.