/*
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 handlers

import (
	"context"
	"crypto/tls"
	"crypto/x509"
	"database/sql"
	"log"
	"net/http"
	"net/http/httptest"
	"os"
	"path"
	"testing"

	"github.com/jmoiron/sqlx"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"

	"git.cacert.org/cacert-boardvoting/internal"
	"git.cacert.org/cacert-boardvoting/internal/models"
)

func prepareTestDb(t *testing.T) *sqlx.DB {
	t.Helper()

	testDir := t.TempDir()

	db, err := sql.Open("sqlite3", path.Join(testDir, "test.sqlite"))
	require.NoError(t, err)

	dbx := sqlx.NewDb(db, "sqlite3")

	return dbx
}

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() //nolint:bodyclose // linters bug

	defer func() { _ = rs.Body.Close() }()

	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_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.Create(
		context.Background(),
		&models.CreateUserParams{
			Admin: &models.User{
				Name:     "Admin",
				Reminder: sql.NullString{String: "admin@example.org", Valid: true},
			},
			Name:      "Test User",
			Reminder:  "test@example.org",
			Emails:    []string{"test@example.org"},
			Reasoning: "Test data",
		},
	)

	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)

	mw := UserMiddleware{
		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)

		mw.TryAuthenticate(next).ServeHTTP(rr, r)

		rs := rr.Result() //nolint:bodyclose // linters bug

		defer func() { _ = rs.Body.Close() }()

		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{}}

		mw.TryAuthenticate(next).ServeHTTP(rr, r)

		rs := rr.Result() //nolint:bodyclose // linters bug

		defer func() { _ = rs.Body.Close() }()

		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"},
			ExtKeyUsage:    []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
		}}}

		mw.TryAuthenticate(next).ServeHTTP(rr, r)

		rs := rr.Result() //nolint:bodyclose // linters bug

		defer func() { _ = rs.Body.Close() }()

		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")
	})
}
