feat: import Sea vHost single-server testing release
This commit is contained in:
commit
248badd33e
441 files changed
+63221
No files matched your search
@@ -0,0 +1,86 @@
|
||||
package controlwire
|
||||
|
||||
import (
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/hex"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"math/big"
|
||||
"net"
|
||||
"time"
|
||||
)
|
||||
|
||||
func Pair(nodeID uint64, endpoint string) (Credentials, ServerIdentity, error) {
|
||||
if nodeID == 0 {
|
||||
return Credentials{}, ServerIdentity{}, errors.New("node identity required")
|
||||
}
|
||||
u, err := ValidateEndpoint(endpoint)
|
||||
if err != nil {
|
||||
return Credentials{}, ServerIdentity{}, err
|
||||
}
|
||||
serial := func() (*big.Int, error) { return rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 120)) }
|
||||
caSerial, err := serial()
|
||||
if err != nil {
|
||||
return Credentials{}, ServerIdentity{}, err
|
||||
}
|
||||
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if err != nil {
|
||||
return Credentials{}, ServerIdentity{}, err
|
||||
}
|
||||
now := time.Now()
|
||||
ca := &x509.Certificate{SerialNumber: caSerial, Subject: pkix.Name{CommonName: "Sea vHost node trust"}, NotBefore: now.Add(-5 * time.Minute), NotAfter: now.AddDate(2, 0, 0), IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign}
|
||||
caDER, err := x509.CreateCertificate(rand.Reader, ca, ca, &key.PublicKey, key)
|
||||
if err != nil {
|
||||
return Credentials{}, ServerIdentity{}, err
|
||||
}
|
||||
caPEM := string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: caDER}))
|
||||
issue := func(client bool) (string, string, *ecdsa.PrivateKey, error) {
|
||||
k, e := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if e != nil {
|
||||
return "", "", nil, e
|
||||
}
|
||||
certSerial, e := serial()
|
||||
if e != nil {
|
||||
return "", "", nil, e
|
||||
}
|
||||
cert := &x509.Certificate{SerialNumber: certSerial, Subject: pkix.Name{CommonName: "Sea vHost paired identity"}, NotBefore: now.Add(-5 * time.Minute), NotAfter: now.AddDate(1, 0, 0), KeyUsage: x509.KeyUsageDigitalSignature}
|
||||
if client {
|
||||
cert.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}
|
||||
} else {
|
||||
cert.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}
|
||||
if ip := net.ParseIP(u.Hostname()); ip != nil {
|
||||
cert.IPAddresses = []net.IP{ip}
|
||||
} else {
|
||||
cert.DNSNames = []string{u.Hostname()}
|
||||
}
|
||||
}
|
||||
der, e := x509.CreateCertificate(rand.Reader, cert, ca, &k.PublicKey, key)
|
||||
if e != nil {
|
||||
return "", "", nil, e
|
||||
}
|
||||
private, e := x509.MarshalPKCS8PrivateKey(k)
|
||||
if e != nil {
|
||||
return "", "", nil, e
|
||||
}
|
||||
return string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})), string(pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: private})), k, nil
|
||||
}
|
||||
clientCert, clientKey, client, e := issue(true)
|
||||
if e != nil {
|
||||
return Credentials{}, ServerIdentity{}, e
|
||||
}
|
||||
serverCert, serverKey, _, e := issue(false)
|
||||
if e != nil {
|
||||
return Credentials{}, ServerIdentity{}, e
|
||||
}
|
||||
spki, e := x509.MarshalPKIXPublicKey(&client.PublicKey)
|
||||
if e != nil {
|
||||
return Credentials{}, ServerIdentity{}, e
|
||||
}
|
||||
digest := sha256.Sum256(spki)
|
||||
return Credentials{CAPEM: caPEM, ClientCertificate: clientCert, ClientPrivateKey: clientKey}, ServerIdentity{NodeID: nodeID, CAPEM: caPEM, Certificate: serverCert, PrivateKey: serverKey, ClientSPKI: hex.EncodeToString(digest[:])}, nil
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
// 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
|
||||
}
|
||||
Reference in new issue
Block a user