The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
package main
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"encoding/pem"
"fmt"
"math/big"
"net"
"net/http"
"strings"
"sync"
"time"
)
// BoxCA signs short-lived host certificates with the persisted per-box CA.
type BoxCA struct {
cert *x509.Certificate
key *ecdsa.PrivateKey
certPEM []byte
certCache sync.Map // hostname -> *tls.Certificate
}
var (
upstreamRootCAs *x509.CertPool
upstreamRootCAsOnce sync.Once
upstreamRootCAsErr error
)
// NewBoxCAFromPEM reconstructs a BoxCA from PEM-encoded cert and key.
// The cert/key are generated by the Rust side and passed via GvproxyConfig JSON.
func NewBoxCAFromPEM(certPEM, keyPEM []byte) (*BoxCA, error) {
block, _ := pem.Decode(certPEM)
if block == nil || block.Type != "CERTIFICATE" {
return nil, fmt.Errorf("failed to decode CA certificate PEM")
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, fmt.Errorf("failed to parse CA certificate: %w", err)
}
keyBlock, _ := pem.Decode(keyPEM)
if keyBlock == nil {
return nil, fmt.Errorf("failed to decode CA key PEM")
}
// rcgen uses PKCS8 format ("PRIVATE KEY"), try that first
rawKey, err := x509.ParsePKCS8PrivateKey(keyBlock.Bytes)
if err != nil {
// Fallback to SEC1 format ("EC PRIVATE KEY")
rawKey, err = x509.ParseECPrivateKey(keyBlock.Bytes)
if err != nil {
return nil, fmt.Errorf("failed to parse CA key (tried PKCS8 and SEC1): %w", err)
}
}
ecKey, ok := rawKey.(*ecdsa.PrivateKey)
if !ok {
return nil, fmt.Errorf("CA key is not ECDSA (got %T)", rawKey)
}
return &BoxCA{
cert: cert,
key: ecKey,
certPEM: certPEM,
}, nil
}
// CACertPEM returns the CA certificate in PEM format.
func (ca *BoxCA) CACertPEM() []byte {
return ca.certPEM
}
// CACertPool returns an x509.CertPool containing this CA's certificate.
func (ca *BoxCA) CACertPool() (*x509.CertPool, error) {
pool := x509.NewCertPool()
pool.AddCert(ca.cert)
return pool, nil
}
const maxCertCacheSize = 10000
// GenerateHostCert generates a TLS certificate for the given hostname, signed by this CA.
// Results are cached per-hostname.
func (ca *BoxCA) GenerateHostCert(hostname string) (*tls.Certificate, error) {
return ca.generateHostCert(hostname, time.Now())
}
// generateHostCert evaluates issuer and cache validity at one instant.
func (ca *BoxCA) generateHostCert(hostname string, now time.Time) (*tls.Certificate, error) {
if now.Before(ca.cert.NotBefore) || !now.Before(ca.cert.NotAfter) {
return nil, fmt.Errorf("MITM CA is invalid at %s (valid from %s until %s)", now, ca.cert.NotBefore, ca.cert.NotAfter)
}
if cached, ok := ca.certCache.Load(hostname); ok {
tlsCert := cached.(*tls.Certificate)
// Check TTL: regenerate if cert has expired
if tlsCert.Leaf != nil && !now.Before(tlsCert.Leaf.NotBefore) && now.Before(tlsCert.Leaf.NotAfter) {
return tlsCert, nil
}
// Expired — fall through to regenerate
ca.certCache.Delete(hostname)
}
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return nil, err
}
serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
if err != nil {
return nil, err
}
template := &x509.Certificate{
SerialNumber: serial,
NotBefore: now.Add(-1 * time.Minute),
NotAfter: now.Add(24 * time.Hour),
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
}
if template.NotAfter.After(ca.cert.NotAfter) {
template.NotAfter = ca.cert.NotAfter
}
if template.NotBefore.Before(ca.cert.NotBefore) {
template.NotBefore = ca.cert.NotBefore
}
if ip := net.ParseIP(hostname); ip != nil {
template.IPAddresses = []net.IP{ip}
} else {
template.DNSNames = []string{hostname}
}
certDER, err := x509.CreateCertificate(rand.Reader, template, ca.cert, &key.PublicKey, ca.key)
if err != nil {
return nil, err
}
leaf, _ := x509.ParseCertificate(certDER)
tlsCert := &tls.Certificate{
Certificate: [][]byte{certDER, ca.cert.Raw},
PrivateKey: key,
Leaf: leaf, // stored for TTL check
}
// Evict expired entries and enforce max size.
// sync.Map doesn't have a size, so we count during eviction.
cacheSize := 0
ca.certCache.Range(func(key, val any) bool {
if cert, ok := val.(*tls.Certificate); ok && cert.Leaf != nil && now.After(cert.Leaf.NotAfter) {
ca.certCache.Delete(key) // expired
} else {
cacheSize++
}
return true
})
if cacheSize >= maxCertCacheSize {
// Over limit even after TTL eviction — clear oldest half
evicted := 0
ca.certCache.Range(func(key, _ any) bool {
ca.certCache.Delete(key)
evicted++
return evicted < cacheSize/2
})
}
actual, loaded := ca.certCache.LoadOrStore(hostname, tlsCert)
if loaded {
return actual.(*tls.Certificate), nil
}
return tlsCert, nil
}
// injectSecretHeaders injects configured secret headers for the matching host.
// It overwrites only headers present in the original request, including empty values.
// Rust validates templates and supplies defaults before sending this configuration.
func injectSecretHeaders(req *http.Request, originalHeaders http.Header, secrets []SecretConfig) {
for _, s := range secrets {
for headerName, template := range s.Headers {
if _, present := originalHeaders[http.CanonicalHeaderKey(headerName)]; !present {
continue
}
req.Header.Set(headerName, strings.Replace(template, "{value}", s.Value, 1))
}
}
}
// resolveUpstreamTLS returns the TLS config for upstream connections.
// Uses the first override if provided, otherwise creates a default config with ServerName.
func resolveUpstreamTLS(hostname string, overrides ...*tls.Config) *tls.Config {
if len(overrides) > 0 && overrides[0] != nil {
return overrides[0]
}
cfg := &tls.Config{ServerName: hostname}
if roots, err := loadUpstreamRootCAs(); err == nil {
cfg.RootCAs = roots
}
return cfg
}
func loadUpstreamRootCAs() (*x509.CertPool, error) {
upstreamRootCAsOnce.Do(func() {
upstreamRootCAs, upstreamRootCAsErr = x509.SystemCertPool()
})
return upstreamRootCAs, upstreamRootCAsErr
}
// SecretHostMatcher provides O(1) lookup for whether a hostname has secrets.
type SecretHostMatcher struct {
exactHosts map[string]bool
wildcardSuffixes []string
secrets []SecretConfig
}
// NewSecretHostMatcher builds a matcher from secret configs.
func NewSecretHostMatcher(secrets []SecretConfig) *SecretHostMatcher {
m := &SecretHostMatcher{
exactHosts: make(map[string]bool),
secrets: secrets,
}
for _, s := range secrets {
for _, host := range s.Hosts {
h := strings.ToLower(host)
if strings.HasPrefix(h, "*.") {
suffix := h[1:] // e.g., ".openai.com"
m.wildcardSuffixes = append(m.wildcardSuffixes, suffix)
} else {
m.exactHosts[h] = true
}
}
}
return m
}
// matchesWildcard checks if hostname matches a wildcard suffix (e.g., ".foo.com").
// Only single-level subdomains match: "bar.foo.com" matches but "sub.bar.foo.com" doesn't.
func matchesWildcard(hostname, suffix string) bool {
return strings.HasSuffix(hostname, suffix) &&
!strings.Contains(hostname[:len(hostname)-len(suffix)], ".")
}
// Matches returns true if hostname has associated secrets.
func (m *SecretHostMatcher) Matches(hostname string) bool {
h := strings.ToLower(hostname)
if m.exactHosts[h] {
return true
}
for _, suffix := range m.wildcardSuffixes {
if matchesWildcard(h, suffix) {
return true
}
}
return false
}
// SecretsForHost returns all secrets whose Hosts list includes hostname.
func (m *SecretHostMatcher) SecretsForHost(hostname string) []SecretConfig {
h := strings.ToLower(hostname)
var result []SecretConfig
for _, s := range m.secrets {
for _, host := range s.Hosts {
host = strings.ToLower(host)
if host == h {
result = append(result, s)
break
}
if strings.HasPrefix(host, "*.") && matchesWildcard(h, host[1:]) {
result = append(result, s)
break
}
}
}
return result
}