// Package httpauth wraps knox's HTTP surfaces (gossip sync, MCP over HTTP) with // a shared bearer-token check and optional TLS. // // The design goal is a node that can be reached from an untrusted network // without owning a public DNS name or a CA-issued certificate: set // KNOX_TLS_CERT/KNOX_TLS_KEY to a self-signed pair (see GenerateSelfSigned), // point peers at it with KNOX_TLS_CA, and share KNOX_AUTH_TOKEN. package httpauth import ( "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/subtle" "crypto/tls" "crypto/x509" "crypto/x509/pkix" "encoding/pem" "fmt" "math/big" "net" "net/http" "os" "path/filepath" "strings" "time" ) // Environment variables shared by server and client sides. const ( // TokenEnv holds the shared secret required in "Authorization: Bearer". TokenEnv = "KNOX_AUTH_TOKEN" // CertEnv and KeyEnv point at the serving certificate and key (PEM). CertEnv = "KNOX_TLS_CERT" KeyEnv = "KNOX_TLS_KEY" // CAEnv points at a PEM bundle to trust when talking to peers. For a // self-signed node this is the node's own certificate. CAEnv = "KNOX_TLS_CA" // InsecureEnv ("1") skips verification. Convenient on a trusted overlay; // prefer CAEnv everywhere else. InsecureEnv = "KNOX_INSECURE_TLS" ) // Token returns the configured shared secret, or "" when auth is disabled. func Token() string { return strings.TrimSpace(os.Getenv(TokenEnv)) } // Enabled reports whether a shared token is configured. func Enabled() bool { return Token() != "" } // TLSCert and TLSKey return the configured serving certificate pair. func TLSCert() string { return strings.TrimSpace(os.Getenv(CertEnv)) } func TLSKey() string { return strings.TrimSpace(os.Getenv(KeyEnv)) } // TLSAvailable reports whether the node has a serving certificate configured. func TLSAvailable() bool { return TLSCert() != "" && TLSKey() != "" } // Middleware requires a bearer token on every request when one is configured. // With no token set it passes requests through untouched, so an existing // loopback-only setup keeps working with no configuration. func Middleware(next http.Handler) http.Handler { token := Token() if token == "" { return next } want := []byte("Bearer " + token) return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { got := []byte(r.Header.Get("Authorization")) if subtle.ConstantTimeCompare(got, want) != 1 { w.Header().Set("WWW-Authenticate", `Bearer realm="knox"`) http.Error(w, "unauthorized", http.StatusUnauthorized) return } next.ServeHTTP(w, r) }) } // Client returns an HTTP client that presents the shared token and trusts the // configured CA (or nothing, when InsecureEnv is set). A zero timeout disables // the client-level timeout, which is what long-running streamed responses want. func Client(timeout time.Duration) *http.Client { tr := http.DefaultTransport.(*http.Transport).Clone() tlsCfg := &tls.Config{MinVersion: tls.VersionTLS12} if ca := strings.TrimSpace(os.Getenv(CAEnv)); ca != "" { if pool, err := loadCA(ca); err == nil { tlsCfg.RootCAs = pool } } if v := strings.TrimSpace(os.Getenv(InsecureEnv)); v == "1" || strings.EqualFold(v, "true") { tlsCfg.InsecureSkipVerify = true } tr.TLSClientConfig = tlsCfg token := Token() return &http.Client{ Timeout: timeout, Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) { if token != "" { r = r.Clone(r.Context()) r.Header.Set("Authorization", "Bearer "+token) } return tr.RoundTrip(r) }), } } // Serve runs srv with TLS when a certificate is configured, and in plaintext // otherwise. It returns a plaintext error the same way http.Server does, so // callers can ignore http.ErrServerClosed identically in both modes. func Serve(srv *http.Server) error { if TLSAvailable() { return srv.ListenAndServeTLS(TLSCert(), TLSKey()) } return srv.ListenAndServe() } // loadCA reads a PEM file into a certificate pool. The file may contain one or // more certificates; a self-signed node's own cert works as its own CA. func loadCA(path string) (*x509.CertPool, error) { data, err := os.ReadFile(path) if err != nil { return nil, err } pool := x509.NewCertPool() if !pool.AppendCertsFromPEM(data) { return nil, fmt.Errorf("%s: no certificates found", path) } return pool, nil } // roundTripFunc adapts a function to http.RoundTripper. type roundTripFunc func(*http.Request) (*http.Response, error) func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } // GenerateSelfSigned writes a self-signed certificate and key covering hosts // (DNS names and/or IP addresses), valid for the given duration. The // certificate is its own CA, so distributed peers can trust it via CAEnv // without a public DNS name or an external certificate authority. func GenerateSelfSigned(certPath, keyPath string, hosts []string, validFor time.Duration) error { key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { return fmt.Errorf("generate key: %w", err) } serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128)) if err != nil { return fmt.Errorf("serial: %w", err) } now := time.Now() tmpl := x509.Certificate{ SerialNumber: serial, Subject: pkix.Name{Organization: []string{"knox"}, CommonName: "knox"}, NotBefore: now.Add(-time.Hour), NotAfter: now.Add(validFor), KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, BasicConstraintsValid: true, IsCA: true, } for _, h := range hosts { h = strings.TrimSpace(h) if h == "" { continue } if ip := net.ParseIP(h); ip != nil { tmpl.IPAddresses = append(tmpl.IPAddresses, ip) } else { tmpl.DNSNames = append(tmpl.DNSNames, h) } } if len(tmpl.IPAddresses) == 0 && len(tmpl.DNSNames) == 0 { tmpl.DNSNames = []string{"localhost"} tmpl.IPAddresses = []net.IP{net.IPv4(127, 0, 0, 1), net.IPv6loopback} } der, err := x509.CreateCertificate(rand.Reader, &tmpl, &tmpl, &key.PublicKey, key) if err != nil { return fmt.Errorf("create certificate: %w", err) } if err := os.MkdirAll(filepath.Dir(certPath), 0o755); err != nil { return err } certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}) if err := os.WriteFile(certPath, certPEM, 0o644); err != nil { return err } keyDER, err := x509.MarshalECPrivateKey(key) if err != nil { return fmt.Errorf("marshal key: %w", err) } keyPEM := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER}) if err := os.WriteFile(keyPath, keyPEM, 0o600); err != nil { return err } return nil }