Files
archie/internal/infrastructure/rpctls/rpctls_test.go
T
sam cf3455ef2e feat(rpc): mTLS between services from operator-issued certificates
Replace the service bearer tokens with [tls] ca_file and cert_dir. Caller
identity comes from the verified certificate, not metadata. Without TLS,
services listen and dial on loopback only. Task containers get only the CA
and keep their grant.
2026-10-16 02:37:51 +11:00

172 lines
5.8 KiB
Go

package rpctls
import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"math/big"
"net"
"os"
"path/filepath"
"testing"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/health"
healthpb "google.golang.org/grpc/health/grpc_health_v1"
"google.golang.org/grpc/test/bufconn"
)
// TestHandshake pins the transport boundary: who may connect, and the
// identity the server sees.
func TestHandshake(t *testing.T) {
dir := t.TempDir()
ca := newCA(t, dir, "ca")
foreign := newCA(t, dir, "foreign")
ca.issue(t, dir, "archie-state-store")
ca.issue(t, dir, "archied")
foreignDir := filepath.Join(dir, "foreign-certs")
foreign.issue(t, foreignDir, "archied")
server := load(t, ca.path, dir, "archie-state-store")
daemon := load(t, ca.path, dir, "archied")
impostor := load(t, ca.path, foreignDir, "archied")
tests := []struct {
name string
optionalClient bool
dial func(target string) (grpc.DialOption, error)
wantService string
wantTrusted bool
wantErr bool
}{
{"service certificate names the caller", false, func(tg string) (grpc.DialOption, error) { return daemon.DialOption(tg, "archie-state-store") }, "archied", true, false},
{"foreign CA is refused", false, func(tg string) (grpc.DialOption, error) { return impostor.DialOption(tg, "archie-state-store") }, "", false, true},
{"no certificate where one is required", false, func(tg string) (grpc.DialOption, error) { return CAOnlyDialOption(ca.pem, tg, "archie-state-store") }, "", false, true},
{"no certificate where it is optional is untrusted", true, func(tg string) (grpc.DialOption, error) { return CAOnlyDialOption(ca.pem, tg, "archie-state-store") }, "", false, false},
{"wrong server name is refused", false, func(tg string) (grpc.DialOption, error) { return daemon.DialOption(tg, "archie-gateway") }, "", false, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
creds, err := server.ServerOption("127.0.0.1:0", tt.optionalClient)
if err != nil {
t.Fatal(err)
}
var gotService string
var gotTrusted bool
srv := grpc.NewServer(creds, grpc.UnaryInterceptor(func(ctx context.Context, req any, _ *grpc.UnaryServerInfo, h grpc.UnaryHandler) (any, error) {
gotService, gotTrusted = PeerService(ctx), Trusted(ctx)
return h(ctx, req)
}))
healthpb.RegisterHealthServer(srv, health.NewServer())
lis := bufconn.Listen(1 << 16)
go func() { _ = srv.Serve(lis) }()
t.Cleanup(srv.Stop)
dialCreds, err := tt.dial("127.0.0.1:1")
if err != nil {
t.Fatal(err)
}
conn, err := grpc.NewClient("passthrough:///bufnet", dialCreds,
grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { return lis.DialContext(ctx) }))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = conn.Close() })
ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
defer cancel()
_, err = healthpb.NewHealthClient(conn).Check(ctx, &healthpb.HealthCheckRequest{})
if (err != nil) != tt.wantErr {
t.Fatalf("err = %v, wantErr %v", err, tt.wantErr)
}
if gotService != tt.wantService || gotTrusted != tt.wantTrusted {
t.Fatalf("service %q trusted %v, want %q %v", gotService, gotTrusted, tt.wantService, tt.wantTrusted)
}
})
}
var plaintext *Identity
if _, err := plaintext.DialOption("10.0.0.1:9090", "archie-state-store"); err == nil {
t.Fatal("plaintext dial to a non-loopback target was allowed")
}
if _, err := plaintext.ServerOption("0.0.0.0:9090", false); err == nil {
t.Fatal("plaintext listener on a non-loopback address was allowed")
}
}
type testCA struct {
cert *x509.Certificate
key *ecdsa.PrivateKey
pem []byte
path string
}
func newCA(t *testing.T, dir, name string) testCA {
t.Helper()
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
tmpl := &x509.Certificate{
SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: name},
NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour),
IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign,
}
der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
if err != nil {
t.Fatal(err)
}
cert, _ := x509.ParseCertificate(der)
p := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})
path := filepath.Join(dir, name+"-ca.pem")
write(t, path, p)
return testCA{cert: cert, key: key, pem: p, path: path}
}
func (c testCA) issue(t *testing.T, dir, service string) {
t.Helper()
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
tmpl := &x509.Certificate{
SerialNumber: big.NewInt(2), Subject: pkix.Name{CommonName: service}, DNSNames: []string{service},
NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour),
KeyUsage: x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},
}
der, err := x509.CreateCertificate(rand.Reader, tmpl, c.cert, &key.PublicKey, c.key)
if err != nil {
t.Fatal(err)
}
keyDER, err := x509.MarshalECPrivateKey(key)
if err != nil {
t.Fatal(err)
}
write(t, filepath.Join(dir, service+".pem"), pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}))
write(t, filepath.Join(dir, service+"-key.pem"), pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER}))
}
func load(t *testing.T, caFile, certDir, service string) *Identity {
t.Helper()
id, err := Load(caFile, certDir, service)
if err != nil {
t.Fatal(err)
}
return id
}
func write(t *testing.T, path string, data []byte) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, data, 0o600); err != nil {
t.Fatal(err)
}
}