go-http-peering/server/middleware.go

238 lines
5.9 KiB
Go
Raw Permalink Normal View History

2019-02-03 20:56:58 +01:00
package server
import (
"bytes"
"context"
2019-02-22 17:35:49 +01:00
"crypto/rsa"
2019-02-03 20:56:58 +01:00
"crypto/sha256"
"errors"
2019-02-22 17:35:49 +01:00
"io"
2019-02-03 20:56:58 +01:00
"io/ioutil"
"net/http"
2019-02-03 20:56:58 +01:00
"time"
peeringCrypto "forge.cadoles.com/Cadoles/go-http-peering/crypto"
2019-02-03 20:56:58 +01:00
peering "forge.cadoles.com/Cadoles/go-http-peering"
2019-02-03 20:56:58 +01:00
jwt "github.com/dgrijalva/jwt-go"
)
const (
2019-02-22 17:35:49 +01:00
ServerTokenHeader = "X-Server-Token" // nolint: gosec
ClientTokenHeader = "X-Client-Token"
KeyPeerID ContextKey = "PeerID"
2019-02-03 20:56:58 +01:00
)
var (
ErrInvalidClaims = errors.New("invalid claims")
ErrInvalidChecksum = errors.New("invalid checksum")
ErrNotPeered = errors.New("not peered")
)
type ContextKey string
2019-02-22 17:35:49 +01:00
func Authenticate(store peering.Store, key *rsa.PublicKey, funcs ...OptionFunc) func(http.Handler) http.Handler {
2019-02-03 20:56:58 +01:00
options := createOptions(funcs...)
logger := options.Logger
middleware := func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
2019-02-22 17:35:49 +01:00
serverToken := r.Header.Get(ServerTokenHeader)
if serverToken == "" {
2019-02-03 20:56:58 +01:00
sendError(w, http.StatusUnauthorized)
return
}
2019-02-22 17:35:49 +01:00
clientToken := r.Header.Get(ClientTokenHeader)
if clientToken == "" {
2019-02-03 20:56:58 +01:00
sendError(w, http.StatusUnauthorized)
return
}
2019-02-22 17:35:49 +01:00
serverClaims, err := assertServerToken(key, serverToken)
if err != nil {
2019-02-03 20:56:58 +01:00
logger.Printf("[ERROR] %s", err)
sendError(w, http.StatusUnauthorized)
return
}
clientClaims, err := assertClientToken(
serverClaims.PeerID,
store,
clientToken,
logger,
options.IgnoredClientTokenErrors...,
)
2019-02-03 20:56:58 +01:00
if err != nil {
logger.Printf("[ERROR] %s", err)
switch err {
case peering.ErrPeerNotFound:
2019-02-22 17:35:49 +01:00
sendError(w, http.StatusUnauthorized)
case ErrNotPeered:
if err := store.UpdateLastContact(serverClaims.PeerID, r.RemoteAddr, time.Now()); err != nil {
logger.Printf("[ERROR] %s", err)
sendError(w, http.StatusInternalServerError)
return
}
sendError(w, http.StatusUnauthorized)
return
2019-04-07 15:56:04 +02:00
case ErrPeerRejected:
if err := store.UpdateLastContact(serverClaims.PeerID, r.RemoteAddr, time.Now()); err != nil {
logger.Printf("[ERROR] %s", err)
sendError(w, http.StatusInternalServerError)
return
}
sendError(w, http.StatusForbidden)
return
default:
2019-02-22 17:35:49 +01:00
sendError(w, http.StatusInternalServerError)
return
2019-02-22 17:35:49 +01:00
}
2019-02-03 20:56:58 +01:00
}
2019-02-22 17:35:49 +01:00
match, body, err := assertBodySum(r.Body, clientClaims.BodySum)
2019-02-03 20:56:58 +01:00
if err != nil {
logger.Printf("[ERROR] %s", err)
2019-02-22 17:35:49 +01:00
sendError(w, http.StatusInternalServerError)
2019-02-03 20:56:58 +01:00
return
}
if !match {
logger.Printf("[ERROR] %s", ErrInvalidChecksum)
sendError(w, http.StatusBadRequest)
return
}
2019-02-22 17:35:49 +01:00
if err := store.UpdateLastContact(serverClaims.PeerID, r.RemoteAddr, time.Now()); err != nil {
2019-02-03 20:56:58 +01:00
logger.Printf("[ERROR] %s", err)
sendError(w, http.StatusInternalServerError)
return
}
2019-02-22 17:35:49 +01:00
ctx := context.WithValue(r.Context(), KeyPeerID, serverClaims.PeerID)
2019-02-03 20:56:58 +01:00
r = r.WithContext(ctx)
r.Body = ioutil.NopCloser(bytes.NewBuffer(body))
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
return middleware
}
func GetPeerID(r *http.Request) (peering.PeerID, error) {
peerID, ok := r.Context().Value(KeyPeerID).(peering.PeerID)
if !ok {
return "", ErrUnauthorized
}
return peerID, nil
}
2019-02-22 17:35:49 +01:00
func assertServerToken(key *rsa.PublicKey, serverToken string) (*peering.ServerTokenClaims, error) {
fn := func(token *jwt.Token) (interface{}, error) {
return key, nil
}
token, err := jwt.ParseWithClaims(serverToken, &peering.ServerTokenClaims{}, fn)
if err != nil {
2019-03-29 16:44:09 +01:00
validationError, ok := err.(*jwt.ValidationError)
if ok {
return nil, validationError.Inner
}
2019-02-22 17:35:49 +01:00
return nil, err
}
if !token.Valid {
return nil, ErrInvalidClaims
}
claims, ok := token.Claims.(*peering.ServerTokenClaims)
if !ok {
return nil, ErrInvalidClaims
}
return claims, nil
}
func assertClientToken(peerID peering.PeerID, store peering.Store, clientToken string, logger Logger, ignoredValidationErrors ...uint32) (*peering.ClientTokenClaims, error) {
2019-02-22 17:35:49 +01:00
fn := func(token *jwt.Token) (interface{}, error) {
peer, err := store.Get(peerID)
if err != nil {
return nil, err
}
if peer.Status == peering.StatusRejected {
return nil, ErrPeerRejected
}
if peer.Status != peering.StatusPeered {
return nil, ErrNotPeered
}
publicKey, err := peeringCrypto.DecodePEMToPublicKey(peer.PublicKey)
if err != nil {
return nil, err
}
return publicKey, nil
}
getPeeringClaims := func(token *jwt.Token) (*peering.ClientTokenClaims, error) {
claims, ok := token.Claims.(*peering.ClientTokenClaims)
if !ok {
return nil, ErrInvalidClaims
}
return claims, nil
}
2019-02-22 17:35:49 +01:00
token, err := jwt.ParseWithClaims(clientToken, &peering.ClientTokenClaims{}, fn)
if err != nil {
2019-03-29 16:44:09 +01:00
validationError, ok := err.(*jwt.ValidationError)
if ok {
for _, c := range ignoredValidationErrors {
if validationError.Errors&c != 0 {
logger.Printf("ignoring token validation error: '%s'", validationError.Inner)
return getPeeringClaims(token)
}
}
2019-03-29 16:44:09 +01:00
return nil, validationError.Inner
}
2019-02-22 17:35:49 +01:00
return nil, err
}
2019-02-22 17:35:49 +01:00
if !token.Valid {
return nil, ErrInvalidClaims
}
return getPeeringClaims(token)
2019-02-22 17:35:49 +01:00
}
func assertBodySum(rc io.ReadCloser, bodySum []byte) (bool, []byte, error) {
body, err := ioutil.ReadAll(rc)
if err != nil {
return false, nil, err
}
if err := rc.Close(); err != nil {
return false, nil, err
}
match, err := compareChecksum(body, bodySum)
if err != nil {
return false, nil, err
}
return match, body, nil
}
2019-02-03 20:56:58 +01:00
func sendError(w http.ResponseWriter, status int) {
http.Error(w, http.StatusText(status), status)
}
func filterIgnoredValidationError(err *jwt.ValidationError, ignored ...uint32) error {
for _, c := range ignored {
if err.Errors&c != 0 {
return nil
}
}
return err
}
2019-02-03 20:56:58 +01:00
func compareChecksum(body []byte, sum []byte) (bool, error) {
sha := sha256.New()
_, err := sha.Write(body)
if err != nil {
return false, err
}
return bytes.Equal(sum, sha.Sum(nil)), nil
}