cacert-boardvoting/cmd/boardvoting/middleware.go
Jan Dittberner c3d0733e27 Replace gorilla/csrf with justinas/nosurf
- replace dependency for less indirect dependencies
- remove unused configuration options
2022-05-26 17:25:25 +02:00

188 lines
4.3 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 (
"context"
"errors"
"fmt"
"net/http"
"strings"
"github.com/justinas/nosurf"
"git.cacert.org/cacert-boardvoting/internal/models"
)
type contextKey int
const (
ctxUser contextKey = iota
)
func secureHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Security-Policy", "default-src 'self'; font-src 'self' data:")
w.Header().Set("Referrer-Policy", "origin-when-cross-origin")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("X-Frame-Options", "deny")
w.Header().Set("X-XSS-Protection", "0")
w.Header().Set("Strict-Transport-Security", "max-age=63072000")
next.ServeHTTP(w, r)
})
}
func (app *application) logRequest(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
app.infoLog.Printf("%s - %s %s %s", r.RemoteAddr, r.Proto, r.Method, r.URL.RequestURI())
next.ServeHTTP(w, r)
})
}
func (app *application) authenticateRequest(r *http.Request) (*models.User, error) {
if r.TLS == nil {
return nil, nil
}
if len(r.TLS.PeerCertificates) < 1 {
return nil, nil
}
emails := r.TLS.PeerCertificates[0].EmailAddresses
user, err := app.users.GetUser(r.Context(), emails)
if err != nil {
return nil, fmt.Errorf("could not get user information from database: %w", err)
}
return user, nil
}
func (app *application) tryAuthenticate(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user, err := app.authenticateRequest(r)
if err != nil {
app.serverError(w, err)
return
}
if user == nil {
next.ServeHTTP(w, r)
return
}
w.Header().Add("Cache-Control", "no-store")
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxUser, user)))
})
}
func (app *application) GetUser(r *http.Request) (*models.User, error) {
user := r.Context().Value(ctxUser)
if user == nil {
return nil, errors.New("no user in context")
}
result, ok := user.(*models.User)
if !ok {
return nil, fmt.Errorf("%v is not a user", user)
}
return result, nil
}
func (app *application) HasRole(r *http.Request, roles []string) (bool, bool, error) {
user, err := app.GetUser(r)
if err != nil {
return false, false, err
}
if user == nil {
return false, false, nil
}
roleMatched, err := user.HasRole(roles)
if err != nil {
return false, true, fmt.Errorf("could not determin user role assignment: %w", err)
}
if !roleMatched {
app.errorLog.Printf(
"user %s does not have any of the required role(s) %s assigned",
user.Name,
strings.Join(roles, ", "),
)
return false, true, nil
}
return true, true, nil
}
func (app *application) requireRole(next http.Handler, roles []string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hasRole, hasUser, err := app.HasRole(r, roles)
if err != nil {
app.serverError(w, err)
return
}
if !hasUser {
app.clientError(w, http.StatusUnauthorized)
return
}
if !hasRole {
app.clientError(w, http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}
func (app *application) userCanVote(next http.Handler) http.Handler {
return app.requireRole(next, []string{models.RoleVoter})
}
func (app *application) userCanEditVote(next http.Handler) http.Handler {
return app.requireRole(next, []string{models.RoleVoter})
}
func (app *application) userCanChangeVoters(next http.Handler) http.Handler {
return app.requireRole(next, []string{models.RoleSecretary, models.RoleAdmin})
}
func noSurf(next http.Handler) http.Handler {
csrfHandler := nosurf.New(next)
csrfHandler.SetBaseCookie(http.Cookie{
HttpOnly: true,
Path: "/",
Secure: true,
SameSite: http.SameSiteStrictMode,
})
return csrfHandler
}