Compare commits

..

1 Commits

Author SHA1 Message Date
wpetit 958652ddba feat: sign released binaries
Cadoles/go-http-peering/pipeline/head This commit is unstable Details
2023-10-19 15:15:36 +02:00
12 changed files with 88 additions and 199 deletions

View File

@ -1,2 +1,3 @@
GPG_SIGNING_KEY= GPG_SIGNING_KEY=
ARCH_TARGETS='amd64 arm arm64 386' GPG_SIGNING_PASSPHRASE=
ARCH_TARGETS='amd64 arm arm64'

View File

@ -1,8 +1,6 @@
SHELL := /bin/bash SHELL := /bin/bash
test: go-test keygen-test test:
go-test:
go clean -testcache go clean -testcache
go test -cover -v ./... go test -cover -v ./...
@ -38,13 +36,6 @@ gitea-release: .mktools tools/gitea-release/bin/gitea-release.sh release
GITEA_RELEASE_ATTACHMENTS="$$(find release -type f -name '*.tar.gz')" \ GITEA_RELEASE_ATTACHMENTS="$$(find release -type f -name '*.tar.gz')" \
tools/gitea-release/bin/gitea-release.sh tools/gitea-release/bin/gitea-release.sh
keygen-test: tools/bash_unit/bin/bash_unit
tools/bash_unit/bin/bash_unit misc/bash_unit/keygen_test.sh
tools/bash_unit/bin/bash_unit:
mkdir -p tools/bash_unit/bin
cd tools/bash_unit/bin && bash <(curl -s https://raw.githubusercontent.com/pgrange/bash_unit/master/install.sh)
.PHONY: mktools .PHONY: mktools
mktools: mktools:
rm -rf .mktools rm -rf .mktools

View File

@ -5,11 +5,11 @@ import (
"crypto/rsa" "crypto/rsa"
"crypto/sha256" "crypto/sha256"
"encoding/json" "encoding/json"
"errors"
"net/http" "net/http"
"time" "time"
jwt "github.com/dgrijalva/jwt-go" jwt "github.com/dgrijalva/jwt-go"
"github.com/pkg/errors"
peering "forge.cadoles.com/Cadoles/go-http-peering" peering "forge.cadoles.com/Cadoles/go-http-peering"
"forge.cadoles.com/Cadoles/go-http-peering/crypto" "forge.cadoles.com/Cadoles/go-http-peering/crypto"
@ -52,7 +52,7 @@ func (c *Client) Advertise(attrs peering.PeerAttributes) error {
case http.StatusConflict: case http.StatusConflict:
return peering.ErrPeerExists return peering.ErrPeerExists
default: default:
return errors.Wrapf(ErrUnexpectedResponse, "unexpected http status code '%d'", res.StatusCode) return ErrUnexpectedResponse
} }
} }
@ -76,7 +76,7 @@ func (c *Client) UpdateAttributes(attrs peering.PeerAttributes) error {
case http.StatusForbidden: case http.StatusForbidden:
return ErrRejected return ErrRejected
default: default:
return errors.Wrapf(ErrUnexpectedResponse, "unexpected http status code '%d'", res.StatusCode) return ErrUnexpectedResponse
} }
} }
@ -96,7 +96,7 @@ func (c *Client) Ping() error {
case http.StatusForbidden: case http.StatusForbidden:
return ErrRejected return ErrRejected
default: default:
return errors.Wrapf(ErrUnexpectedResponse, "unexpected http status code '%d'", res.StatusCode) return ErrUnexpectedResponse
} }
} }

View File

@ -11,10 +11,8 @@ var (
createKeyCmd = false createKeyCmd = false
getPublicKeyCmd = false getPublicKeyCmd = false
createTokenCmd = false createTokenCmd = false
verifyTokenCmd = false
debug = false debug = false
keyFile string keyFile string
tokenFile string
tokenIssuer string tokenIssuer string
tokenPeerID = uuid.New() tokenPeerID = uuid.New()
keySize = 2048 keySize = 2048
@ -30,17 +28,12 @@ func init() {
&createTokenCmd, "create-token", createTokenCmd, &createTokenCmd, "create-token", createTokenCmd,
"Create a new signed authentication token", "Create a new signed authentication token",
) )
flag.BoolVar(
&verifyTokenCmd, "verify-token", verifyTokenCmd,
"Verify a token generated with the given key",
)
flag.BoolVar( flag.BoolVar(
&getPublicKeyCmd, "get-public-key", getPublicKeyCmd, &getPublicKeyCmd, "get-public-key", getPublicKeyCmd,
"Get the PEM encoded public key associated with the private key", "Get the PEM encoded public key associated with the private key",
) )
flag.BoolVar(&debug, "debug", debug, "Debug mode") flag.BoolVar(&debug, "debug", debug, "Debug mode")
flag.StringVar(&keyFile, "key", keyFile, "Path to the encrypted PEM encoded key") flag.StringVar(&keyFile, "key", keyFile, "Path to the encrypted PEM encoded key")
flag.StringVar(&tokenFile, "token", tokenFile, "Path to the token to verify")
flag.StringVar(&tokenIssuer, "token-issuer", tokenIssuer, "Token issuer") flag.StringVar(&tokenIssuer, "token-issuer", tokenIssuer, "Token issuer")
flag.StringVar(&tokenPeerID, "token-peer-id", tokenPeerID, "Token peer ID") flag.StringVar(&tokenPeerID, "token-peer-id", tokenPeerID, "Token peer ID")
flag.IntVar(&keySize, "key-size", keySize, "Size of the private key") flag.IntVar(&keySize, "key-size", keySize, "Size of the private key")
@ -55,8 +48,6 @@ func main() {
getPublicKey() getPublicKey()
case createTokenCmd: case createTokenCmd:
createToken() createToken()
case verifyTokenCmd:
verifyToken()
default: default:
flag.Usage() flag.Usage()
} }

View File

@ -2,11 +2,13 @@ package main
import ( import (
"bytes" "bytes"
"crypto/rand"
"crypto/rsa" "crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"os" "os"
"strings"
"syscall" "syscall"
"forge.cadoles.com/Cadoles/go-http-peering/crypto" "forge.cadoles.com/Cadoles/go-http-peering/crypto"
@ -45,6 +47,25 @@ func askPassphrase() ([]byte, error) {
return passphrase, nil return passphrase, nil
} }
func privateKeyToEncryptedPEM(key *rsa.PrivateKey, passphrase []byte) ([]byte, error) {
if passphrase == nil {
return nil, errors.New("passphrase cannot be empty")
}
// Convert it to pem
block := &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(key),
}
block, err := x509.EncryptPEMBlock(rand.Reader, block.Type, block.Bytes, passphrase, x509.PEMCipherAES256)
if err != nil {
return nil, errors.WithStack(err)
}
return pem.EncodeToMemory(block), nil
}
func loadPrivateKey() (*rsa.PrivateKey, error) { func loadPrivateKey() (*rsa.PrivateKey, error) {
if keyFile == "" { if keyFile == "" {
return nil, errors.New("you must specify a key file to load") return nil, errors.New("you must specify a key file to load")
@ -64,19 +85,6 @@ func loadPrivateKey() (*rsa.PrivateKey, error) {
return privateKey, nil return privateKey, nil
} }
func loadToken() (string, error) {
if tokenFile == "" {
return "", errors.New("you must specify a token file to load")
}
token, err := os.ReadFile(tokenFile)
if err != nil {
return "", errors.WithStack(err)
}
return strings.TrimSpace(string(token)), nil
}
func handleError(err error) { func handleError(err error) {
if !debug { if !debug {
fmt.Printf("%+v\n", errors.WithStack(err)) fmt.Printf("%+v\n", errors.WithStack(err))

View File

@ -1,55 +0,0 @@
package main
import (
"encoding/json"
"fmt"
peering "forge.cadoles.com/Cadoles/go-http-peering"
"github.com/dgrijalva/jwt-go"
"github.com/pkg/errors"
)
func verifyToken() {
rawToken, err := loadToken()
if err != nil {
handleError(errors.WithStack(err))
}
privateKey, err := loadPrivateKey()
if err != nil {
handleError(errors.WithStack(err))
}
fn := func(token *jwt.Token) (interface{}, error) {
return &privateKey.PublicKey, nil
}
token, err := jwt.ParseWithClaims(rawToken, &peering.ServerTokenClaims{}, fn)
if err != nil {
validationError, ok := err.(*jwt.ValidationError)
if ok {
handleError(errors.WithStack(validationError.Inner))
}
handleError(errors.WithStack(err))
}
if !token.Valid {
handleError(errors.New("token is invalid"))
}
claims, ok := token.Claims.(*peering.ServerTokenClaims)
if !ok {
handleError(errors.New("unexpected token claims"))
}
data, err := json.MarshalIndent(claims, "", " ")
if err != nil {
handleError(errors.WithStack(err))
}
fmt.Println("Token OK.")
fmt.Println("Claims:")
fmt.Println(string(data))
}

View File

@ -9,7 +9,6 @@ import (
jwt "github.com/dgrijalva/jwt-go" jwt "github.com/dgrijalva/jwt-go"
"github.com/pkg/errors" "github.com/pkg/errors"
"golang.org/x/crypto/ssh"
) )
func EncodePublicKeyToPEM(key crypto.PublicKey) ([]byte, error) { func EncodePublicKeyToPEM(key crypto.PublicKey) ([]byte, error) {
@ -29,23 +28,25 @@ func DecodePEMToPublicKey(pem []byte) (crypto.PublicKey, error) {
} }
func DecodePEMEncryptedPrivateKey(key []byte, passphrase []byte) (*rsa.PrivateKey, error) { func DecodePEMEncryptedPrivateKey(key []byte, passphrase []byte) (*rsa.PrivateKey, error) {
var ( // Parse PEM block
rawKey interface{} var block *pem.Block
err error if block, _ = pem.Decode(key); block == nil {
) return nil, errors.New("invalid PEM block")
if len(passphrase) == 0 {
rawKey, err = ssh.ParseRawPrivateKey(key)
} else {
rawKey, err = ssh.ParseRawPrivateKeyWithPassphrase(key, passphrase)
} }
decryptedBlock, err := x509.DecryptPEMBlock(block, passphrase)
if err != nil { if err != nil {
return nil, errors.WithStack(err) return nil, errors.WithStack(err)
} }
var parsedKey interface{}
if parsedKey, err = x509.ParsePKCS1PrivateKey(decryptedBlock); err != nil {
return nil, errors.WithStack(err)
}
var privateKey *rsa.PrivateKey var privateKey *rsa.PrivateKey
var ok bool var ok bool
if privateKey, ok = rawKey.(*rsa.PrivateKey); !ok { if privateKey, ok = parsedKey.(*rsa.PrivateKey); !ok {
return nil, errors.New("invalid RSA private key") return nil, errors.New("invalid RSA private key")
} }
@ -53,13 +54,16 @@ func DecodePEMEncryptedPrivateKey(key []byte, passphrase []byte) (*rsa.PrivateKe
} }
func EncodePrivateKeyToEncryptedPEM(key *rsa.PrivateKey, passphrase []byte) ([]byte, error) { func EncodePrivateKeyToEncryptedPEM(key *rsa.PrivateKey, passphrase []byte) ([]byte, error) {
if passphrase == nil {
return nil, errors.New("passphrase cannot be empty")
}
block := &pem.Block{ block := &pem.Block{
Type: "RSA PRIVATE KEY", Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(key), Bytes: x509.MarshalPKCS1PrivateKey(key),
} }
if len(passphrase) != 0 { block, err := x509.EncryptPEMBlock(
encryptedBlock, err := x509.EncryptPEMBlock(
rand.Reader, block.Type, rand.Reader, block.Type,
block.Bytes, passphrase, x509.PEMCipherAES256, block.Bytes, passphrase, x509.PEMCipherAES256,
) )
@ -67,8 +71,5 @@ func EncodePrivateKeyToEncryptedPEM(key *rsa.PrivateKey, passphrase []byte) ([]b
return nil, errors.WithStack(err) return nil, errors.WithStack(err)
} }
block = encryptedBlock
}
return pem.EncodeToMemory(block), nil return pem.EncodeToMemory(block), nil
} }

View File

@ -1,49 +0,0 @@
#!/bin/bash
KEYGEN_BIN=${KEYGEN_BIN:-go run ../../cmd/keygen}
test_create_key_without_passphrase() {
local workspace=$(mktemp -d)
# Generate a new private key without passphrase
local key_path="${workspace}/private.key"
KEY_PASSPHRASE= $KEYGEN_BIN -create-key > "${key_path}"
}
test_create_key_with_passphrase() {
local workspace=$(mktemp -d)
# Generate a new private key with passphrase
local key_path="${workspace}/private.key"
KEY_PASSPHRASE=foobar $KEYGEN_BIN -create-key > "${key_path}"
}
test_verify_token_without_passphrase() {
local workspace=$(mktemp -d)
# Generate a new private key without passphrase
local key_path="${workspace}/private.key"
KEY_PASSPHRASE= $KEYGEN_BIN -create-key > "${key_path}"
# Generate a new token
local token_path="${workspace}/token.jwt"
KEY_PASSPHRASE= $KEYGEN_BIN -create-token -key "${key_path}" > "${token_path}"
# Verify token
KEY_PASSPHRASE= $KEYGEN_BIN -verify-token -key "${key_path}" -token "${token_path}" 1>/dev/null
}
test_verify_token_with_passphrase() {
local workspace=$(mktemp -d)
# Generate a new private key with passphrase
local key_path="${workspace}/private.key"
KEY_PASSPHRASE=foobar $KEYGEN_BIN -create-key > "${key_path}"
# Generate a new token
local token_path="${workspace}/token.jwt"
KEY_PASSPHRASE=foobar $KEYGEN_BIN -create-token -key "${key_path}" > "${token_path}"
# Verify token
KEY_PASSPHRASE=foobar $KEYGEN_BIN -verify-token -key "${key_path}" -token "${token_path}" 1>/dev/null
}

View File

@ -1,5 +1,5 @@
FROM reg.cadoles.com/proxy_cache/library/golang:1.21 FROM golang:1.19
RUN apt-get update && apt-get install -y make curl ca-certificates bash jq RUN apt-get update && apt-get install -y make upx-ucl curl ca-certificates bash jq
RUN curl -k https://forge.cadoles.com/Cadoles/Jenkins/raw/branch/master/resources/com/cadoles/common/add-letsencrypt-ca.sh | bash RUN curl -k https://forge.cadoles.com/Cadoles/Jenkins/raw/branch/master/resources/com/cadoles/common/add-letsencrypt-ca.sh | bash

View File

@ -39,7 +39,7 @@ function build {
if [ ! -z "${GPG_SIGNING_KEY}" ]; then if [ ! -z "${GPG_SIGNING_KEY}" ]; then
echo "signing '$destdir/$name' with gpg key '$GPG_SIGNING_KEY'..." echo "signing '$destdir/$name' with gpg key '$GPG_SIGNING_KEY'..."
gpg --sign --default-key "${GPG_SIGNING_KEY}" --armor --detach-sign --output "$destdir/$name.sig" "$destdir/$name" echo $GPG_SIGNING_PASSPHRASE | gpg --pinentry-mode loopback --passphrase-fd 0 --sign --default-key "${GPG_SIGNING_KEY}" --output "$destdir/$name.sig" "$destdir/$name"
fi fi
} }

View File

@ -3,12 +3,12 @@ package server
import ( import (
"crypto/rsa" "crypto/rsa"
"encoding/json" "encoding/json"
"errors"
"net/http" "net/http"
"time" "time"
peering "forge.cadoles.com/Cadoles/go-http-peering" peering "forge.cadoles.com/Cadoles/go-http-peering"
peeringCrypto "forge.cadoles.com/Cadoles/go-http-peering/crypto" peeringCrypto "forge.cadoles.com/Cadoles/go-http-peering/crypto"
"github.com/pkg/errors"
) )
var ( var (
@ -34,7 +34,7 @@ func AdvertiseHandler(store peering.Store, key *rsa.PublicKey, funcs ...OptionFu
serverClaims, err := assertServerToken(key, serverToken) serverClaims, err := assertServerToken(key, serverToken)
if err != nil { if err != nil {
logger.Printf("[ERROR] %+v", errors.Wrapf(err, "could not validate token '%s'", serverToken)) logger.Printf("[ERROR] %s", err)
sendError(w, http.StatusUnauthorized) sendError(w, http.StatusUnauthorized)
return return
} }
@ -43,53 +43,54 @@ func AdvertiseHandler(store peering.Store, key *rsa.PublicKey, funcs ...OptionFu
decoder := json.NewDecoder(r.Body) decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(advertising); err != nil { if err := decoder.Decode(advertising); err != nil {
logger.Printf("[ERROR] %+v", errors.WithStack(err)) logger.Printf("[ERROR] %s", err)
options.ErrorHandler(w, r, ErrInvalidAdvertisingRequest) options.ErrorHandler(w, r, ErrInvalidAdvertisingRequest)
return return
} }
if _, err := peeringCrypto.DecodePEMToPublicKey(advertising.PublicKey); err != nil { if _, err := peeringCrypto.DecodePEMToPublicKey(advertising.PublicKey); err != nil {
logger.Printf("[ERROR] %+v", errors.WithStack(err)) logger.Printf("[ERROR] %s", err)
options.ErrorHandler(w, r, ErrInvalidAdvertisingRequest) options.ErrorHandler(w, r, ErrInvalidAdvertisingRequest)
return return
} }
_, err = store.Get(serverClaims.PeerID) peer, err := store.Get(serverClaims.PeerID)
if err == nil { if err == nil {
logger.Printf("[WARN] %s", errors.WithStack(ErrPeerIDAlreadyInUse)) logger.Printf("[ERROR] %s", ErrPeerIDAlreadyInUse)
options.ErrorHandler(w, r, ErrPeerIDAlreadyInUse) options.ErrorHandler(w, r, ErrPeerIDAlreadyInUse)
return return
} }
if !errors.Is(err, peering.ErrPeerNotFound) { if err != peering.ErrPeerNotFound {
logger.Printf("[ERROR] %+v", errors.WithStack(err)) logger.Printf("[ERROR] %s", err)
options.ErrorHandler(w, r, err) options.ErrorHandler(w, r, err)
return return
} }
attrs := filterAttributes(options.PeerAttributes, advertising.Attributes) attrs := filterAttributes(options.PeerAttributes, advertising.Attributes)
peer, err := store.Create(serverClaims.PeerID, attrs) peer, err = store.Create(serverClaims.PeerID, attrs)
if err != nil { if err != nil {
logger.Printf("[ERROR] %+v", errors.WithStack(err)) logger.Printf("[ERROR] %s", err)
options.ErrorHandler(w, r, err) options.ErrorHandler(w, r, err)
return return
} }
if err := store.UpdateLastContact(peer.ID, r.RemoteAddr, time.Now()); err != nil { if err := store.UpdateLastContact(peer.ID, r.RemoteAddr, time.Now()); err != nil {
logger.Printf("[ERROR] %+v", errors.WithStack(err)) logger.Printf("[ERROR] %s", err)
options.ErrorHandler(w, r, err) options.ErrorHandler(w, r, err)
return return
} }
if err := store.UpdateLastContact(peer.ID, r.RemoteAddr, time.Now()); err != nil { if err := store.UpdateLastContact(peer.ID, r.RemoteAddr, time.Now()); err != nil {
logger.Printf("[ERROR] %+v", errors.WithStack(err)) logger.Printf("[ERROR] %s", err)
options.ErrorHandler(w, r, err) options.ErrorHandler(w, r, err)
return return
} }
if err := store.UpdatePublicKey(peer.ID, advertising.PublicKey); err != nil { if err := store.UpdatePublicKey(peer.ID, advertising.PublicKey); err != nil {
logger.Printf("[ERROR] %+v", errors.WithStack(err)) logger.Printf("[ERROR] %s", err)
options.ErrorHandler(w, r, err) options.ErrorHandler(w, r, err)
return return
} }
@ -116,39 +117,39 @@ func UpdateHandler(store peering.Store, funcs ...OptionFunc) http.HandlerFunc {
peerID, err := GetPeerID(r) peerID, err := GetPeerID(r)
if err != nil { if err != nil {
logger.Printf("[ERROR] %+v", errors.WithStack(err)) logger.Printf("[ERROR] %s", err)
options.ErrorHandler(w, r, err) options.ErrorHandler(w, r, err)
return return
} }
peer, err := store.Get(peerID) peer, err := store.Get(peerID)
if err != nil { if err != nil {
logger.Printf("[ERROR] %+v", errors.WithStack(err)) logger.Printf("[ERROR] %s", err)
options.ErrorHandler(w, r, err) options.ErrorHandler(w, r, err)
return return
} }
if peer == nil { if peer == nil {
logger.Printf("[ERROR] %+v", errors.WithStack(ErrUnauthorized)) logger.Printf("[ERROR] %s", ErrUnauthorized)
options.ErrorHandler(w, r, ErrUnauthorized) options.ErrorHandler(w, r, ErrUnauthorized)
return return
} }
if peer.Status == peering.StatusRejected { if peer.Status == peering.StatusRejected {
logger.Printf("[ERROR] %+v", errors.WithStack(ErrPeerRejected)) logger.Printf("[ERROR] %s", ErrPeerRejected)
options.ErrorHandler(w, r, ErrPeerRejected) options.ErrorHandler(w, r, ErrPeerRejected)
return return
} }
if err := store.UpdateLastContact(peer.ID, r.RemoteAddr, time.Now()); err != nil { if err := store.UpdateLastContact(peer.ID, r.RemoteAddr, time.Now()); err != nil {
logger.Printf("[ERROR] %+v", errors.WithStack(err)) logger.Printf("[ERROR] %s", err)
options.ErrorHandler(w, r, err) options.ErrorHandler(w, r, err)
return return
} }
attrs := filterAttributes(options.PeerAttributes, update.Attributes) attrs := filterAttributes(options.PeerAttributes, update.Attributes)
if err := store.UpdateAttributes(peer.ID, attrs); err != nil { if err := store.UpdateAttributes(peer.ID, attrs); err != nil {
logger.Printf("[ERROR] %+v", errors.WithStack(err)) logger.Printf("[ERROR] %s", err)
options.ErrorHandler(w, r, err) options.ErrorHandler(w, r, err)
return return
} }
@ -175,32 +176,32 @@ func PingHandler(store peering.Store, funcs ...OptionFunc) http.HandlerFunc {
peerID, err := GetPeerID(r) peerID, err := GetPeerID(r)
if err != nil { if err != nil {
logger.Printf("[ERROR] %+v", errors.WithStack(err)) logger.Printf("[ERROR] %s", err)
options.ErrorHandler(w, r, err) options.ErrorHandler(w, r, err)
return return
} }
peer, err := store.Get(peerID) peer, err := store.Get(peerID)
if err != nil { if err != nil {
logger.Printf("[ERROR] %+v", errors.WithStack(err)) logger.Printf("[ERROR] %s", err)
options.ErrorHandler(w, r, err) options.ErrorHandler(w, r, err)
return return
} }
if peer == nil { if peer == nil {
logger.Printf("[ERROR] %+v", errors.WithStack(ErrUnauthorized)) logger.Printf("[ERROR] %s", ErrUnauthorized)
options.ErrorHandler(w, r, ErrUnauthorized) options.ErrorHandler(w, r, ErrUnauthorized)
return return
} }
if peer.Status == peering.StatusRejected { if peer.Status == peering.StatusRejected {
logger.Printf("[ERROR] %+v", errors.WithStack(ErrPeerRejected)) logger.Printf("[ERROR] %s", ErrPeerRejected)
options.ErrorHandler(w, r, ErrPeerRejected) options.ErrorHandler(w, r, ErrPeerRejected)
return return
} }
if err := store.UpdateLastContact(peer.ID, r.RemoteAddr, time.Now()); err != nil { if err := store.UpdateLastContact(peer.ID, r.RemoteAddr, time.Now()); err != nil {
logger.Printf("[ERROR] %+v", errors.WithStack(err)) logger.Printf("[ERROR] %s", err)
options.ErrorHandler(w, r, err) options.ErrorHandler(w, r, err)
return return
} }

View File

@ -5,6 +5,7 @@ import (
"context" "context"
"crypto/rsa" "crypto/rsa"
"crypto/sha256" "crypto/sha256"
"errors"
"io" "io"
"io/ioutil" "io/ioutil"
"net/http" "net/http"
@ -14,7 +15,6 @@ import (
peering "forge.cadoles.com/Cadoles/go-http-peering" peering "forge.cadoles.com/Cadoles/go-http-peering"
jwt "github.com/dgrijalva/jwt-go" jwt "github.com/dgrijalva/jwt-go"
"github.com/pkg/errors"
) )
const ( const (
@ -51,7 +51,7 @@ func Authenticate(store peering.Store, key *rsa.PublicKey, funcs ...OptionFunc)
serverClaims, err := assertServerToken(key, serverToken) serverClaims, err := assertServerToken(key, serverToken)
if err != nil { if err != nil {
logger.Printf("[ERROR] %+v", errors.WithStack(err)) logger.Printf("[ERROR] %s", err)
sendError(w, http.StatusUnauthorized) sendError(w, http.StatusUnauthorized)
return return
} }
@ -64,13 +64,13 @@ func Authenticate(store peering.Store, key *rsa.PublicKey, funcs ...OptionFunc)
options.IgnoredClientTokenErrors..., options.IgnoredClientTokenErrors...,
) )
if err != nil { if err != nil {
logger.Printf("[ERROR] %+v", errors.WithStack(err)) logger.Printf("[ERROR] %s", err)
switch err { switch err {
case peering.ErrPeerNotFound: case peering.ErrPeerNotFound:
sendError(w, http.StatusUnauthorized) sendError(w, http.StatusUnauthorized)
case ErrNotPeered: case ErrNotPeered:
if err := store.UpdateLastContact(serverClaims.PeerID, r.RemoteAddr, time.Now()); err != nil { if err := store.UpdateLastContact(serverClaims.PeerID, r.RemoteAddr, time.Now()); err != nil {
logger.Printf("[ERROR] %+v", errors.WithStack(err)) logger.Printf("[ERROR] %s", err)
sendError(w, http.StatusInternalServerError) sendError(w, http.StatusInternalServerError)
return return
} }
@ -78,7 +78,7 @@ func Authenticate(store peering.Store, key *rsa.PublicKey, funcs ...OptionFunc)
return return
case ErrPeerRejected: case ErrPeerRejected:
if err := store.UpdateLastContact(serverClaims.PeerID, r.RemoteAddr, time.Now()); err != nil { if err := store.UpdateLastContact(serverClaims.PeerID, r.RemoteAddr, time.Now()); err != nil {
logger.Printf("[ERROR] %+v", errors.WithStack(err)) logger.Printf("[ERROR] %s", err)
sendError(w, http.StatusInternalServerError) sendError(w, http.StatusInternalServerError)
return return
} }
@ -92,19 +92,19 @@ func Authenticate(store peering.Store, key *rsa.PublicKey, funcs ...OptionFunc)
match, body, err := assertBodySum(r.Body, clientClaims.BodySum) match, body, err := assertBodySum(r.Body, clientClaims.BodySum)
if err != nil { if err != nil {
logger.Printf("[ERROR] %+v", errors.WithStack(err)) logger.Printf("[ERROR] %s", err)
sendError(w, http.StatusInternalServerError) sendError(w, http.StatusInternalServerError)
return return
} }
if !match { if !match {
logger.Printf("[ERROR] %+v", errors.WithStack(ErrInvalidChecksum)) logger.Printf("[ERROR] %s", ErrInvalidChecksum)
sendError(w, http.StatusBadRequest) sendError(w, http.StatusBadRequest)
return return
} }
if err := store.UpdateLastContact(serverClaims.PeerID, r.RemoteAddr, time.Now()); err != nil { if err := store.UpdateLastContact(serverClaims.PeerID, r.RemoteAddr, time.Now()); err != nil {
logger.Printf("[ERROR] %+v", errors.WithStack(err)) logger.Printf("[ERROR] %s", err)
sendError(w, http.StatusInternalServerError) sendError(w, http.StatusInternalServerError)
return return
} }
@ -183,7 +183,7 @@ func assertClientToken(peerID peering.PeerID, store peering.Store, clientToken s
if ok { if ok {
for _, c := range ignoredValidationErrors { for _, c := range ignoredValidationErrors {
if validationError.Errors&c != 0 { if validationError.Errors&c != 0 {
logger.Printf("ignoring token validation error: '%+v'", errors.WithStack(validationError.Inner)) logger.Printf("ignoring token validation error: '%s'", validationError.Inner)
return getPeeringClaims(token) return getPeeringClaims(token)
} }
} }