cacert-boardvoting/cmd/boardvoting/middleware_test.go
Jan Dittberner 335ce16547 Add tests for handlers and middleware
- drop migration 2022052601_drop_unused_decisions_colums because it was implicitly part of an earlier migration
- add /health endpoint for database health check
- add tests for the health check endpoint
- add tests for middleware secureHeaders, logRequest and tryAuthenticate
- add models.UserModel.CreateUser method
2022-05-26 19:22:56 +02:00

169 lines
4.1 KiB
Go

/*
Copyright 2022 CAcert Inc.
SPDX-License-Identifier: Apache-2.0
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 (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"log"
"net/http"
"net/http/httptest"
"os"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"git.cacert.org/cacert-boardvoting/internal"
"git.cacert.org/cacert-boardvoting/internal/models"
)
func Test_secureHeaders(t *testing.T) {
rr := httptest.NewRecorder()
r, err := http.NewRequest(http.MethodGet, "/", nil)
require.NoError(t, err)
next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte("OK"))
})
secureHeaders(next).ServeHTTP(rr, r)
rs := rr.Result()
assert.Equal(t, "default-src 'self'; font-src 'self' data:", rs.Header.Get("Content-Security-Policy"))
assert.Equal(t, "origin-when-cross-origin", rs.Header.Get("Referrer-Policy"))
assert.Equal(t, "nosniff", rs.Header.Get("X-Content-Type-Options"))
assert.Equal(t, "deny", rs.Header.Get("X-Frame-Options"))
assert.Equal(t, "0", rs.Header.Get("X-XSS-Protection"))
assert.Equal(t, "max-age=63072000", rs.Header.Get("Strict-Transport-Security"))
}
func TestApplication_logRequest(t *testing.T) {
rr := httptest.NewRecorder()
r, err := http.NewRequest(http.MethodGet, "/", nil)
require.NoError(t, err)
r.RemoteAddr = "arg"
next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte("OK"))
})
buf := new(bytes.Buffer)
app := &application{infoLog: log.New(buf, "", log.LstdFlags)}
app.logRequest(next).ServeHTTP(rr, r)
rs := rr.Result()
assert.Equal(t, http.StatusOK, rs.StatusCode)
assert.Contains(t, buf.String(), fmt.Sprintf(
"%s - %s %s %s",
r.RemoteAddr,
r.Proto,
r.Method,
r.URL.RequestURI(),
))
}
func TestApplication_tryAuthenticate(t *testing.T) {
db := prepareTestDb(t)
err := internal.InitializeDb(db.DB, log.New(os.Stdout, "", log.LstdFlags))
require.NoError(t, err)
users := &models.UserModel{DB: db}
_, err = users.CreateUser(
context.Background(),
"Test User",
"test@example.org",
[]string{"test@example.org"},
)
var nextCtx context.Context
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("OK"))
nextCtx = r.Context()
})
require.NoError(t, err)
app := application{
users: &models.UserModel{DB: db},
}
t.Run("without TLS", func(t *testing.T) {
rr := httptest.NewRecorder()
r, err := http.NewRequest(http.MethodGet, "/", nil)
require.NoError(t, err)
app.tryAuthenticate(next).ServeHTTP(rr, r)
rs := rr.Result()
assert.Equal(t, http.StatusOK, rs.StatusCode)
assert.Nil(t, nextCtx.Value(ctxUser))
})
t.Run("with TLS no certificate", func(t *testing.T) {
rr := httptest.NewRecorder()
r, err := http.NewRequest(http.MethodGet, "/", nil)
require.NoError(t, err)
r.TLS = &tls.ConnectionState{PeerCertificates: []*x509.Certificate{}}
app.tryAuthenticate(next).ServeHTTP(rr, r)
rs := rr.Result()
assert.Equal(t, http.StatusOK, rs.StatusCode)
assert.Nil(t, nextCtx.Value(ctxUser))
})
t.Run("with TLS matching user", func(t *testing.T) {
rr := httptest.NewRecorder()
r, err := http.NewRequest(http.MethodGet, "/", nil)
require.NoError(t, err)
r.TLS = &tls.ConnectionState{PeerCertificates: []*x509.Certificate{{EmailAddresses: []string{"test@example.org"}}}}
app.tryAuthenticate(next).ServeHTTP(rr, r)
rs := rr.Result()
assert.Equal(t, http.StatusOK, rs.StatusCode)
user := nextCtx.Value(ctxUser)
assert.NotNil(t, user)
userInstance, ok := user.(*models.User)
assert.True(t, ok)
assert.Equal(t, userInstance.Name, "Test User")
})
}