Closes the mTLS-enabled half of docs/THREAT-MODEL.md's "Known gaps" item 2: with mTLS disabled (the default) nothing bound a gRPC caller's transport identity to the source_service string its AppendRequest claimed, so a compromised agent calling audit-log.Append directly with source_service: "ledger-core" could forge an entry that looked authoritative. Added pkg/mtls.PeerCommonName (extracts the verified leaf cert's CommonName from a gRPC context, ok=false for any non-mTLS peer) and wired it into audit-log's Append: when a verified identity is present it overrides the claimed source_service outright, rather than merely checking it. The mTLS-disabled case is unavoidable and stays exactly as documented. Full go test suite green across every module; THREAT-MODEL.md's gap #2 and the earlier-stale gap #4 entry updated to match what the code actually does today. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
255 lines
9.1 KiB
Go
255 lines
9.1 KiB
Go
// Package mtls wires mutual-TLS credentials for gRPC servers and clients
|
|
// shared between every internal Ration service (gateway, agent, cli,
|
|
// tui, audit-log — ledger-core's Rust server has its own analogous
|
|
// loader, see services/ledger-core/src/mtls.rs, driven by the same
|
|
// cert/key/CA files).
|
|
//
|
|
// Design mirrors every other mock/live toggle already in this repo
|
|
// (AIRWALLEX_MODE, for example): mTLS is opt-in and defaults to
|
|
// disabled, so local dev and the demo script keep working with zero
|
|
// certs on disk. Set <PREFIX>_MTLS_ENABLED=true and point the
|
|
// <PREFIX>_MTLS_* vars at files generated by infra/dev-ca/ (or a real
|
|
// PKI in a non-dev deployment) to require it.
|
|
//
|
|
// When enabled:
|
|
// - Servers require and verify a client certificate signed by the
|
|
// configured CA (tls.RequireAndVerifyClientCert) — a service that
|
|
// cannot present a cert signed by the shared internal CA cannot
|
|
// open a connection at all, regardless of what it sends at the
|
|
// gRPC layer.
|
|
// - Clients verify the server's certificate against the same CA and
|
|
// present their own client certificate, so the handshake is mutual
|
|
// in both directions.
|
|
//
|
|
// This package deliberately does not implement any kind of
|
|
// certificate-based *authorization* (e.g. "only card-issuance may call
|
|
// ApplyEntry") — it only establishes a strongly-authenticated transport
|
|
// between services that are already trusted to call each other's RPCs.
|
|
// See docs/THREAT-MODEL.md for what this is, and is not, a defense
|
|
// against.
|
|
package mtls
|
|
|
|
import (
|
|
"context"
|
|
"crypto/tls"
|
|
"crypto/x509"
|
|
"fmt"
|
|
"os"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"google.golang.org/grpc"
|
|
"google.golang.org/grpc/credentials"
|
|
"google.golang.org/grpc/credentials/insecure"
|
|
"google.golang.org/grpc/peer"
|
|
)
|
|
|
|
// Config holds one service's TLS identity (cert/key) and the CA used to
|
|
// verify the identity of whoever it talks to. The zero value is "mTLS
|
|
// disabled" — every constructor in this package treats a disabled
|
|
// Config as a request to fall back to plaintext transport credentials,
|
|
// never as an error, so callers can wire this unconditionally.
|
|
type Config struct {
|
|
Enabled bool
|
|
|
|
// CertFile/KeyFile are this service's own leaf certificate and
|
|
// private key, signed by the CA in CAFile.
|
|
CertFile string
|
|
KeyFile string
|
|
|
|
// CAFile is the CA certificate (PEM) used to verify peers: the
|
|
// internal dev CA from infra/dev-ca/ in local/demo deployments, or
|
|
// a real internal CA's root/intermediate in a production one.
|
|
CAFile string
|
|
|
|
// ServerName overrides the name a client verifies the server's
|
|
// certificate against (tls.Config.ServerName). Required when
|
|
// dialing by bare IP or a Docker/Kubernetes service name that
|
|
// doesn't match the certificate's SAN exactly; leave empty to use
|
|
// whatever go-grpc derives from the dial target.
|
|
ServerName string
|
|
}
|
|
|
|
// WithDefaultServerName returns a copy of c with ServerName set to name
|
|
// when c.ServerName is empty, unchanged otherwise. Lets a client that
|
|
// dials several different peers (e.g. the agent dialing both
|
|
// ledger-core and gateway with the one <PREFIX>_MTLS_* identity it was
|
|
// issued) pick the right per-peer SAN to verify against without
|
|
// mutating the shared Config each dial starts from, while still
|
|
// honoring an operator-supplied <PREFIX>_MTLS_SERVER_NAME override if
|
|
// one was set.
|
|
func (c Config) WithDefaultServerName(name string) Config {
|
|
if c.ServerName != "" {
|
|
return c
|
|
}
|
|
c.ServerName = name
|
|
return c
|
|
}
|
|
|
|
// envPrefix is the per-service environment variable prefix convention:
|
|
// <PREFIX>_MTLS_ENABLED, <PREFIX>_MTLS_CERT_FILE, <PREFIX>_MTLS_KEY_FILE,
|
|
// <PREFIX>_MTLS_CA_FILE, <PREFIX>_MTLS_SERVER_NAME.
|
|
func envKey(prefix, suffix string) string {
|
|
return strings.ToUpper(prefix) + "_MTLS_" + suffix
|
|
}
|
|
|
|
// LoadFromEnv reads a Config for the given service prefix (e.g.
|
|
// "GATEWAY", "LEDGER_CORE", "AUDIT_LOG") from the process environment.
|
|
// Returns a disabled Config, not an error, when <PREFIX>_MTLS_ENABLED
|
|
// is unset or "false" — mTLS is opt-in. Returns an error if it is
|
|
// enabled but any of CERT_FILE/KEY_FILE/CA_FILE is missing, since a
|
|
// half-configured mTLS setup is worse than refusing to start.
|
|
func LoadFromEnv(prefix string) (Config, error) {
|
|
enabled, err := parseBool(os.Getenv(envKey(prefix, "ENABLED")))
|
|
if err != nil {
|
|
return Config{}, fmt.Errorf("mtls: invalid %s: %w", envKey(prefix, "ENABLED"), err)
|
|
}
|
|
cfg := Config{
|
|
Enabled: enabled,
|
|
CertFile: os.Getenv(envKey(prefix, "CERT_FILE")),
|
|
KeyFile: os.Getenv(envKey(prefix, "KEY_FILE")),
|
|
CAFile: os.Getenv(envKey(prefix, "CA_FILE")),
|
|
ServerName: os.Getenv(envKey(prefix, "SERVER_NAME")),
|
|
}
|
|
if !enabled {
|
|
return cfg, nil
|
|
}
|
|
missing := []string{}
|
|
if cfg.CertFile == "" {
|
|
missing = append(missing, envKey(prefix, "CERT_FILE"))
|
|
}
|
|
if cfg.KeyFile == "" {
|
|
missing = append(missing, envKey(prefix, "KEY_FILE"))
|
|
}
|
|
if cfg.CAFile == "" {
|
|
missing = append(missing, envKey(prefix, "CA_FILE"))
|
|
}
|
|
if len(missing) > 0 {
|
|
return Config{}, fmt.Errorf("mtls: %s requires env vars: %v", envKey(prefix, "ENABLED"), missing)
|
|
}
|
|
return cfg, nil
|
|
}
|
|
|
|
func parseBool(v string) (bool, error) {
|
|
if v == "" {
|
|
return false, nil
|
|
}
|
|
return strconv.ParseBool(v)
|
|
}
|
|
|
|
// loadCertAndCA reads the leaf cert/key pair and CA pool common to both
|
|
// server and client setup.
|
|
func (c Config) loadCertAndCA() (tls.Certificate, *x509.CertPool, error) {
|
|
cert, err := tls.LoadX509KeyPair(c.CertFile, c.KeyFile)
|
|
if err != nil {
|
|
return tls.Certificate{}, nil, fmt.Errorf("mtls: load key pair (cert=%s key=%s): %w", c.CertFile, c.KeyFile, err)
|
|
}
|
|
caPEM, err := os.ReadFile(c.CAFile)
|
|
if err != nil {
|
|
return tls.Certificate{}, nil, fmt.Errorf("mtls: read CA file %s: %w", c.CAFile, err)
|
|
}
|
|
pool := x509.NewCertPool()
|
|
if !pool.AppendCertsFromPEM(caPEM) {
|
|
return tls.Certificate{}, nil, fmt.Errorf("mtls: CA file %s contained no usable certificates", c.CAFile)
|
|
}
|
|
return cert, pool, nil
|
|
}
|
|
|
|
// ServerTLSConfig builds the *tls.Config a gRPC server should present:
|
|
// its own identity, and tls.RequireAndVerifyClientCert against the
|
|
// shared CA so only callers holding a cert signed by that CA can
|
|
// complete the handshake.
|
|
func (c Config) ServerTLSConfig() (*tls.Config, error) {
|
|
cert, pool, err := c.loadCertAndCA()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &tls.Config{
|
|
Certificates: []tls.Certificate{cert},
|
|
ClientCAs: pool,
|
|
ClientAuth: tls.RequireAndVerifyClientCert,
|
|
MinVersion: tls.VersionTLS13,
|
|
}, nil
|
|
}
|
|
|
|
// ClientTLSConfig builds the *tls.Config a gRPC client should dial
|
|
// with: its own identity (presented if the server requests a client
|
|
// cert) and the shared CA used to verify the server's certificate.
|
|
func (c Config) ClientTLSConfig() (*tls.Config, error) {
|
|
cert, pool, err := c.loadCertAndCA()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &tls.Config{
|
|
Certificates: []tls.Certificate{cert},
|
|
RootCAs: pool,
|
|
ServerName: c.ServerName,
|
|
MinVersion: tls.VersionTLS13,
|
|
}, nil
|
|
}
|
|
|
|
// ServerOption returns the grpc.ServerOption to pass to grpc.NewServer.
|
|
// When c.Enabled is false it returns plaintext (insecure) credentials
|
|
// rather than an error — see the package doc for why that's the
|
|
// intended default.
|
|
func (c Config) ServerOption() (grpc.ServerOption, error) {
|
|
if !c.Enabled {
|
|
return grpc.Creds(insecure.NewCredentials()), nil
|
|
}
|
|
tlsCfg, err := c.ServerTLSConfig()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return grpc.Creds(credentials.NewTLS(tlsCfg)), nil
|
|
}
|
|
|
|
// PeerCommonName extracts the CommonName of the verified leaf
|
|
// certificate the caller presented on this gRPC call, if any. It
|
|
// returns ok=false whenever there is no cryptographically-verified
|
|
// peer identity to report — a plaintext connection (mTLS disabled, the
|
|
// default), a TLS connection that isn't mutual, or a call made outside
|
|
// a gRPC server handler entirely — never a zero-value CommonName
|
|
// mistaken for a real one.
|
|
//
|
|
// This is the building block for closing docs/THREAT-MODEL.md's
|
|
// "Known gaps" item 2 (audit-log trusting a client-claimed
|
|
// source_service verbatim): a handler can call this once mTLS makes a
|
|
// verified identity available and bind an attacker-controlled field to
|
|
// the transport-authenticated one instead of trusting it blindly. It
|
|
// deliberately does not fall back to anything client-supplied — the
|
|
// whole point is that this value, when present, did not come from a
|
|
// request field an attacker controls.
|
|
func PeerCommonName(ctx context.Context) (string, bool) {
|
|
p, ok := peer.FromContext(ctx)
|
|
if !ok || p.AuthInfo == nil {
|
|
return "", false
|
|
}
|
|
tlsInfo, ok := p.AuthInfo.(credentials.TLSInfo)
|
|
if !ok {
|
|
return "", false
|
|
}
|
|
chains := tlsInfo.State.PeerCertificates
|
|
if len(chains) == 0 {
|
|
return "", false
|
|
}
|
|
cn := chains[0].Subject.CommonName
|
|
if cn == "" {
|
|
return "", false
|
|
}
|
|
return cn, true
|
|
}
|
|
|
|
// DialOption returns the grpc.DialOption to pass to grpc.NewClient (or
|
|
// grpc.DialContext). When c.Enabled is false it returns plaintext
|
|
// (insecure) credentials — see the package doc.
|
|
func (c Config) DialOption() (grpc.DialOption, error) {
|
|
if !c.Enabled {
|
|
return grpc.WithTransportCredentials(insecure.NewCredentials()), nil
|
|
}
|
|
tlsCfg, err := c.ClientTLSConfig()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return grpc.WithTransportCredentials(credentials.NewTLS(tlsCfg)), nil
|
|
}
|