rpc/link: one dial helper and one server builder for every gRPC link

core/rpc/link builds every gRPC link: Dial is grpc.NewClient with plaintext
credentials exactly as before (caller options follow), NewServer runs the
caller's unary and stream interceptors in order (none by default). Every
production site now goes through it: nine dials to blockmaster, the two
SeaweedFS dials and both servers; the failback runtime keeps its injected
dial options unchanged. No behaviour change.

INV-SEC-ONE-SEAM-001: a guard test fails if a non-test file outside the
package creates insecure credentials or a raw gRPC server (red on the base: it
lists the 12 files with the 13 raw sites).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
pingqiuandClaude Opus 5.5 committed 2026-11-21 06:24:58 -08:00
1 parent 654b560170
commit a600bb8e2b
15 files changed
+228 -34

No files matched your search

+3 -3
View File
@@ -21,7 +21,7 @@ import (
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/internal/buildinfo"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
)
type flags struct {
@@ -127,7 +127,7 @@ func run(f flags) int {
registrar blockcsi.VolumeObjectRegistrar
)
if f.masterAddr != "" {
masterConn, err = grpc.NewClient(f.masterAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
masterConn, err = link.Dial(f.masterAddr)
if err != nil {
fmt.Fprintln(os.Stderr, "blockcsi: master dial:", err)
return 1
@@ -167,7 +167,7 @@ func run(f flags) int {
nodeSrv.StartMountedNVMeReconnectOwner(reconnectCtx, f.nvmeReconnectInterval)
}
srv := grpc.NewServer()
srv := link.NewServer(link.ServerConfig{})
csipb.RegisterIdentityServer(srv, blockcsi.NewIdentityServer())
csipb.RegisterControllerServer(srv, blockcsi.NewControllerServerWithProvisionerMetadataAndRegistrar(lookup, provisioner, resolver, registrar))
csipb.RegisterNodeServer(srv, nodeSrv)
@@ -8,8 +8,7 @@ import (
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
)
// Automatic GC stays default-off until restart-safe unknown-CAS settlement and
@@ -27,7 +26,7 @@ func newChunkMaintenance(cat *chunkstore.Catalog, blobs chunkstore.BlobDeleter,
if defaultChunkGCGrace <= max(defaultChunkCutTimeout, chunkstore.DefaultOpDeadline)+defaultChunkMaintenanceTimeout {
return nil, closeFn, errors.New("automatic GC grace does not cover cut/copy and mark bounds")
}
conn, err := grpc.NewClient(master, grpc.WithTransportCredentials(insecure.NewCredentials()))
conn, err := link.Dial(master)
if err != nil {
return nil, closeFn, err
}
+2 -3
View File
@@ -10,8 +10,7 @@ import (
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/ops"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
)
// Same clock seam as GCConfig; production always uses wall time. Tests can
@@ -78,7 +77,7 @@ func chunkGC(args []string, stdout, stderr io.Writer) int {
// masterEvidence dials the blockmaster's evidence service (gc and
// volume-delete read volume status from it).
func masterEvidence(master string) (control.EvidenceServiceClient, func() error, error) {
conn, e := grpc.NewClient(master, grpc.WithTransportCredentials(insecure.NewCredentials()))
conn, e := link.Dial(master)
if e != nil {
return nil, nil, e
}
@@ -8,14 +8,13 @@ import (
"io"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/ops"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
)
// chunkVolumeDelete: sw-block ops chunk volume-delete <vol> --chunk-filer
@@ -51,7 +50,7 @@ func chunkVolumeDelete(args []string, stdout, stderr io.Writer) int {
return exit
}
defer closeFn()
conn, err := grpc.NewClient(master, grpc.WithTransportCredentials(insecure.NewCredentials()))
conn, err := link.Dial(master)
if err != nil {
return chunkResult("volume-delete", nil, err, stdout, stderr)
}
+2 -3
View File
@@ -17,9 +17,8 @@ import (
"github.com/seaweedfs/seaweed-block/core/ops"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
"github.com/seaweedfs/seaweed-block/internal/buildinfo"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"gopkg.in/yaml.v3"
)
@@ -1158,7 +1157,7 @@ func liveNodeEvidenceNamespace(namespace string) string {
}
func readMasterClusterEvidence(ctx context.Context, masterAddr string) (ops.ClusterEvidence, error) {
conn, err := grpc.NewClient(masterAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
conn, err := link.Dial(masterAddr)
if err != nil {
return ops.ClusterEvidence{}, err
}
@@ -11,10 +11,10 @@ import (
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/masterpb"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
)
// ErrNotSingleFiler: block metadata needs exactly one filer behind the
@@ -147,7 +147,7 @@ func (c *SWFS) isTarget(ctx context.Context, listed string) bool {
}
func listFilers(ctx context.Context, addr, group string) ([]string, error) {
conn, err := grpc.NewClient(addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
conn, err := link.Dial(addr)
if err != nil {
return nil, err
}
@@ -12,10 +12,10 @@ import (
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
)
// SWFSConfig configures the minimal SeaweedFS client.
@@ -56,8 +56,7 @@ func DialSWFS(cfg SWFSConfig) (*SWFS, error) {
if cfg.HTTPTimeout == 0 {
cfg.HTTPTimeout = 60 * time.Second
}
conn, err := grpc.NewClient(cfg.FilerGRPC,
grpc.WithTransportCredentials(insecure.NewCredentials()),
conn, err := link.Dial(cfg.FilerGRPC,
grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(64<<20), grpc.MaxCallSendMsgSize(64<<20)))
if err != nil {
return nil, fmt.Errorf("chunkstore: dial filer %s: %w", cfg.FilerGRPC, err)
+2 -1
View File
@@ -31,6 +31,7 @@ import (
"github.com/seaweedfs/seaweed-block/core/host/bootstrap"
"github.com/seaweedfs/seaweed-block/core/lifecycle"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
"github.com/seaweedfs/seaweed-block/core/storeident"
"google.golang.org/grpc"
)
@@ -319,7 +320,7 @@ func New(cfg Config) (*Host, error) {
WriteTimeout: statusWriteTimeout, IdleTimeout: statusIdleTimeout}
}
grpcSrv := grpc.NewServer()
grpcSrv := link.NewServer(link.ServerConfig{})
svc := newServices(h)
control.RegisterObservationServiceServer(grpcSrv, svc)
control.RegisterAssignmentServiceServer(grpcSrv, svc)
+2 -2
View File
@@ -15,9 +15,9 @@ import (
"github.com/seaweedfs/seaweed-block/core/engine"
"github.com/seaweedfs/seaweed-block/core/replication"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
"github.com/seaweedfs/seaweed-block/core/storeident"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/timestamppb"
)
@@ -259,7 +259,7 @@ func New(cfg Config) (*Host, error) {
lg = log.Default()
}
conn, err := grpc.NewClient(cfg.MasterAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
conn, err := link.Dial(cfg.MasterAddr)
if err != nil {
return nil, fmt.Errorf("volume.New: dial master %q: %w", cfg.MasterAddr, err)
}
@@ -5,8 +5,8 @@ import (
"fmt"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
type GRPCFailbackRuntime struct {
@@ -22,11 +22,15 @@ func (r *GRPCFailbackRuntime) ExecuteFailback(ctx context.Context, req FailbackR
if r == nil || r.Addr == "" {
return FailbackRuntimeResult{}, fmt.Errorf("failback runtime gRPC address is required")
}
opts := append([]grpc.DialOption(nil), r.Opts...)
if len(opts) == 0 {
opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials()))
// Injected options replace the default link (as before); none means the
// standard link.
dial := link.Dial
if len(r.Opts) > 0 {
dial = func(target string, _ ...grpc.DialOption) (*grpc.ClientConn, error) {
return grpc.NewClient(target, r.Opts...)
}
}
conn, err := grpc.NewClient(r.Addr, opts...)
conn, err := dial(r.Addr)
if err != nil {
return FailbackRuntimeResult{}, err
}
+2 -3
View File
@@ -18,8 +18,7 @@ import (
hostvolume "github.com/seaweedfs/seaweed-block/core/host/volume"
"github.com/seaweedfs/seaweed-block/core/replication"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
)
type LiveVolumeStatusConfig struct {
@@ -95,7 +94,7 @@ func NewLiveVolumeStatusReportCollector(cfg LiveVolumeStatusConfig) VolumeStatus
}
func queryLiveMasterStatus(ctx context.Context, masterAddr, volumeID string) (*control.StatusResponse, error) {
conn, err := grpc.NewClient(masterAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
conn, err := link.Dial(masterAddr)
if err != nil {
return nil, fmt.Errorf("dial master: %w", err)
}
+40
View File
@@ -0,0 +1,40 @@
// Package link builds every gRPC link between seaweed-block processes and to
// SeaweedFS: one dial helper and one server builder, so transport security
// and call authorization have a single place to be added. Today a link is
// plaintext, exactly as before this package existed, and a server runs only
// the interceptors its caller passes (none by default).
package link
import (
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
// Dial opens a lazy client connection to target with plaintext transport
// credentials; opts follow (a later option overrides an earlier one).
func Dial(target string, opts ...grpc.DialOption) (*grpc.ClientConn, error) {
all := make([]grpc.DialOption, 0, len(opts)+1)
all = append(all, grpc.WithTransportCredentials(insecure.NewCredentials()))
all = append(all, opts...)
return grpc.NewClient(target, all...)
}
// ServerConfig is a server's interceptor chain; the zero value has none.
type ServerConfig struct {
Unary []grpc.UnaryServerInterceptor
Stream []grpc.StreamServerInterceptor
}
// NewServer builds a gRPC server whose calls pass through cfg's interceptors,
// in order; opts follow.
func NewServer(cfg ServerConfig, opts ...grpc.ServerOption) *grpc.Server {
all := make([]grpc.ServerOption, 0, len(opts)+2)
if len(cfg.Unary) > 0 {
all = append(all, grpc.ChainUnaryInterceptor(cfg.Unary...))
}
if len(cfg.Stream) > 0 {
all = append(all, grpc.ChainStreamInterceptor(cfg.Stream...))
}
all = append(all, opts...)
return grpc.NewServer(all...)
}
+149
View File
@@ -0,0 +1,149 @@
package link
import (
"context"
"io/fs"
"net"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/health"
healthpb "google.golang.org/grpc/health/grpc_health_v1"
)
func serve(t *testing.T, cfg ServerConfig) string {
t.Helper()
lis, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
srv := NewServer(cfg)
healthpb.RegisterHealthServer(srv, health.NewServer())
done := make(chan struct{})
go func() { _ = srv.Serve(lis); close(done) }()
t.Cleanup(func() {
srv.Stop()
select {
case <-done:
case <-time.After(5 * time.Second):
t.Error("server did not stop")
}
})
return lis.Addr().String()
}
// A link dialed with Dial reaches a server built with NewServer, for a unary
// and a streaming call, as plaintext gRPC did before the seam.
func TestLink_DialReachesNewServerUnaryAndStream(t *testing.T) {
addr := serve(t, ServerConfig{})
conn, err := Dial(addr)
if err != nil {
t.Fatal(err)
}
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
c := healthpb.NewHealthClient(conn)
if r, err := c.Check(ctx, &healthpb.HealthCheckRequest{}); err != nil || r.Status != healthpb.HealthCheckResponse_SERVING {
t.Fatalf("unary call: %v %v", r, err)
}
w, err := c.Watch(ctx, &healthpb.HealthCheckRequest{})
if err != nil {
t.Fatal(err)
}
if r, err := w.Recv(); err != nil || r.Status != healthpb.HealthCheckResponse_SERVING {
t.Fatalf("stream call: %v %v", r, err)
}
}
// The server runs its unary and stream interceptors in the configured order.
func TestLink_ServerRunsInterceptorsInOrder(t *testing.T) {
var mu sync.Mutex
var seen []string
note := func(s string) { mu.Lock(); seen = append(seen, s); mu.Unlock() }
unary := func(name string) grpc.UnaryServerInterceptor {
return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, h grpc.UnaryHandler) (any, error) {
note(name)
return h(ctx, req)
}
}
stream := func(name string) grpc.StreamServerInterceptor {
return func(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, h grpc.StreamHandler) error {
note(name)
return h(srv, ss)
}
}
addr := serve(t, ServerConfig{Unary: []grpc.UnaryServerInterceptor{unary("u1"), unary("u2")}, Stream: []grpc.StreamServerInterceptor{stream("s1"), stream("s2")}})
conn, err := Dial(addr)
if err != nil {
t.Fatal(err)
}
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
c := healthpb.NewHealthClient(conn)
if _, err := c.Check(ctx, &healthpb.HealthCheckRequest{}); err != nil {
t.Fatal(err)
}
w, err := c.Watch(ctx, &healthpb.HealthCheckRequest{})
if err != nil {
t.Fatal(err)
}
if _, err := w.Recv(); err != nil {
t.Fatal(err)
}
mu.Lock()
defer mu.Unlock()
if got := strings.Join(seen, ","); got != "u1,u2,s1,s2" {
t.Fatalf("interceptors ran as %q, want u1,u2,s1,s2", got)
}
}
// Every production gRPC link goes through this package: no other non-test Go
// file builds plaintext credentials or a gRPC server directly.
func TestLink_NoProductionSiteBypassesTheSeam(t *testing.T) {
root, err := filepath.Abs(filepath.Join("..", "..", ".."))
if err != nil {
t.Fatal(err)
}
self, err := filepath.Abs(".")
if err != nil {
t.Fatal(err)
}
var bad []string
err = filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
if name := d.Name(); name == ".git" || name == "vendor" || name == "testdata" || p == self {
return filepath.SkipDir
}
return nil
}
if !strings.HasSuffix(p, ".go") || strings.HasSuffix(p, "_test.go") {
return nil
}
b, err := os.ReadFile(p)
if err != nil {
return err
}
src := string(b)
if strings.Contains(src, "insecure.NewCredentials(") || strings.Contains(src, "grpc.NewServer(") {
rel, _ := filepath.Rel(root, p)
bad = append(bad, rel)
}
return nil
})
if err != nil {
t.Fatal(err)
}
if len(bad) > 0 {
t.Fatalf("gRPC links built outside core/rpc/link (use link.Dial / link.NewServer): %v", bad)
}
}
+2 -2
View File
@@ -17,9 +17,9 @@ import (
"time"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
)
@@ -124,7 +124,7 @@ func New(rpc control.WorkspaceServiceClient) *Client { return &Client{rpc: rpc}
// Dial connects to the blockmaster gRPC address (plaintext, as the other
// operator commands).
func Dial(addr string) (*Client, error) {
conn, err := grpc.NewClient(addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
conn, err := link.Dial(addr)
if err != nil {
return nil, err
}
+7 -1
View File
@@ -382,7 +382,7 @@ with a separate scope/config-bound mark. Incomplete marks carry no coverage.
## Part B. Invariant ledger
136 rows: 116 ACTIVE, 17 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 121 new.
137 rows: 117 ACTIVE, 17 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 122 new.
The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger.
@@ -633,6 +633,12 @@ Notes:
|---|---|---|---|---|---|---|
| `INV-NVME-H2C-RANGE-001` | An H2CData range exceeding the expected transfer size is refused before slicing, including a uint32 offset-plus-length overflow; an exact-bound payload is preserved. | Frontend H2C receive validation; no storage state transition | `core/frontend/nvme/session.go` `recvH2CData` | `TestRecvH2CDataRangeBounds` (`core/frontend/nvme/h2c_bounds_test.go`) | — | ACTIVE |
### B.9 Security: gRPC links
| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status |
|---|---|---|---|---|---|---|
| `INV-SEC-ONE-SEAM-001` | Every production gRPC client and server is built by core/rpc/link; a non-test file outside it that creates insecure credentials or a raw grpc server fails the guard test. | AUTHORITY: every gRPC link (client dial, server build) | `core/rpc/link` `Dial`, `NewServer` | `TestLink_NoProductionSiteBypassesTheSeam`, `TestLink_DialReachesNewServerUnaryAndStream`, `TestLink_ServerRunsInterceptorsInOrder` (`core/rpc/link/link_test.go`) | — (no state machine; the guard test is the proof form) | ACTIVE |
### Experimental data-file synchronization
| ID | Invariant | Machine / transition | Enforced in | Tests | TLA+ | Status |