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.
This commit is contained in:
sam committed 2026-10-16 02:37:51 +11:00
1 parent 88ef6ca5b2
commit 53c95038de
51 files changed
+746 -689

No files matched your search

@@ -39,6 +39,9 @@ type Config struct {
StateStoreURL string
StateStoreToken string
// StateStoreCA is the PEM CA the State Store's certificate chains to.
// Empty dials plaintext, which only a loopback target allows.
StateStoreCA []byte
}
const (
@@ -96,7 +99,7 @@ func Connect(ctx context.Context, config Config, log *slog.Logger) (*Transport,
conn.Close()
return nil, fmt.Errorf("state store target is required: archie-agent no longer supports the legacy NATS storerpc path (docs/prds/state-store-contract.md §12 step 4)")
}
state, closeState, err := staterpc.Dial(config.StateStoreURL, "archie-agent", config.StateStoreToken)
state, closeState, err := staterpc.DialTask(config.StateStoreURL, config.StateStoreCA, config.StateStoreToken)
if err != nil {
conn.Close()
return nil, fmt.Errorf("connect state store: %w", err)
@@ -114,6 +114,7 @@ func (h *Host) Start(ctx context.Context, spec Spec, surface string, impl goplug
Cmd: cmd,
AllowedProtocols: []goplugin.Protocol{goplugin.ProtocolGRPC},
SkipHostEnv: true,
AutoMTLS: true,
Logger: h.log.Named(spec.Name),
})}
rpc, err := p.client.Client()
+6 -82
View File
@@ -2,94 +2,18 @@ package gatewayrpc
import (
"context"
"crypto/subtle"
"net"
"strings"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"github.com/samcharles93/archie-core/internal/infrastructure/rpcidentity"
)
// tokenMetadataKey is the gRPC metadata key the Gateway Bearer [REDACTED]
// travels in. Metadata, never a URL, mirroring the State Store's
// token lifecycle.
const tokenMetadataKey = "gateway-token"
// TargetIsLoopback reports whether addr's host is a loopback IP or
// "localhost".
func TargetIsLoopback(addr string) (bool, error) {
host, _, err := net.SplitHostPort(addr)
if err != nil {
return false, err
}
if strings.EqualFold(host, "localhost") {
return true, nil
}
ip := net.ParseIP(host)
if ip == nil {
return false, nil
}
return ip.IsLoopback(), nil
// unaryPrincipal forwards the context's principal on every unary call.
func unaryPrincipal(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
return invoker(rpcidentity.Outgoing(ctx, "gateway-client"), method, req, reply, cc, opts...)
}
// validToken compares candidate against the configured token in constant
// time so a timing side channel cannot leak how many bytes matched.
func validToken(token, candidate string) bool {
if token == "" || candidate == "" {
return false
}
return subtle.ConstantTimeCompare([]byte(token), []byte(candidate)) == 1
}
// UnaryServerInterceptor validates the Bearer [REDACTED] carried in each unary
// call's metadata, returning codes.Unauthenticated on a missing or wrong
// token. It is installed only for a non-loopback listener; a loopback
// listener serves with no interceptors.
func UnaryServerInterceptor(token string) grpc.UnaryServerInterceptor {
return func(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return nil, status.Error(codes.Unauthenticated, "missing gateway token")
}
values := md.Get(tokenMetadataKey)
if len(values) == 0 || !validToken(token, values[0]) {
return nil, status.Error(codes.Unauthenticated, "missing or invalid gateway token")
}
return handler(ctx, req)
}
}
// StreamServerInterceptor is the streaming counterpart of
// UnaryServerInterceptor: the chat Stream RPC is server-streaming, so its
// credential must be checked on the stream context as well.
func StreamServerInterceptor(token string) grpc.StreamServerInterceptor {
return func(srv any, stream grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
md, _ := metadata.FromIncomingContext(stream.Context())
values := md.Get(tokenMetadataKey)
if len(values) == 0 || !validToken(token, values[0]) {
return status.Error(codes.Unauthenticated, "missing or invalid gateway token")
}
return handler(srv, stream)
}
}
// UnaryClientTokenInterceptor attaches token to every outgoing unary call's
// metadata under tokenMetadataKey.
func UnaryClientTokenInterceptor(token string) grpc.UnaryClientInterceptor {
return func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
return invoker(metadata.AppendToOutgoingContext(rpcidentity.Outgoing(ctx, "gateway-client"), tokenMetadataKey, token), method, req, reply, cc, opts...)
}
}
// StreamClientTokenInterceptor attaches token to the outgoing stream's
// context, covering the chat Stream RPC that the unary interceptor cannot
// see.
func StreamClientTokenInterceptor(token string) grpc.StreamClientInterceptor {
return func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {
return streamer(metadata.AppendToOutgoingContext(rpcidentity.Outgoing(ctx, "gateway-client"), tokenMetadataKey, token), desc, cc, method, opts...)
}
// streamPrincipal forwards the context's principal on every stream.
func streamPrincipal(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {
return streamer(rpcidentity.Outgoing(ctx, "gateway-client"), desc, cc, method, opts...)
}
+12 -20
View File
@@ -5,34 +5,26 @@ import (
"strings"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"github.com/samcharles93/archie-core/internal/domain/presence"
"github.com/samcharles93/archie-core/internal/infrastructure/rpctls"
)
// Dial returns a Gateway chat client for target. A loopback target dials
// insecure; any other target requires a token. The cleanup closes the
// connection.
func Dial(target, token string, options ...grpc.DialOption) (*Client, func(), error) {
// Dial returns a Gateway chat client for target, authenticated by id. The
// cleanup closes the connection.
func Dial(target string, id *rpctls.Identity, options ...grpc.DialOption) (*Client, func(), error) {
target = strings.TrimSpace(target)
if target == "" {
return nil, nil, fmt.Errorf("gateway target is required")
}
loopback, err := TargetIsLoopback(target)
creds, err := id.DialOption(target, presence.Gateway)
if err != nil {
return nil, nil, fmt.Errorf("gateway target must be host:port: %w", err)
return nil, nil, fmt.Errorf("gateway: %w", err)
}
if !loopback && token == "" {
return nil, nil, fmt.Errorf(
"gateway target %q is non-loopback; non-loopback exposure requires a Bearer [REDACTED] ([services.gateway].target_token / GATEWAY_TOKEN) or TLS",
target,
)
}
opts := []grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())}
if token != "" {
opts = append(
opts,
grpc.WithUnaryInterceptor(UnaryClientTokenInterceptor(token)),
grpc.WithStreamInterceptor(StreamClientTokenInterceptor(token)),
)
opts := []grpc.DialOption{
creds,
grpc.WithUnaryInterceptor(unaryPrincipal),
grpc.WithStreamInterceptor(streamPrincipal),
}
conn, err := grpc.NewClient(target, append(opts, options...)...)
if err != nil {
@@ -6,7 +6,6 @@ package harnessrpc
import (
"context"
"crypto/subtle"
"errors"
"fmt"
"io"
@@ -14,43 +13,33 @@ import (
"sync"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
pb "github.com/samcharles93/archie-core/internal/contracts/harness/v1"
"github.com/samcharles93/archie-core/internal/domain/presence"
"github.com/samcharles93/archie-core/internal/infrastructure/rpctls"
)
// tokenMetadataKey is the gRPC metadata key the harness service token travels
// in, mirroring the Gateway's and State Store's token keys.
const tokenMetadataKey = "harness-token"
// Client opens sessions against a daemon's HarnessService.
type Client struct {
svc pb.HarnessServiceClient
}
// Dial returns a harness client for target. The token is required for every
// target, loopback included: the daemon's listener enforces it because a
// session is a shell in a container that holds an org's credential. The
// cleanup closes the connection.
func Dial(target, token string, options ...grpc.DialOption) (*Client, func(), error) {
// Dial returns a harness client for target. A session is a shell in a
// container that holds an org's credential, so it needs a service
// certificate even on loopback. The cleanup closes the connection.
func Dial(target string, id *rpctls.Identity, options ...grpc.DialOption) (*Client, func(), error) {
target = strings.TrimSpace(target)
if target == "" {
return nil, nil, errors.New("harness target is required")
}
if token == "" {
return nil, nil, fmt.Errorf(
"harness target %q reads a setup session, so it needs a bearer token ([services.harness].target_token / HARNESS_TOKEN)",
target,
)
if id == nil {
return nil, nil, errors.New("harness sessions need [tls] ca_file and cert_dir")
}
opts := []grpc.DialOption{
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithStreamInterceptor(streamClientToken(token)),
creds, err := id.DialOption(target, presence.Daemon)
if err != nil {
return nil, nil, fmt.Errorf("harness: %w", err)
}
conn, err := grpc.NewClient(target, append(opts, options...)...)
conn, err := grpc.NewClient(target, append([]grpc.DialOption{creds}, options...)...)
if err != nil {
return nil, nil, fmt.Errorf("create harness client: %w", err)
}
@@ -169,40 +158,3 @@ func (s *session) Close() error {
s.cancel()
return nil
}
// validToken compares candidate against the configured token in constant
// time.
func validToken(token, candidate string) bool {
if token == "" || candidate == "" {
return false
}
return subtle.ConstantTimeCompare([]byte(token), []byte(candidate)) == 1
}
// StreamServerInterceptor validates the harness token on a stream. The
// session RPC is bidi, so this is the interceptor that matters. Unlike the
// State Store, a loopback listener enforces it too: a session is a shell in a
// container that holds an org's credential.
func StreamServerInterceptor(token string) grpc.StreamServerInterceptor {
return func(srv any, stream grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
if !validContextToken(stream.Context(), token) {
return status.Error(codes.Unauthenticated, "missing or invalid harness token")
}
return handler(srv, stream)
}
}
func validContextToken(ctx context.Context, token string) bool {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return false
}
values := md.Get(tokenMetadataKey)
return len(values) > 0 && validToken(token, values[0])
}
func streamClientToken(token string) grpc.StreamClientInterceptor {
return func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {
return streamer(metadata.AppendToOutgoingContext(ctx, tokenMetadataKey, token), desc, cc, method, opts...)
}
}
+4
View File
@@ -17,6 +17,7 @@ type Endpoints struct {
NATSToken string
StateStore string
StateStoreToken string
StateStoreCA []byte
}
// WorkerEnv is the worker's entire environment in a Kit container: NATS and
@@ -36,6 +37,9 @@ func WorkerEnv(e Endpoints, uid, gid int) ([]string, error) {
if e.StateStoreToken != "" {
env = append(env, "STATE_STORE_TOKEN="+e.StateStoreToken)
}
if len(e.StateStoreCA) > 0 {
env = append(env, "STATE_STORE_CA="+string(e.StateStoreCA))
}
}
return append(env, "WORKTREE_UID="+strconv.Itoa(uid), "WORKTREE_GID="+strconv.Itoa(gid)), nil
}
@@ -5,24 +5,20 @@ package messagingrpc
import (
"context"
"crypto/subtle"
"errors"
"fmt"
"strings"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
pb "github.com/samcharles93/archie-core/internal/contracts/messaging/v1"
"github.com/samcharles93/archie-core/internal/infrastructure/gatewayrpc"
"github.com/samcharles93/archie-core/internal/domain/presence"
"github.com/samcharles93/archie-core/internal/infrastructure/rpctls"
"github.com/samcharles93/archie-core/internal/logging"
)
const tokenMetadataKey = "messaging-token"
// ErrUnavailable marks a delivery the channel could not make now: the channel
// is unknown, stopped or cannot send. The caller may retry later.
var ErrUnavailable = errors.New("messaging: channel unavailable")
@@ -58,52 +54,26 @@ func (s *server) Deliver(ctx context.Context, req *pb.DeliverRequest) (*pb.Deliv
}
}
// ServerOptions serves a loopback listen address without credentials and
// requires token on any other, failing closed when it is empty.
func ServerOptions(listen, token string) ([]grpc.ServerOption, error) {
loopback, err := gatewayrpc.TargetIsLoopback(listen)
// ServerOptions serves listen with id's credentials.
func ServerOptions(listen string, id *rpctls.Identity) ([]grpc.ServerOption, error) {
creds, err := id.ServerOption(listen, false)
if err != nil {
return nil, err
}
if loopback {
return nil, nil
}
if token == "" {
return nil, fmt.Errorf("messaging listen address %q is non-loopback and requires a bearer token", listen)
}
return []grpc.ServerOption{grpc.ChainUnaryInterceptor(requireToken(token))}, nil
}
func requireToken(token string) grpc.UnaryServerInterceptor {
return func(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
values := metadata.ValueFromIncomingContext(ctx, tokenMetadataKey)
if len(values) == 0 || subtle.ConstantTimeCompare([]byte(token), []byte(values[0])) != 1 {
return nil, status.Error(codes.Unauthenticated, "missing or invalid messaging token")
}
return handler(ctx, req)
return nil, fmt.Errorf("messaging: %w", err)
}
return []grpc.ServerOption{creds}, nil
}
// Client delivers through a dialled MessagingService.
type Client struct{ rpc pb.MessagingServiceClient }
// Dial returns a client for target. A non-loopback target requires token.
func Dial(target, token string) (*Client, func(), error) {
// Dial returns a client for target, authenticated by id.
func Dial(target string, id *rpctls.Identity) (*Client, func(), error) {
target = strings.TrimSpace(target)
loopback, err := gatewayrpc.TargetIsLoopback(target)
creds, err := id.DialOption(target, presence.Messaging)
if err != nil {
return nil, nil, fmt.Errorf("messaging target must be host:port: %w", err)
return nil, nil, fmt.Errorf("messaging: %w", err)
}
if !loopback && token == "" {
return nil, nil, fmt.Errorf("messaging target %q is non-loopback and requires a bearer token ([services.messaging].target_token / MESSAGING_TOKEN)", target)
}
opts := []grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())}
if token != "" {
opts = append(opts, grpc.WithUnaryInterceptor(func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
return invoker(metadata.AppendToOutgoingContext(ctx, tokenMetadataKey, token), method, req, reply, cc, opts...)
}))
}
conn, err := grpc.NewClient(target, opts...)
conn, err := grpc.NewClient(target, creds)
if err != nil {
return nil, nil, fmt.Errorf("create messaging client: %w", err)
}
@@ -1,36 +0,0 @@
package messagingrpc
import (
"context"
"testing"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
func TestRequireToken(t *testing.T) {
ok := func(context.Context, any) (any, error) { return "served", nil }
for _, tc := range []struct {
name string
md metadata.MD
want codes.Code
}{
{"valid", metadata.Pairs(tokenMetadataKey, "secret"), codes.OK},
{"wrong", metadata.Pairs(tokenMetadataKey, "secrex"), codes.Unauthenticated},
{"missing", metadata.MD{}, codes.Unauthenticated},
{"other service's key", metadata.Pairs("gateway-token", "secret"), codes.Unauthenticated},
} {
t.Run(tc.name, func(t *testing.T) {
ctx := metadata.NewIncomingContext(context.Background(), tc.md)
_, err := requireToken("secret")(ctx, nil, &grpc.UnaryServerInfo{}, ok)
if got := status.Code(err); got != tc.want {
t.Fatalf("code = %v, want %v", got, tc.want)
}
})
}
if _, err := ServerOptions("0.0.0.0:8586", ""); err == nil {
t.Fatal("non-loopback listen with no token was accepted")
}
}
@@ -13,6 +13,7 @@ import (
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/domain/presence"
"github.com/samcharles93/archie-core/internal/infrastructure/rpctls"
)
// CallerKey names the service making the call.
@@ -34,10 +35,10 @@ func Outgoing(ctx context.Context, caller string) context.Context {
return metadata.NewOutgoingContext(ctx, md)
}
// Callers resolves who a call is made by. It runs after authentication,
// which is what makes the metadata trustworthy: only holders of the instance
// credential reach it with their metadata intact (a task grant's is
// stripped). A call naming a principal acts in, and reads only, that principal's
// Callers resolves who a call is made by. It runs after authentication:
// the caller is the verified certificate's service, else (a plaintext
// loopback peer) the metadata's claim, and a task grant's metadata is
// stripped before it gets here. A call naming a principal acts in, and reads only, that principal's
// org; any other acts in the default org.
type Callers struct {
Principals access.PrincipalSource
@@ -45,7 +46,10 @@ type Callers struct {
func (c Callers) resolve(ctx context.Context) (context.Context, error) {
md, _ := metadata.FromIncomingContext(ctx)
caller := first(md, CallerKey)
caller := rpctls.PeerService(ctx)
if caller == "" {
caller = first(md, CallerKey)
}
if caller != "" {
ctx = access.WithActor(access.WithSource(ctx, caller), caller)
}
+204
View File
@@ -0,0 +1,204 @@
// Package rpctls builds the transport credentials every gRPC hop uses from
// certificate files the operator's PKI issues. With no identity configured a
// process speaks plaintext, and only over loopback.
package rpctls
import (
"context"
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"net"
"os"
"path/filepath"
"strings"
"sync"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/peer"
)
// Identity is one process's certificate and the CA it trusts. A nil Identity
// is the plaintext loopback mode.
type Identity struct {
pool *x509.CertPool
caPEM []byte
cert *certFile
}
// Load reads the CA at caFile and service's key pair from
// certDir/<service>.pem and certDir/<service>-key.pem. Both paths empty means
// no TLS and returns nil.
func Load(caFile, certDir, service string) (*Identity, error) {
if caFile == "" && certDir == "" {
return nil, nil
}
if caFile == "" || certDir == "" {
return nil, errors.New("tls: ca_file and cert_dir are both required")
}
caPEM, err := os.ReadFile(caFile)
if err != nil {
return nil, fmt.Errorf("tls: read CA: %w", err)
}
pool := x509.NewCertPool()
if !pool.AppendCertsFromPEM(caPEM) {
return nil, fmt.Errorf("tls: %s holds no PEM certificate", caFile)
}
cert := &certFile{
certPath: filepath.Join(certDir, service+".pem"),
keyPath: filepath.Join(certDir, service+"-key.pem"),
}
if _, err := cert.get(); err != nil {
return nil, err
}
return &Identity{pool: pool, caPEM: caPEM, cert: cert}, nil
}
// CAPEM is the CA certificate a container receives to verify the State
// Store. Nil in plaintext mode.
func (i *Identity) CAPEM() []byte {
if i == nil {
return nil
}
return i.caPEM
}
// ServerOption returns the credentials for a listener on listen. A listener
// that accepts calls without a client certificate (the State Store's task
// grants) passes optionalClient; every other listener requires one.
func (i *Identity) ServerOption(listen string, optionalClient bool) (grpc.ServerOption, error) {
if i == nil {
if err := requireLoopback(listen); err != nil {
return nil, err
}
return grpc.Creds(insecure.NewCredentials()), nil
}
auth := tls.RequireAndVerifyClientCert
if optionalClient {
auth = tls.VerifyClientCertIfGiven
}
return grpc.Creds(credentials.NewTLS(&tls.Config{
MinVersion: tls.VersionTLS13,
GetCertificate: func(*tls.ClientHelloInfo) (*tls.Certificate, error) { return i.cert.get() },
ClientCAs: i.pool,
ClientAuth: auth,
})), nil
}
// DialOption returns the credentials for dialling server (its certificate
// name) at target. The name, not target's host, is verified, so a service is
// reachable through any address, relay or proxy.
func (i *Identity) DialOption(target, server string) (grpc.DialOption, error) {
if i == nil {
if err := requireLoopback(target); err != nil {
return nil, err
}
return grpc.WithTransportCredentials(insecure.NewCredentials()), nil
}
return grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{
MinVersion: tls.VersionTLS13,
RootCAs: i.pool,
ServerName: server,
GetClientCertificate: func(*tls.CertificateRequestInfo) (*tls.Certificate, error) { return i.cert.get() },
})), nil
}
// CAOnlyDialOption dials server trusting caPEM and presenting no
// certificate: a container's credentials are its task grant alone. Empty
// caPEM is plaintext, loopback only.
func CAOnlyDialOption(caPEM []byte, target, server string) (grpc.DialOption, error) {
if len(caPEM) == 0 {
var none *Identity
return none.DialOption(target, server)
}
pool := x509.NewCertPool()
if !pool.AppendCertsFromPEM(caPEM) {
return nil, errors.New("tls: CA holds no PEM certificate")
}
return grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{
MinVersion: tls.VersionTLS13,
RootCAs: pool,
ServerName: server,
})), nil
}
// PeerService is the service named by the caller's verified certificate, or
// "" when it presented none.
func PeerService(ctx context.Context) string {
p, ok := peer.FromContext(ctx)
if !ok {
return ""
}
info, ok := p.AuthInfo.(credentials.TLSInfo)
if !ok || len(info.State.VerifiedChains) == 0 || len(info.State.VerifiedChains[0]) == 0 {
return ""
}
if names := info.State.VerifiedChains[0][0].DNSNames; len(names) > 0 {
return names[0]
}
return ""
}
// Trusted reports whether the caller is a service: it holds a verified
// certificate, or reached a plaintext listener, which is loopback only.
func Trusted(ctx context.Context) bool {
p, ok := peer.FromContext(ctx)
if !ok {
return false
}
if _, isTLS := p.AuthInfo.(credentials.TLSInfo); !isTLS {
return true
}
return PeerService(ctx) != ""
}
func requireLoopback(addr string) error {
host, _, err := net.SplitHostPort(addr)
if err != nil {
return fmt.Errorf("address %q must be host:port: %w", addr, err)
}
if strings.EqualFold(host, "localhost") {
return nil
}
if ip := net.ParseIP(host); ip != nil && ip.IsLoopback() {
return nil
}
return fmt.Errorf("%q is not loopback; configure [tls] ca_file and cert_dir to serve or dial it", addr)
}
// certFile reloads a key pair when its certificate file changes, so the
// operator's renewal tooling needs no restart.
type certFile struct {
certPath, keyPath string
mu sync.Mutex
modified time.Time
cert *tls.Certificate
}
func (c *certFile) get() (*tls.Certificate, error) {
info, err := os.Stat(c.certPath)
if err != nil {
return nil, fmt.Errorf("tls: %w", err)
}
c.mu.Lock()
defer c.mu.Unlock()
if c.cert != nil && info.ModTime().Equal(c.modified) {
return c.cert, nil
}
cert, err := tls.LoadX509KeyPair(c.certPath, c.keyPath)
if err != nil {
if c.cert != nil {
// A renewal caught between writing the two files keeps the
// previous pair until both match.
return c.cert, nil
}
return nil, fmt.Errorf("tls: load %s: %w", c.certPath, err)
}
c.cert, c.modified = &cert, info.ModTime()
return c.cert, nil
}
@@ -0,0 +1,171 @@
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)
}
}
+5 -5
View File
@@ -9,7 +9,7 @@ import (
"github.com/samcharles93/archie-core/internal/infrastructure/rpcidentity"
)
// tokenMetadataKey is the gRPC metadata key the bearer token travels in.
// tokenMetadataKey is the gRPC metadata key a task grant travels in.
// Metadata, never a URL.
const tokenMetadataKey = "state-store-token"
@@ -21,16 +21,16 @@ func outgoing(ctx context.Context, caller, token string) context.Context {
return ctx
}
// UnaryClientCredentialInterceptor attaches caller and token to every
// outgoing call.
// UnaryClientCredentialInterceptor attaches caller and any task grant to
// every outgoing call.
func UnaryClientCredentialInterceptor(caller, token string) grpc.UnaryClientInterceptor {
return func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
return invoker(outgoing(ctx, caller, token), method, req, reply, cc, opts...)
}
}
// StreamClientCredentialInterceptor attaches caller and token to every
// outgoing stream.
// StreamClientCredentialInterceptor attaches caller and any task grant to
// every outgoing stream.
func StreamClientCredentialInterceptor(caller, token string) grpc.StreamClientInterceptor {
return func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {
return streamer(outgoing(ctx, caller, token), desc, cc, method, opts...)
@@ -7,7 +7,9 @@ import (
"time"
"google.golang.org/grpc"
grpccreds "google.golang.org/grpc/credentials"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/peer"
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
"github.com/samcharles93/archie-core/internal/domain/access"
@@ -45,10 +47,10 @@ func (p principalsByID) PrincipalFor(_ context.Context, id identity.IdentityID)
return access.Principal{IdentityID: id, Org: p[id]}, nil
}
// TestCallerAttribution pins who a call acts as: the instance credential's
// metadata is trusted, a task grant's is not.
// TestCallerAttribution pins who a call acts as: a trusted service's
// metadata is trusted, a task grant's is not, and a caller with neither a
// certificate nor a grant is refused.
func TestCallerAttribution(t *testing.T) {
const admin = "admin-token"
taskToken := strings.Repeat("ab", 32)
grants := &TaskGrants{Store: credentials{}}
if err := grants.register(context.Background(), 7, taskToken, time.Hour); err != nil {
@@ -56,20 +58,27 @@ func TestCallerAttribution(t *testing.T) {
}
callers := rpcidentity.Callers{Principals: principalsByID{"alice": "acme"}}
update := &grpc.UnaryServerInfo{FullMethod: pb.StateStoreService_Update_FullMethodName}
// A plaintext peer reached a loopback listener; a TLS peer without a
// verified chain presented no client certificate.
plaintext := &peer.Peer{}
noCert := &peer.Peer{AuthInfo: grpccreds.TLSInfo{}}
tests := []struct {
name string
peer *peer.Peer
md []string
wantActor string
wantOrg org.OrgID
wantErr bool
}{
{"service alone acts in the default org", []string{tokenMetadataKey, admin, rpcidentity.CallerKey, "archied"}, "archied", org.DefaultOrgID},
{"forwarded principal sets actor and org", []string{tokenMetadataKey, admin, rpcidentity.CallerKey, "archie-ui", rpcidentity.PrincipalKey, "alice"}, "alice", "acme"},
{"task grant cannot claim a principal", []string{tokenMetadataKey, taskToken, rpcidentity.CallerKey, "archie-ui", rpcidentity.PrincipalKey, "alice"}, "task/7", org.DefaultOrgID},
{"service alone acts in the default org", plaintext, []string{rpcidentity.CallerKey, "archied"}, "archied", org.DefaultOrgID, false},
{"forwarded principal sets actor and org", plaintext, []string{rpcidentity.CallerKey, "archie-ui", rpcidentity.PrincipalKey, "alice"}, "alice", "acme", false},
{"task grant cannot claim a principal", noCert, []string{tokenMetadataKey, taskToken, rpcidentity.CallerKey, "archie-ui", rpcidentity.PrincipalKey, "alice"}, "task/7", org.DefaultOrgID, false},
{"no certificate and no grant is refused", noCert, []string{rpcidentity.CallerKey, "archied"}, "", "", true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctx := metadata.NewIncomingContext(context.Background(), metadata.Pairs(tt.md...))
ctx := peer.NewContext(metadata.NewIncomingContext(context.Background(), metadata.Pairs(tt.md...)), tt.peer)
var gotActor string
var gotOrg org.OrgID
handler := func(ctx context.Context, _ any) (any, error) {
@@ -80,8 +89,9 @@ func TestCallerAttribution(t *testing.T) {
return callers.Unary()(ctx, req, update, handler)
}
req := &pb.UpdateRequest{Task: &pb.Task{Id: 7}}
if _, err := grants.UnaryInterceptor(admin)(ctx, req, update, chained); err != nil {
t.Fatal(err)
_, err := grants.UnaryInterceptor()(ctx, req, update, chained)
if (err != nil) != tt.wantErr {
t.Fatalf("err = %v, wantErr %v", err, tt.wantErr)
}
if gotActor != tt.wantActor || gotOrg != tt.wantOrg {
t.Fatalf("got actor %q org %q, want %q %q", gotActor, gotOrg, tt.wantActor, tt.wantOrg)
+23 -35
View File
@@ -2,45 +2,50 @@ package staterpc
import (
"fmt"
"net"
"strings"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/keepalive"
"github.com/samcharles93/archie-core/internal/domain/presence"
"github.com/samcharles93/archie-core/internal/infrastructure/rpctls"
)
// Dial returns a State Store client for target, attributed to the caller
// service. A loopback target dials insecure; any other target requires a
// token. The cleanup closes the connection.
func Dial(target, caller, token string, options ...grpc.DialOption) (*Client, func(), error) {
// service and authenticated by id. The cleanup closes the connection.
func Dial(target, caller string, id *rpctls.Identity, options ...grpc.DialOption) (*Client, func(), error) {
target = strings.TrimSpace(target)
if target == "" {
return nil, nil, fmt.Errorf("state store target is required")
}
loopback, err := TargetIsLoopback(target)
creds, err := id.DialOption(target, presence.StateStore)
if err != nil {
return nil, nil, fmt.Errorf("state store target must be host:port: %w", err)
return nil, nil, fmt.Errorf("state store: %w", err)
}
if !loopback && token == "" {
return nil, nil, fmt.Errorf(
"state store target %q is non-loopback; non-loopback exposure requires a bearer token ([services.state].target_token / STATE_STORE_TOKEN) or TLS, mirroring the gateway's --listen confinement (docs/prds/state-store-contract.md §9)",
target,
)
return dial(target, creds, caller, "", options)
}
// DialTask returns the client a task container uses: it trusts caPEM and
// presents only the task grant, never a service certificate.
func DialTask(target string, caPEM []byte, grant string) (*Client, func(), error) {
creds, err := rpctls.CAOnlyDialOption(caPEM, target, presence.StateStore)
if err != nil {
return nil, nil, fmt.Errorf("state store: %w", err)
}
return dial(target, creds, presence.Agent, grant, nil)
}
func dial(target string, creds grpc.DialOption, caller, grant string, options []grpc.DialOption) (*Client, func(), error) {
opts := []grpc.DialOption{
grpc.WithTransportCredentials(insecure.NewCredentials()),
creds,
// Keepalive detects a dead peer on an otherwise silent watch stream.
grpc.WithKeepaliveParams(ClientKeepaliveParams()),
// GetInstalledPackage returns the whole layer, which for an extension is
// a plugin binary well past gRPC's default 4 MiB receive limit.
grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(maxPackageResponseBytes)),
// Both call shapes need the credential: the server's interceptors
// guard unary RPCs and the streaming capture reads separately, so a
// unary-only interceptor leaves the streams unauthenticated.
grpc.WithUnaryInterceptor(UnaryClientCredentialInterceptor(caller, token)),
grpc.WithStreamInterceptor(StreamClientCredentialInterceptor(caller, token)),
grpc.WithUnaryInterceptor(UnaryClientCredentialInterceptor(caller, grant)),
grpc.WithStreamInterceptor(StreamClientCredentialInterceptor(caller, grant)),
}
conn, err := grpc.NewClient(target, append(opts, options...)...)
if err != nil {
@@ -82,23 +87,6 @@ func ServerKeepalivePolicy() keepalive.EnforcementPolicy {
}
}
// TargetIsLoopback reports whether addr's host is a loopback IP or
// "localhost".
func TargetIsLoopback(addr string) (bool, error) {
host, _, err := net.SplitHostPort(addr)
if err != nil {
return false, fmt.Errorf("address must be host:port: %w", err)
}
if strings.EqualFold(host, "localhost") {
return true, nil
}
ip := net.ParseIP(host)
if ip == nil {
return false, nil
}
return ip.IsLoopback(), nil
}
// WaitForPeer makes calls to the State Store wait for it to come up
// instead of failing while it is down or restarting. A call that must not
// wait carries its own deadline.
@@ -8,13 +8,15 @@ import (
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
grpccreds "google.golang.org/grpc/credentials"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/peer"
"google.golang.org/grpc/status"
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
)
func TestServiceLogsRequireInstanceCredential(t *testing.T) {
func TestServiceLogsRequireService(t *testing.T) {
run := strings.Repeat("ab", 32)
grants := &TaskGrants{Store: credentials{}}
if err := grants.register(t.Context(), 7, run, time.Hour); err != nil {
@@ -22,15 +24,16 @@ func TestServiceLogsRequireInstanceCredential(t *testing.T) {
}
for _, tt := range []struct {
name, token string
peer *peer.Peer
code codes.Code
}{
{"instance", "admin", codes.OK},
{"task cannot read other services", run, codes.PermissionDenied},
{"anonymous", "", codes.Unauthenticated},
{"service", "", &peer.Peer{}, codes.OK},
{"task cannot read other services", run, &peer.Peer{AuthInfo: grpccreds.TLSInfo{}}, codes.PermissionDenied},
{"anonymous", "", &peer.Peer{AuthInfo: grpccreds.TLSInfo{}}, codes.Unauthenticated},
} {
t.Run(tt.name, func(t *testing.T) {
ctx := metadata.NewIncomingContext(t.Context(), metadata.Pairs(tokenMetadataKey, tt.token))
_, err := grants.UnaryInterceptor("admin")(ctx, &pb.RecentLogsRequest{}, &grpc.UnaryServerInfo{FullMethod: pb.StateStoreService_RecentLogs_FullMethodName}, func(context.Context, any) (any, error) { return &pb.RecentLogsResponse{}, nil })
ctx := peer.NewContext(metadata.NewIncomingContext(t.Context(), metadata.Pairs(tokenMetadataKey, tt.token)), tt.peer)
_, err := grants.UnaryInterceptor()(ctx, &pb.RecentLogsRequest{}, &grpc.UnaryServerInfo{FullMethod: pb.StateStoreService_RecentLogs_FullMethodName}, func(context.Context, any) (any, error) { return &pb.RecentLogsResponse{}, nil })
if status.Code(err) != tt.code {
t.Fatalf("code %s want %s", status.Code(err), tt.code)
}
+13 -17
View File
@@ -4,7 +4,6 @@ import (
"context"
"crypto/rand"
"crypto/sha256"
"crypto/subtle"
"encoding/hex"
"errors"
"fmt"
@@ -23,6 +22,7 @@ import (
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/infrastructure/rpctls"
)
// TaskGrants verifies run credentials: the one token a task's container
@@ -158,24 +158,25 @@ var taskScopedTargets = map[string]func(any) int64{
},
}
// UnaryInterceptor separates administrator access from task-scoped worker
// access. A tokenless listener is permitted only on loopback by composition.
// Supplied worker tokens are still validated on loopback.
func (g *TaskGrants) UnaryInterceptor(adminToken string) grpc.UnaryServerInterceptor {
// UnaryInterceptor separates services from task-scoped workers. A trusted
// caller (a verified service certificate, or a plaintext peer, which only a
// loopback listener admits) has full access; any other call needs a task
// grant and is confined to its task.
func (g *TaskGrants) UnaryInterceptor() grpc.UnaryServerInterceptor {
return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
token := requestToken(ctx)
if (adminToken == "" && token == "") || (adminToken != "" && subtle.ConstantTimeCompare([]byte(token), []byte(adminToken)) == 1) {
if rpctls.Trusted(ctx) {
return handler(ctx, req)
}
token := requestToken(ctx)
if token == "" {
return nil, status.Error(codes.Unauthenticated, "missing state store token")
return nil, status.Error(codes.Unauthenticated, "missing client certificate or task grant")
}
taskID, err := g.taskFor(ctx, token)
if err != nil {
return nil, status.Error(codes.Unavailable, "run credentials unavailable")
}
if taskID == 0 {
return nil, status.Error(codes.Unauthenticated, "invalid state store token")
return nil, status.Error(codes.Unauthenticated, "invalid task grant")
}
if !authorizesTaskScopedCall(info.FullMethod, req, taskID) {
return nil, status.Error(codes.PermissionDenied, "task grant does not authorize this operation")
@@ -202,15 +203,10 @@ func dropDefinitionPin(req any) {
r.Task.WorkflowDefinitionYaml = ""
}
// StreamInterceptor admits only administrators to store read streams.
func (g *TaskGrants) StreamInterceptor(adminToken string) grpc.StreamServerInterceptor {
// StreamInterceptor admits only services to store read streams.
func (g *TaskGrants) StreamInterceptor() grpc.StreamServerInterceptor {
return func(srv any, stream grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
md, _ := metadata.FromIncomingContext(stream.Context())
tokens := md.Get(tokenMetadataKey)
if adminToken == "" && len(tokens) == 0 {
return handler(srv, stream)
}
if len(tokens) > 0 && adminToken != "" && subtle.ConstantTimeCompare([]byte(tokens[0]), []byte(adminToken)) == 1 {
if rpctls.Trusted(stream.Context()) {
return handler(srv, stream)
}
return status.Error(codes.PermissionDenied, "task grant does not authorize streaming reads")
@@ -7,7 +7,9 @@ import (
"testing"
"google.golang.org/grpc"
grpccreds "google.golang.org/grpc/credentials"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/peer"
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
)
@@ -19,16 +21,17 @@ import (
func TestTaskCredentialCannotReplaceItsPin(t *testing.T) {
taskToken := strings.Repeat("ab", 32)
grants := &TaskGrants{Store: credentials{sha256.Sum256([]byte(taskToken)): 7}}
intercept := grants.UnaryInterceptor("admin")
intercept := grants.UnaryInterceptor()
tests := []struct {
name, token, wantYAML string
peer *peer.Peer
}{
{"task credential", taskToken, ""},
{"daemon credential", "admin", "yaml-b"},
{"task credential", taskToken, "", &peer.Peer{AuthInfo: grpccreds.TLSInfo{}}},
{"daemon", "", "yaml-b", &peer.Peer{}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctx := metadata.NewIncomingContext(context.Background(), metadata.Pairs(tokenMetadataKey, tt.token))
ctx := peer.NewContext(metadata.NewIncomingContext(context.Background(), metadata.Pairs(tokenMetadataKey, tt.token)), tt.peer)
req := &pb.UpdateRequest{Task: &pb.Task{
Id: 7, Workflow: "handoff-target",
WorkflowDefinitionVersion: 4, WorkflowDefinitionDigest: "digest-b", WorkflowDefinitionYaml: "yaml-b",