feat: always-on remote node — MCP over HTTP, TLS/token, Docker, CI, sqlc (#9)
build / test (push) Successful in 3m19s
build / image (push) Successful in 18s

Deploys knox as a headless, always-on replica so agents keep their memory when the laptop is off.

Closes #8. **Supersedes #5** (its hardening commit is merged in here; close #5 after this lands).

## What changed

**MCP transport + SDK**
- Moves from `mark3labs/mcp-go` v0.17 (stdio only, five releases behind) to the official `modelcontextprotocol/go-sdk` v1.8. Tool inputs are typed structs, so schemas are generated instead of hand-built.
- Adds `knox mcp --http` (Streamable HTTP). stdio remains the default.

**Transport security without a public name**
- `KNOX_AUTH_TOKEN` guards gossip and MCP HTTP; `KNOX_TLS_CERT/KEY` serve TLS; `knox tls init` mints a self-signed cert whose SANs are whatever addresses clients dial. Verified: 401 without the token, 200 with, cert valid for the overlay IP.

**Daemon hygiene**
- SIGTERM shuts down the gossip and metrics servers.
- `--version` reports the VCS revision.
- `KNOX_LOCAL_SOURCES=none` makes a node ingest nothing but still derive.
- Default watch dirs skip paths that do not exist.

**Deployment topology fixes** (all found by actually running a replica)
- `KNOX_LISTEN_ADDR` split from `KNOX_PEER_ADDR`: a container cannot bind the host's overlay IP, and previously the gossip server silently failed to start.
- Reconcile now fires on push and on startup, not only on pull. Three separate bugs left `entries` empty on a push-only node.
- Pushes batch by byte budget, not just row count — 500 content-heavy rows exceeded the 4 MiB body limit and the log stalled permanently at 3,000 observations.
- Threads and snippets derive on replicas: gating them with the ingesters left the server holding 11.5k observations and 4.9k entries but 2 of 28 threads.

**Packaging + CI**
- Multi-stage Dockerfile (static, non-root, `/data` volume).
- Gitea workflow builds on the dhg.lol daemon through the runner socket, tags `:latest` + `:<sha>`, and restarts the stack when installed. BuildKit cache mounts keep module downloads warm.

**sqlc pilot**
- Schema extracted to `internal/db/schema.sql` (embedded); read paths behind the MCP tools are generated.
- The pilot found real drift: `entries.created_at` existed only as a runtime `ALTER`. It is now declared in the schema, and `sqlcdb_pilot_test.go` fails if generated code disagrees with `db.Open`.
- FTS5 stays hand-written: sqlc ignores `CREATE VIRTUAL TABLE`, so `MATCH`/`bm25` cannot be generated.

## Verification
- `go vet ./...`, `go test ./...`, `gofmt` clean
- `scripts/conformance.sh` — official MCP suite, exit 0 against `conformance-baseline.yml` (documents the capabilities knox does not implement: resources, prompts, completions, fixture tools)
- Live: both containers healthy on dhg.lol, ports bound only to the ZeroTier address, 11,553 observations / 4,943 entries replicated and reconciled

## Deploy
Infrastructure lives in `tf-net/apps/knox` (separate repo); this branch is what is currently running in production.

Reviewed-on: #9
Co-authored-by: David Gwilliam <dhgwilliam@gmail.com>
Co-committed-by: David Gwilliam <dhgwilliam@gmail.com>
This commit was merged in pull request #9.
This commit is contained in:
2026-11-05 02:14:33 +00:00
committed by david
parent 8d6d73b747
commit e3bbeabb6b
31 changed files with 2883 additions and 1334 deletions
+200
View File
@@ -0,0 +1,200 @@
// 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
}