177 lines
5.8 KiB
Go
177 lines
5.8 KiB
Go
// Package controlwire defines the versioned controller-initiated node wire
|
|
// protocol. It has no store, scheduler or business database dependency.
|
|
package controlwire
|
|
|
|
import (
|
|
"bytes"
|
|
"crypto/sha256"
|
|
"crypto/subtle"
|
|
"crypto/tls"
|
|
"crypto/x509"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
const Version = "sea-vhost-node/1"
|
|
const MaxEnvelopeBytes = 4 << 20
|
|
|
|
type Credentials struct {
|
|
CAPEM string `json:"caPem"`
|
|
ClientCertificate string `json:"clientCertificate"`
|
|
ClientPrivateKey string `json:"clientPrivateKey"`
|
|
}
|
|
type ServerIdentity struct {
|
|
NodeID uint64 `json:"nodeId"`
|
|
CAPEM string `json:"caPem"`
|
|
Certificate string `json:"certificate"`
|
|
PrivateKey string `json:"privateKey"`
|
|
ClientSPKI string `json:"clientSpki"`
|
|
}
|
|
|
|
func ValidateEndpoint(endpoint string) (*url.URL, error) {
|
|
u, err := url.Parse(endpoint)
|
|
if err != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") {
|
|
return nil, errors.New("node endpoint must be an HTTPS origin without credentials, path, query or fragment")
|
|
}
|
|
return u, nil
|
|
}
|
|
func ClientTLS(credentials Credentials) (*tls.Config, error) {
|
|
roots := x509.NewCertPool()
|
|
if !roots.AppendCertsFromPEM([]byte(credentials.CAPEM)) {
|
|
return nil, errors.New("invalid node CA")
|
|
}
|
|
certificate, err := tls.X509KeyPair([]byte(credentials.ClientCertificate), []byte(credentials.ClientPrivateKey))
|
|
if err != nil {
|
|
return nil, errors.New("invalid controller client identity")
|
|
}
|
|
return &tls.Config{MinVersion: tls.VersionTLS13, RootCAs: roots, Certificates: []tls.Certificate{certificate}}, nil
|
|
}
|
|
func ServerTLS(identity ServerIdentity) (*tls.Config, error) {
|
|
if identity.NodeID == 0 || len(identity.ClientSPKI) != 64 {
|
|
return nil, errors.New("invalid node identity")
|
|
}
|
|
expected, err := hex.DecodeString(identity.ClientSPKI)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
roots := x509.NewCertPool()
|
|
if !roots.AppendCertsFromPEM([]byte(identity.CAPEM)) {
|
|
return nil, errors.New("invalid controller trust CA")
|
|
}
|
|
certificate, err := tls.X509KeyPair([]byte(identity.Certificate), []byte(identity.PrivateKey))
|
|
if err != nil {
|
|
return nil, errors.New("invalid node TLS keypair")
|
|
}
|
|
return &tls.Config{MinVersion: tls.VersionTLS13, Certificates: []tls.Certificate{certificate}, ClientCAs: roots, ClientAuth: tls.RequireAndVerifyClientCert, VerifyConnection: func(state tls.ConnectionState) error {
|
|
if len(state.PeerCertificates) == 0 {
|
|
return errors.New("controller identity missing")
|
|
}
|
|
actual := sha256.Sum256(state.PeerCertificates[0].RawSubjectPublicKeyInfo)
|
|
if subtle.ConstantTimeCompare(actual[:], expected) != 1 {
|
|
return errors.New("controller identity is not paired to this node")
|
|
}
|
|
return nil
|
|
}}, nil
|
|
}
|
|
func Decode(w http.ResponseWriter, r *http.Request, out any) error {
|
|
r.Body = http.MaxBytesReader(w, r.Body, MaxEnvelopeBytes)
|
|
decoder := json.NewDecoder(r.Body)
|
|
decoder.DisallowUnknownFields()
|
|
if err := decoder.Decode(out); err != nil {
|
|
return errors.New("invalid node request")
|
|
}
|
|
if decoder.Decode(&struct{}{}) != io.EOF {
|
|
return errors.New("trailing node request data")
|
|
}
|
|
return nil
|
|
}
|
|
func Encode(w http.ResponseWriter, status int, value any) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.Header().Set("Cache-Control", "no-store")
|
|
w.WriteHeader(status)
|
|
_ = json.NewEncoder(w).Encode(value)
|
|
}
|
|
|
|
// Authenticated also binds the destination node and protocol. Credentials for
|
|
// one node cannot be silently reused against a different node endpoint.
|
|
func Authenticated(nodeID uint64, next http.Handler) http.Handler {
|
|
var mu sync.Mutex
|
|
seen := map[string]int64{}
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if r.TLS == nil || len(r.TLS.VerifiedChains) == 0 {
|
|
http.Error(w, "mutual TLS required", 401)
|
|
return
|
|
}
|
|
if r.Header.Get("X-Sea-Protocol") != Version || r.Header.Get("X-Sea-Node") != strconv.FormatUint(nodeID, 10) {
|
|
http.Error(w, "wrong node or protocol", 403)
|
|
return
|
|
}
|
|
expiry, err := strconv.ParseInt(r.Header.Get("X-Sea-Expires"), 10, 64)
|
|
now := time.Now().Unix()
|
|
if err != nil || expiry < now || expiry > now+300 {
|
|
http.Error(w, "expired node request", 403)
|
|
return
|
|
}
|
|
requestID := r.Header.Get("X-Sea-Request")
|
|
if len(requestID) != 32 {
|
|
http.Error(w, "invalid request identity", 400)
|
|
return
|
|
}
|
|
if _, err := hex.DecodeString(requestID); err != nil {
|
|
http.Error(w, "invalid request identity", 400)
|
|
return
|
|
}
|
|
if r.Method != http.MethodGet {
|
|
mu.Lock()
|
|
for id, until := range seen {
|
|
if until < now {
|
|
delete(seen, id)
|
|
}
|
|
}
|
|
_, duplicate := seen[requestID]
|
|
full := len(seen) >= 20000
|
|
if !duplicate && !full {
|
|
seen[requestID] = expiry
|
|
}
|
|
mu.Unlock()
|
|
if duplicate {
|
|
http.Error(w, "request already received; reconcile actual state", 409)
|
|
return
|
|
}
|
|
if full {
|
|
http.Error(w, "node request capacity reached", 503)
|
|
return
|
|
}
|
|
}
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
func NewRequest(method, endpoint, route string, nodeID uint64, requestID string, body []byte) (*http.Request, error) {
|
|
base, err := ValidateEndpoint(endpoint)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if !strings.HasPrefix(route, "/v1/") || strings.Contains(route, "..") || strings.ContainsAny(route, "?#") {
|
|
return nil, errors.New("invalid node route")
|
|
}
|
|
base.Path = route
|
|
request, err := http.NewRequest(method, base.String(), bytes.NewReader(body))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
request.Header.Set("Content-Type", "application/json")
|
|
request.Header.Set("X-Sea-Protocol", Version)
|
|
request.Header.Set("X-Sea-Node", strconv.FormatUint(nodeID, 10))
|
|
request.Header.Set("X-Sea-Request", requestID)
|
|
request.Header.Set("X-Sea-Expires", strconv.FormatInt(time.Now().Add(2*time.Minute).Unix(), 10))
|
|
return request, nil
|
|
}
|