From 160fcc0d29458b7f7c840713f61185053fafc451 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 08:23:03 -0800 Subject: [PATCH 01/36] feat(auth): the caller is the CA-verified certificate pinned by the role file core/auth (phase 0, S2): ParseRoleFile/LoadRoleFile (sha256: role id), an Authenticator whose table swaps atomically (a failed reload keeps the previous table), and PeerIdentity: the leaf certificate the TLS handshake verified to the client CA, its fingerprint bound to a role and id, CN equal to that id, not expired on the master's clock; every failure is UNAUTHENTICATED. authtest issues test CAs and certificates. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/auth/authtest/certs.go | 133 ++++++++++++++++ seaweed-block/core/auth/identity.go | 179 ++++++++++++++++++++++ seaweed-block/core/auth/identity_test.go | 159 +++++++++++++++++++ 3 files changed, 471 insertions(+) create mode 100644 seaweed-block/core/auth/authtest/certs.go create mode 100644 seaweed-block/core/auth/identity.go create mode 100644 seaweed-block/core/auth/identity_test.go diff --git a/seaweed-block/core/auth/authtest/certs.go b/seaweed-block/core/auth/authtest/certs.go new file mode 100644 index 0000000000..e9cfe7c718 --- /dev/null +++ b/seaweed-block/core/auth/authtest/certs.go @@ -0,0 +1,133 @@ +// Package authtest issues test certificates for the phase 0 authentication +// tests: a CA, and leaf certificates signed by it with a chosen CN and expiry. +// Test support only; nothing in the product imports it. +package authtest + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/sha256" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "encoding/hex" + "encoding/pem" + "math/big" + "net" + "os" + "path/filepath" + "testing" + "time" +) + +// CA is a test certificate authority. +type CA struct { + Cert *x509.Certificate + key *ecdsa.PrivateKey + PEM []byte +} + +// Leaf is a certificate the CA issued, with its key. +type Leaf struct { + Cert *x509.Certificate + TLS tls.Certificate + CertPEM []byte + KeyPEM []byte + Fingerprint string // "sha256:" of the leaf DER, as the role file writes it +} + +// NewCA makes a CA valid for a day. +func NewCA(t testing.TB, name string) *CA { + 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(24 * time.Hour), + IsCA: true, + KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature, + BasicConstraintsValid: true, + } + der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key) + if err != nil { + t.Fatal(err) + } + cert, err := x509.ParseCertificate(der) + if err != nil { + t.Fatal(err) + } + return &CA{Cert: cert, key: key, PEM: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})} +} + +var serial = big.NewInt(100) + +// Issue signs a leaf certificate with the given CN that expires at notAfter; +// it is valid as a TLS client and server certificate for 127.0.0.1 and +// localhost. +func (ca *CA) Issue(t testing.TB, cn string, notAfter time.Time) *Leaf { + t.Helper() + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + serial = new(big.Int).Add(serial, big.NewInt(1)) + tmpl := &x509.Certificate{ + SerialNumber: serial, + Subject: pkix.Name{CommonName: cn}, + NotBefore: time.Now().Add(-time.Hour), + NotAfter: notAfter, + KeyUsage: x509.KeyUsageDigitalSignature, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth}, + DNSNames: []string{"localhost"}, + IPAddresses: []net.IP{net.ParseIP("127.0.0.1")}, + } + der, err := x509.CreateCertificate(rand.Reader, tmpl, ca.Cert, &key.PublicKey, ca.key) + if err != nil { + t.Fatal(err) + } + cert, err := x509.ParseCertificate(der) + if err != nil { + t.Fatal(err) + } + keyDER, err := x509.MarshalECPrivateKey(key) + if err != nil { + t.Fatal(err) + } + certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}) + keyPEM := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER}) + pair, err := tls.X509KeyPair(certPEM, keyPEM) + if err != nil { + t.Fatal(err) + } + sum := sha256.Sum256(der) + return &Leaf{Cert: cert, TLS: pair, CertPEM: certPEM, KeyPEM: keyPEM, Fingerprint: "sha256:" + hex.EncodeToString(sum[:])} +} + +// WriteFiles writes the leaf's certificate and key to dir as .crt and +// .key and returns their paths. +func (l *Leaf) WriteFiles(t testing.TB, dir, name string) (certPath, keyPath string) { + t.Helper() + certPath, keyPath = filepath.Join(dir, name+".crt"), filepath.Join(dir, name+".key") + if err := os.WriteFile(certPath, l.CertPEM, 0o600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(keyPath, l.KeyPEM, 0o600); err != nil { + t.Fatal(err) + } + return certPath, keyPath +} + +// WriteCA writes the CA certificate to dir/ca.crt and returns its path. +func (ca *CA) WriteCA(t testing.TB, dir string) string { + t.Helper() + p := filepath.Join(dir, "ca.crt") + if err := os.WriteFile(p, ca.PEM, 0o600); err != nil { + t.Fatal(err) + } + return p +} diff --git a/seaweed-block/core/auth/identity.go b/seaweed-block/core/auth/identity.go new file mode 100644 index 0000000000..8059f083bc --- /dev/null +++ b/seaweed-block/core/auth/identity.go @@ -0,0 +1,179 @@ +// Package auth decides who calls blockmaster (phase 0): the caller is the +// leaf certificate of the mutual-TLS connection, verified to the operator's +// CA, pinned by its SHA-256 fingerprint and bound to a role and an id by the +// role file (TERM-CALLER-001). No request field ever names the caller. +package auth + +import ( + "bufio" + "context" + "crypto/sha256" + "encoding/hex" + "fmt" + "io" + "os" + "strings" + "sync/atomic" + "time" + + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials" + "google.golang.org/grpc/peer" + "google.golang.org/grpc/status" +) + +// Role is what a principal may do. viewer < operator < admin (each includes +// the one before) are people and tools; node (a volume host) stands apart. +type Role string + +const ( + RoleViewer Role = "viewer" + RoleOperator Role = "operator" + RoleAdmin Role = "admin" + RoleNode Role = "node" +) + +func parseRole(s string) (Role, bool) { + switch r := Role(s); r { + case RoleViewer, RoleOperator, RoleAdmin, RoleNode: + return r, true + } + return "", false +} + +// Principal is who a call comes from. +type Principal struct { + Role Role + ID string // a node's server id; a person's or tool's name + Fingerprint string // "sha256:" of the leaf DER + NotAfter time.Time +} + +type entry struct { + role Role + id string +} + +// Table is a parsed role file: fingerprint -> (role, id). Configuration +// written only by the operator; never written by the master. +type Table struct { + byFingerprint map[string]entry +} + +// Len is the number of principals in the table. +func (t *Table) Len() int { return len(t.byFingerprint) } + +// ParseRoleFile reads lines "sha256:<64 hex> "; blank lines and +// lines starting with # are ignored. Any malformed line, unknown role or +// repeated fingerprint makes the whole file an error. +func ParseRoleFile(r io.Reader) (*Table, error) { + t := &Table{byFingerprint: map[string]entry{}} + sc := bufio.NewScanner(r) + for n := 1; sc.Scan(); n++ { + line := strings.TrimSpace(sc.Text()) + if line == "" || strings.HasPrefix(line, "#") { + continue + } + f := strings.Fields(line) + if len(f) != 3 { + return nil, fmt.Errorf("role file line %d: want \"sha256: \", got %d fields", n, len(f)) + } + fp := strings.ToLower(f[0]) + hexPart, ok := strings.CutPrefix(fp, "sha256:") + if raw, err := hex.DecodeString(hexPart); !ok || err != nil || len(raw) != sha256.Size { + return nil, fmt.Errorf("role file line %d: %q is not a sha256:<64 hex> fingerprint", n, f[0]) + } + role, ok := parseRole(f[1]) + if !ok { + return nil, fmt.Errorf("role file line %d: unknown role %q (viewer, operator, admin, node)", n, f[1]) + } + if _, dup := t.byFingerprint[fp]; dup { + return nil, fmt.Errorf("role file line %d: fingerprint %s appears twice", n, fp) + } + t.byFingerprint[fp] = entry{role: role, id: f[2]} + } + if err := sc.Err(); err != nil { + return nil, fmt.Errorf("role file: %w", err) + } + return t, nil +} + +// LoadRoleFile parses the role file at path. +func LoadRoleFile(path string) (*Table, error) { + f, err := os.Open(path) + if err != nil { + return nil, fmt.Errorf("role file: %w", err) + } + defer f.Close() + return ParseRoleFile(f) +} + +// Authenticator holds the current table (swapped atomically: a call never +// blocks on a reload) and the master's clock. +type Authenticator struct { + table atomic.Pointer[Table] + now func() time.Time +} + +// NewAuthenticator starts with t; now nil is time.Now. +func NewAuthenticator(t *Table, now func() time.Time) *Authenticator { + if now == nil { + now = time.Now + } + a := &Authenticator{now: now} + a.table.Store(t) + return a +} + +// Swap installs t for every later call. +func (a *Authenticator) Swap(t *Table) { a.table.Store(t) } + +// Reload parses path and installs it; on any error the current table stays. +func (a *Authenticator) Reload(path string) error { + t, err := LoadRoleFile(path) + if err != nil { + return err + } + a.Swap(t) + return nil +} + +// Fingerprint is the role-file form of a DER certificate's fingerprint. +func Fingerprint(der []byte) string { + sum := sha256.Sum256(der) + return "sha256:" + hex.EncodeToString(sum[:]) +} + +func unauthenticated(format string, args ...any) error { + return status.Errorf(codes.Unauthenticated, format, args...) +} + +// PeerIdentity is the only decider of who calls the master. It reads the +// leaf certificate the TLS handshake verified to the client CA (never a +// request field) and runs on every call. Every failure is UNAUTHENTICATED, +// never retryable: no verified client certificate; a fingerprint not in the +// current table; a CN that differs from the table's id; now at or past the +// certificate's NotAfter on the master's clock. +func (a *Authenticator) PeerIdentity(ctx context.Context) (Principal, error) { + p, ok := peer.FromContext(ctx) + if !ok { + return Principal{}, unauthenticated("no client certificate: the call did not come over mutual TLS") + } + info, ok := p.AuthInfo.(credentials.TLSInfo) + if !ok || len(info.State.VerifiedChains) == 0 || len(info.State.VerifiedChains[0]) == 0 { + return Principal{}, unauthenticated("no client certificate verified by the client CA") + } + leaf := info.State.VerifiedChains[0][0] + fp := Fingerprint(leaf.Raw) + e, ok := a.table.Load().byFingerprint[fp] + if !ok { + return Principal{}, unauthenticated("certificate %s (CN=%s) is not in the role file", fp, leaf.Subject.CommonName) + } + if leaf.Subject.CommonName != e.id { + return Principal{}, unauthenticated("certificate CN=%s does not match role-file id %s for fingerprint %s", leaf.Subject.CommonName, e.id, fp) + } + if !a.now().Before(leaf.NotAfter) { + return Principal{}, unauthenticated("certificate %s (CN=%s) expired at %s", fp, e.id, leaf.NotAfter.UTC().Format(time.RFC3339)) + } + return Principal{Role: e.role, ID: e.id, Fingerprint: fp, NotAfter: leaf.NotAfter}, nil +} diff --git a/seaweed-block/core/auth/identity_test.go b/seaweed-block/core/auth/identity_test.go new file mode 100644 index 0000000000..4df326753a --- /dev/null +++ b/seaweed-block/core/auth/identity_test.go @@ -0,0 +1,159 @@ +package auth_test + +import ( + "context" + "crypto/tls" + "crypto/x509" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/auth" + "github.com/seaweedfs/seaweed-block/core/auth/authtest" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials" + "google.golang.org/grpc/peer" + "google.golang.org/grpc/status" +) + +// peerCtx is a call context whose connection presented leaf, verified to ca +// (as the TLS handshake with a client CA leaves it); leaf nil = no client +// certificate. +func peerCtx(leaf *authtest.Leaf, ca *authtest.CA) context.Context { + st := tls.ConnectionState{HandshakeComplete: true} + if leaf != nil { + st.PeerCertificates = []*x509.Certificate{leaf.Cert} + st.VerifiedChains = [][]*x509.Certificate{{leaf.Cert, ca.Cert}} + } + return peer.NewContext(context.Background(), &peer.Peer{AuthInfo: credentials.TLSInfo{State: st}}) +} + +func table(t *testing.T, lines ...string) *auth.Table { + t.Helper() + tab, err := auth.ParseRoleFile(strings.NewReader(strings.Join(lines, "\n"))) + if err != nil { + t.Fatal(err) + } + return tab +} + +// T1: PeerIdentity is the one decider of who is calling: the CA-verified +// leaf's fingerprint, bound to a role and id by the role file, with CN equal +// to the id and the certificate not expired on the master's clock. Every +// failure is UNAUTHENTICATED. +func TestPeerIdentity(t *testing.T) { + ca := authtest.NewCA(t, "test-ca") + expiry := time.Now().Add(time.Hour) + node := ca.Issue(t, "s1", expiry) + op := ca.Issue(t, "alice", expiry) + admin := ca.Issue(t, "ops-admin", expiry) + wrongCN := ca.Issue(t, "s2", expiry) + unlisted := ca.Issue(t, "s3", expiry) + tab := table(t, + "# fingerprint role id", + node.Fingerprint+" node s1", + op.Fingerprint+" operator alice", + admin.Fingerprint+" admin ops-admin", + wrongCN.Fingerprint+" node s1", // pasted on the wrong line + ) + now := time.Now() + a := auth.NewAuthenticator(tab, func() time.Time { return now }) + + for _, c := range []struct { + name string + ctx context.Context + role auth.Role + id string + }{ + {"node", peerCtx(node, ca), auth.RoleNode, "s1"}, + {"operator", peerCtx(op, ca), auth.RoleOperator, "alice"}, + {"admin", peerCtx(admin, ca), auth.RoleAdmin, "ops-admin"}, + } { + p, err := a.PeerIdentity(c.ctx) + if err != nil || p.Role != c.role || p.ID != c.id || p.NotAfter.IsZero() || !strings.HasPrefix(p.Fingerprint, "sha256:") { + t.Fatalf("%s: %+v %v; want role %s id %s", c.name, p, err, c.role, c.id) + } + } + refused := func(name string, ctx context.Context, want string) { + t.Helper() + _, err := a.PeerIdentity(ctx) + if status.Code(err) != codes.Unauthenticated || !strings.Contains(err.Error(), want) { + t.Fatalf("%s: %v; want UNAUTHENTICATED naming %q", name, err, want) + } + } + refused("no peer", context.Background(), "no client certificate") + refused("no client certificate", peerCtx(nil, ca), "no client certificate") + other := authtest.NewCA(t, "other-ca") + stray := other.Issue(t, "s1", expiry) + strayCtx := peer.NewContext(context.Background(), &peer.Peer{AuthInfo: credentials.TLSInfo{State: tls.ConnectionState{ + HandshakeComplete: true, PeerCertificates: []*x509.Certificate{stray.Cert}}}}) // not verified to the CA + refused("a certificate the CA did not verify", strayCtx, "no client certificate") + refused("fingerprint not in the table", peerCtx(unlisted, ca), "not in the role file") + refused("CN differs from the id", peerCtx(wrongCN, ca), "does not match role-file id") + now = node.Cert.NotAfter.Add(-time.Nanosecond) + if _, err := a.PeerIdentity(peerCtx(node, ca)); err != nil { + t.Fatalf("1 ns before NotAfter: %v", err) + } + now = node.Cert.NotAfter + refused("at NotAfter", peerCtx(node, ca), "expired") + now = time.Now() + + // A table swapped between two calls on one connection: the next call sees it. + ctx := peerCtx(node, ca) + if _, err := a.PeerIdentity(ctx); err != nil { + t.Fatal(err) + } + a.Swap(table(t, op.Fingerprint+" operator alice")) + refused("after a reload that removed the node", ctx, "not in the role file") +} + +// T3: a good role file swaps the table; a malformed one keeps the previous +// table and reports the error; an unreadable file at start is an error. +func TestRoleFileReload(t *testing.T) { + ca := authtest.NewCA(t, "test-ca") + node := ca.Issue(t, "s1", time.Now().Add(time.Hour)) + dir := t.TempDir() + path := filepath.Join(dir, "roles") + if _, err := auth.LoadRoleFile(path); err == nil { + t.Fatal("an unreadable role file at start must be an error") + } + if err := os.WriteFile(path, []byte(node.Fingerprint+" node s1\n"), 0o600); err != nil { + t.Fatal(err) + } + tab, err := auth.LoadRoleFile(path) + if err != nil { + t.Fatal(err) + } + a := auth.NewAuthenticator(tab, nil) + if _, err := a.PeerIdentity(peerCtx(node, ca)); err != nil { + t.Fatal(err) + } + for _, bad := range []string{ + "sha256:zz node s1", // not hex + node.Fingerprint + " root s1", // unknown role + node.Fingerprint + " node", // no id + node.Fingerprint + " node s1 more", // extra field + node.Fingerprint + " node s1\n" + node.Fingerprint + " admin x", // fingerprint twice + } { + if err := os.WriteFile(path, []byte(bad+"\n"), 0o600); err != nil { + t.Fatal(err) + } + if err := a.Reload(path); err == nil { + t.Fatalf("malformed role file %q reloaded", bad) + } + if _, err := a.PeerIdentity(peerCtx(node, ca)); err != nil { + t.Fatalf("a failed reload (%q) dropped the previous table: %v", bad, err) + } + } + if err := os.WriteFile(path, []byte("# empty\n"), 0o600); err != nil { + t.Fatal(err) + } + if err := a.Reload(path); err != nil { + t.Fatal(err) + } + if _, err := a.PeerIdentity(peerCtx(node, ca)); status.Code(err) != codes.Unauthenticated { + t.Fatalf("after a reload without the node: %v; want UNAUTHENTICATED", err) + } +} From 34dbc862cd55843436609350ef29b454c2ac8eb7 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 08:25:04 -0800 Subject: [PATCH 02/36] feat(auth): one interceptor, per-method rules, RequireNode / RequireRole Phase 0, S3 (core part): the unary and stream interceptors authenticate every call (PeerIdentity), apply the method's rule (people from a minimum role up; nodes where allowed; a method without a rule is refused), and put the principal on the context for RequireNode (own server id) and RequireRole. A stream re-authenticates before every send and at every role-file reload, so a removed caller loses its open stream at the reload. Development mode marks calls explicitly; a call no interceptor saw is refused by the handler checks (fail closed). Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/auth/authorize.go | 196 ++++++++++++++++++++++ seaweed-block/core/auth/authorize_test.go | 191 +++++++++++++++++++++ seaweed-block/core/auth/identity.go | 24 ++- 3 files changed, 408 insertions(+), 3 deletions(-) create mode 100644 seaweed-block/core/auth/authorize.go create mode 100644 seaweed-block/core/auth/authorize_test.go diff --git a/seaweed-block/core/auth/authorize.go b/seaweed-block/core/auth/authorize.go new file mode 100644 index 0000000000..639434ceb5 --- /dev/null +++ b/seaweed-block/core/auth/authorize.go @@ -0,0 +1,196 @@ +package auth + +import ( + "context" + + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// Rule is who may call one method: people from Min upwards (viewer < +// operator < admin; "" admits no person), and nodes when Node is set (a +// handler then checks the node's own server id with RequireNode). +type Rule struct { + Min Role + Node bool +} + +func rank(r Role) int { + switch r { + case RoleViewer: + return 1 + case RoleOperator: + return 2 + case RoleAdmin: + return 3 + } + return 0 +} + +// Allows reports whether p may call a method with this rule. +func (r Rule) Allows(p Principal) bool { + if p.Role == RoleNode { + return r.Node + } + return r.Min != "" && rank(p.Role) >= rank(r.Min) +} + +type ctxKey struct{} + +// callAuth is what the interceptor decided for one call: the principal, or +// development mode (plaintext on loopback, no role file). +type callAuth struct { + p Principal + dev bool +} + +// FromContext returns the call's principal (false in development mode or +// when no interceptor ran). +func FromContext(ctx context.Context) (Principal, bool) { + c, ok := ctx.Value(ctxKey{}).(callAuth) + return c.p, ok && !c.dev +} + +func forbidden(format string, args ...any) error { + return status.Errorf(codes.PermissionDenied, format, args...) +} + +// decided is the call's decision; a call no interceptor saw is refused, so a +// handler's own checks fail closed if the server was built without one. +func decided(ctx context.Context) (callAuth, error) { + c, ok := ctx.Value(ctxKey{}).(callAuth) + if !ok { + return callAuth{}, unauthenticated("no caller identity on this call") + } + return c, nil +} + +// RequireNode admits a node calling for its own server id (development mode +// admits every call). A person, or a node naming another server id, is +// refused. +func RequireNode(ctx context.Context, serverID string) error { + c, err := decided(ctx) + if err != nil || c.dev { + return err + } + if c.p.Role != RoleNode { + return forbidden("%s %s is not a node", c.p.Role, c.p.ID) + } + if c.p.ID != serverID { + return forbidden("node %s may act only for its own server id, not %q", c.p.ID, serverID) + } + return nil +} + +// RequireRole admits a person with at least min (development mode admits +// every call). +func RequireRole(ctx context.Context, min Role) error { + c, err := decided(ctx) + if err != nil || c.dev { + return err + } + if !(Rule{Min: min}).Allows(c.p) { + return forbidden("%s %s may not do this: it needs %s", c.p.Role, c.p.ID, min) + } + return nil +} + +func (a *Authenticator) admit(ctx context.Context, method string, rules map[string]Rule) (context.Context, error) { + p, err := a.PeerIdentity(ctx) + if err != nil { + return nil, err + } + r, ok := rules[method] + if !ok { + return nil, forbidden("method %s has no authorization rule", method) + } + if !r.Allows(p) { + return nil, forbidden("%s %s may not call %s", p.Role, p.ID, method) + } + return context.WithValue(ctx, ctxKey{}, callAuth{p: p}), nil +} + +// UnaryInterceptor authenticates every call (PeerIdentity) and applies its +// method's rule. +func (a *Authenticator) UnaryInterceptor(rules map[string]Rule) grpc.UnaryServerInterceptor { + return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { + ctx, err := a.admit(ctx, info.FullMethod, rules) + if err != nil { + return nil, err + } + return handler(ctx, req) + } +} + +// StreamInterceptor authenticates a stream when it opens, again before every +// message it sends, and again at every role-file reload: a caller removed +// from the file loses its open stream at the reload (UNAUTHENTICATED), not at +// the next message. +func (a *Authenticator) StreamInterceptor(rules map[string]Rule) grpc.StreamServerInterceptor { + return func(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { + changed := a.Changed() + ctx, err := a.admit(ss.Context(), info.FullMethod, rules) + if err != nil { + return err + } + ctx, cancel := context.WithCancelCause(ctx) + defer cancel(nil) + go func() { + for { + select { + case <-ctx.Done(): + return + case <-changed: + changed = a.Changed() + if _, err := a.PeerIdentity(ss.Context()); err != nil { + cancel(err) + return + } + } + } + }() + err = handler(srv, &authStream{ServerStream: ss, ctx: ctx, a: a}) + if cause := context.Cause(ctx); cause != nil && status.Code(cause) == codes.Unauthenticated { + return cause + } + return err + } +} + +type authStream struct { + grpc.ServerStream + ctx context.Context + a *Authenticator +} + +func (s *authStream) Context() context.Context { return s.ctx } + +func (s *authStream) SendMsg(m any) error { + if _, err := s.a.PeerIdentity(s.ServerStream.Context()); err != nil { + return err + } + return s.ServerStream.SendMsg(m) +} + +// DevUnaryInterceptor and DevStreamInterceptor mark every call as +// development mode (plaintext on loopback, no role file): RequireNode and +// RequireRole then admit it. +func DevUnaryInterceptor() grpc.UnaryServerInterceptor { + return func(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { + return handler(context.WithValue(ctx, ctxKey{}, callAuth{dev: true}), req) + } +} + +func DevStreamInterceptor() grpc.StreamServerInterceptor { + return func(srv any, ss grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) error { + return handler(srv, &devStream{ServerStream: ss, ctx: context.WithValue(ss.Context(), ctxKey{}, callAuth{dev: true})}) + } +} + +type devStream struct { + grpc.ServerStream + ctx context.Context +} + +func (s *devStream) Context() context.Context { return s.ctx } diff --git a/seaweed-block/core/auth/authorize_test.go b/seaweed-block/core/auth/authorize_test.go new file mode 100644 index 0000000000..78fe84ec31 --- /dev/null +++ b/seaweed-block/core/auth/authorize_test.go @@ -0,0 +1,191 @@ +package auth_test + +import ( + "context" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/auth" + "github.com/seaweedfs/seaweed-block/core/auth/authtest" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" +) + +func TestRuleAllows(t *testing.T) { + p := func(r auth.Role) auth.Principal { return auth.Principal{Role: r, ID: "x"} } + for _, c := range []struct { + rule auth.Rule + role auth.Role + want bool + }{ + {auth.Rule{Min: auth.RoleViewer}, auth.RoleViewer, true}, + {auth.Rule{Min: auth.RoleViewer}, auth.RoleAdmin, true}, + {auth.Rule{Min: auth.RoleOperator}, auth.RoleViewer, false}, + {auth.Rule{Min: auth.RoleAdmin}, auth.RoleOperator, false}, + {auth.Rule{Min: auth.RoleAdmin}, auth.RoleNode, false}, + {auth.Rule{Node: true}, auth.RoleNode, true}, + {auth.Rule{Node: true}, auth.RoleAdmin, false}, + {auth.Rule{Min: auth.RoleViewer, Node: true}, auth.RoleNode, true}, + } { + if got := c.rule.Allows(p(c.role)); got != c.want { + t.Errorf("%+v allows %s = %v; want %v", c.rule, c.role, got, c.want) + } + } +} + +// The handler checks: a node only for its own server id; a person only +// with the role; development mode admits; a call no interceptor saw is +// refused (fail closed). +func TestRequireNodeAndRole(t *testing.T) { + ca := authtest.NewCA(t, "ca") + node := ca.Issue(t, "s1", time.Now().Add(time.Hour)) + op := ca.Issue(t, "alice", time.Now().Add(time.Hour)) + a := auth.NewAuthenticator(table(t, node.Fingerprint+" node s1", op.Fingerprint+" operator alice"), nil) + rules := map[string]auth.Rule{"/m": {Min: auth.RoleViewer, Node: true}} + ctxOf := func(leaf *authtest.Leaf) context.Context { + var got context.Context + _, err := a.UnaryInterceptor(rules)(peerCtx(leaf, ca), nil, &grpc.UnaryServerInfo{FullMethod: "/m"}, func(ctx context.Context, _ any) (any, error) { + got = ctx + return nil, nil + }) + if err != nil { + t.Fatal(err) + } + return got + } + nodeCtx, opCtx := ctxOf(node), ctxOf(op) + if err := auth.RequireNode(nodeCtx, "s1"); err != nil { + t.Fatalf("node for its own id: %v", err) + } + if err := auth.RequireNode(nodeCtx, "s2"); status.Code(err) != codes.PermissionDenied { + t.Fatalf("node for another id: %v; want PERMISSION_DENIED", err) + } + if err := auth.RequireNode(opCtx, "s1"); status.Code(err) != codes.PermissionDenied { + t.Fatalf("operator as a node: %v; want PERMISSION_DENIED", err) + } + if err := auth.RequireRole(opCtx, auth.RoleOperator); err != nil { + t.Fatalf("operator needing operator: %v", err) + } + if err := auth.RequireRole(opCtx, auth.RoleAdmin); status.Code(err) != codes.PermissionDenied { + t.Fatalf("operator needing admin: %v; want PERMISSION_DENIED", err) + } + if err := auth.RequireRole(nodeCtx, auth.RoleViewer); status.Code(err) != codes.PermissionDenied { + t.Fatalf("node needing viewer: %v; want PERMISSION_DENIED", err) + } + if err := auth.RequireNode(context.Background(), "s1"); status.Code(err) != codes.Unauthenticated { + t.Fatalf("no interceptor ran: %v; want UNAUTHENTICATED (fail closed)", err) + } + var devCtx context.Context + _, _ = auth.DevUnaryInterceptor()(context.Background(), nil, &grpc.UnaryServerInfo{FullMethod: "/m"}, func(ctx context.Context, _ any) (any, error) { + devCtx = ctx + return nil, nil + }) + if auth.RequireNode(devCtx, "anything") != nil || auth.RequireRole(devCtx, auth.RoleAdmin) != nil { + t.Fatal("development mode must admit") + } + if _, ok := auth.FromContext(devCtx); ok { + t.Fatal("development mode has no principal") + } +} + +// The unary interceptor refuses a caller without a role on the method +// (PERMISSION_DENIED), an unauthenticated one (UNAUTHENTICATED), and any +// method without a rule (fail closed). +func TestUnaryInterceptor(t *testing.T) { + ca := authtest.NewCA(t, "ca") + op := ca.Issue(t, "alice", time.Now().Add(time.Hour)) + a := auth.NewAuthenticator(table(t, op.Fingerprint+" operator alice"), nil) + rules := map[string]auth.Rule{"/viewer": {Min: auth.RoleViewer}, "/admin": {Min: auth.RoleAdmin}} + call := func(ctx context.Context, method string) error { + _, err := a.UnaryInterceptor(rules)(ctx, nil, &grpc.UnaryServerInfo{FullMethod: method}, func(ctx context.Context, _ any) (any, error) { + if p, ok := auth.FromContext(ctx); !ok || p.ID != "alice" { + t.Errorf("handler principal %+v %v", p, ok) + } + return nil, nil + }) + return err + } + if err := call(peerCtx(op, ca), "/viewer"); err != nil { + t.Fatalf("operator on a viewer method: %v", err) + } + if err := call(peerCtx(op, ca), "/admin"); status.Code(err) != codes.PermissionDenied { + t.Fatalf("operator on an admin method: %v; want PERMISSION_DENIED", err) + } + if err := call(peerCtx(op, ca), "/unlisted"); status.Code(err) != codes.PermissionDenied { + t.Fatalf("a method without a rule: %v; want PERMISSION_DENIED", err) + } + if err := call(peerCtx(nil, ca), "/viewer"); status.Code(err) != codes.Unauthenticated { + t.Fatalf("no client certificate: %v; want UNAUTHENTICATED", err) + } +} + +type fakeStream struct { + ctx context.Context + sent int +} + +func (s *fakeStream) SetHeader(metadata.MD) error { return nil } +func (s *fakeStream) SendHeader(metadata.MD) error { return nil } +func (s *fakeStream) SetTrailer(metadata.MD) {} +func (s *fakeStream) Context() context.Context { return s.ctx } +func (s *fakeStream) SendMsg(any) error { s.sent++; return nil } +func (s *fakeStream) RecvMsg(any) error { return nil } + +// T4: a stream whose caller is removed from the role file ends at the reload +// with UNAUTHENTICATED, without waiting for its next message; a send after an +// expiry is refused too. +func TestStreamEndsAtTheReloadThatRevokesItsCaller(t *testing.T) { + ca := authtest.NewCA(t, "ca") + node := ca.Issue(t, "s1", time.Now().Add(time.Hour)) + a := auth.NewAuthenticator(table(t, node.Fingerprint+" node s1"), nil) + rules := map[string]auth.Rule{"/stream": {Node: true}} + ss := &fakeStream{ctx: peerCtx(node, ca)} + done := make(chan error, 1) + opened := make(chan struct{}) + go func() { + done <- a.StreamInterceptor(rules)(nil, ss, &grpc.StreamServerInfo{FullMethod: "/stream"}, func(_ any, s grpc.ServerStream) error { + if err := s.SendMsg("first"); err != nil { + return err + } + close(opened) + <-s.Context().Done() // an idle stream: no message is pending + return s.Context().Err() + }) + }() + <-opened + a.Swap(table(t, "# s1 removed")) + select { + case err := <-done: + if status.Code(err) != codes.Unauthenticated { + t.Fatalf("stream after its caller was removed: %v; want UNAUTHENTICATED", err) + } + case <-time.After(5 * time.Second): + t.Fatal("the stream did not end at the reload") + } + if ss.sent != 1 { + t.Fatalf("sent %d messages; want 1", ss.sent) + } + // A reload that keeps the caller does not end the stream. + a2 := auth.NewAuthenticator(table(t, node.Fingerprint+" node s1"), nil) + ss2 := &fakeStream{ctx: peerCtx(node, ca)} + release := make(chan struct{}) + done2 := make(chan error, 1) + go func() { + done2 <- a2.StreamInterceptor(rules)(nil, ss2, &grpc.StreamServerInfo{FullMethod: "/stream"}, func(_ any, s grpc.ServerStream) error { + select { + case <-s.Context().Done(): + return s.Context().Err() + case <-release: + return s.SendMsg("after the reload") + } + }) + }() + a2.Swap(table(t, node.Fingerprint+" node s1", "# reloaded")) + time.Sleep(50 * time.Millisecond) + close(release) + if err := <-done2; err != nil { + t.Fatalf("a reload that keeps the caller ended its stream: %v", err) + } +} diff --git a/seaweed-block/core/auth/identity.go b/seaweed-block/core/auth/identity.go index 8059f083bc..b9f5d30edf 100644 --- a/seaweed-block/core/auth/identity.go +++ b/seaweed-block/core/auth/identity.go @@ -13,6 +13,7 @@ import ( "io" "os" "strings" + "sync" "sync/atomic" "time" @@ -113,6 +114,9 @@ func LoadRoleFile(path string) (*Table, error) { type Authenticator struct { table atomic.Pointer[Table] now func() time.Time + + mu sync.Mutex + changed chan struct{} // closed (and replaced) by every Swap } // NewAuthenticator starts with t; now nil is time.Now. @@ -120,13 +124,27 @@ func NewAuthenticator(t *Table, now func() time.Time) *Authenticator { if now == nil { now = time.Now } - a := &Authenticator{now: now} + a := &Authenticator{now: now, changed: make(chan struct{})} a.table.Store(t) return a } -// Swap installs t for every later call. -func (a *Authenticator) Swap(t *Table) { a.table.Store(t) } +// Swap installs t for every later call, and wakes every open stream to +// check its caller against it. +func (a *Authenticator) Swap(t *Table) { + a.table.Store(t) + a.mu.Lock() + close(a.changed) + a.changed = make(chan struct{}) + a.mu.Unlock() +} + +// Changed is closed by the next Swap. +func (a *Authenticator) Changed() <-chan struct{} { + a.mu.Lock() + defer a.mu.Unlock() + return a.changed +} // Reload parses path and installs it; on any error the current table stays. func (a *Authenticator) Reload(path string) error { From b807b3f00d69bbeeb342922f918a56aee5bca7d1 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 08:29:40 -0800 Subject: [PATCH 03/36] feat(master): the authorization table and the server's interceptors Phase 0, S3 (master part): masterRules covers all 24 blockmaster methods (PHASE0-AUTH section 3); the gRPC server takes Config.Auth's interceptors, or development-mode ones when authentication is not configured, and Config.ServerOptions. T2: every registered method has a rule and every rule a method. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/host/master/authz.go | 62 ++++++++++++++++++++ seaweed-block/core/host/master/authz_test.go | 42 +++++++++++++ seaweed-block/core/host/master/host.go | 11 +++- 3 files changed, 114 insertions(+), 1 deletion(-) create mode 100644 seaweed-block/core/host/master/authz.go create mode 100644 seaweed-block/core/host/master/authz_test.go diff --git a/seaweed-block/core/host/master/authz.go b/seaweed-block/core/host/master/authz.go new file mode 100644 index 0000000000..c181ce8b03 --- /dev/null +++ b/seaweed-block/core/host/master/authz.go @@ -0,0 +1,62 @@ +package master + +import ( + "github.com/seaweedfs/seaweed-block/core/auth" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/rpc/link" + "google.golang.org/grpc" +) + +// masterRules is the authorization table of every blockmaster gRPC method +// (phase 0): the minimum person role, and whether a node may call it. A node +// call's own-server-id check is the handler's (auth.RequireNode); a forced +// move's admin check is MoveWorkspace's (auth.RequireRole). A method missing +// here is refused (TestMasterAuthorizationTableCoversEveryMethod). +var masterRules = map[string]auth.Rule{ + control.ObservationService_ReportHeartbeat_FullMethodName: {Node: true}, + control.ObservationService_ReportClusterEvent_FullMethodName: {Min: auth.RoleOperator}, + + control.AssignmentService_SubscribeAssignments_FullMethodName: {Node: true}, + + control.EvidenceService_QueryVolumeStatus_FullMethodName: {Min: auth.RoleViewer, Node: true}, + + control.ClusterEvidenceService_GetClusterStatus_FullMethodName: {Min: auth.RoleViewer}, + control.ClusterEvidenceService_ListVolumes_FullMethodName: {Min: auth.RoleViewer}, + control.ClusterEvidenceService_GetVolumeStatus_FullMethodName: {Min: auth.RoleViewer}, + control.ClusterEvidenceService_GetVolumeTimeline_FullMethodName: {Min: auth.RoleViewer}, + control.ClusterEvidenceService_WatchClusterEvents_FullMethodName: {Min: auth.RoleViewer}, + + control.LifecycleService_CreateVolume_FullMethodName: {Min: auth.RoleOperator}, + control.LifecycleService_DeleteVolume_FullMethodName: {Min: auth.RoleAdmin}, + control.LifecycleService_MarkVolumeDeleting_FullMethodName: {Min: auth.RoleAdmin}, + control.LifecycleService_AbortVolumeDeleting_FullMethodName: {Min: auth.RoleAdmin}, + control.LifecycleService_CommitVolumeDeleting_FullMethodName: {Min: auth.RoleAdmin}, + + control.FailbackService_ExecuteFailback_FullMethodName: {Min: auth.RoleAdmin}, + + control.WorkspaceService_RegisterWorkspaceBinding_FullMethodName: {Min: auth.RoleAdmin}, + control.WorkspaceService_PlaceWorkspace_FullMethodName: {Min: auth.RoleOperator}, + control.WorkspaceService_RenewWorkspaceLease_FullMethodName: {Node: true}, + control.WorkspaceService_AckWorkspaceRevoked_FullMethodName: {Node: true}, + control.WorkspaceService_RevokeWorkspace_FullMethodName: {Min: auth.RoleOperator}, + control.WorkspaceService_MoveWorkspace_FullMethodName: {Min: auth.RoleOperator}, // forced: admin, in the handler + control.WorkspaceService_QueryWorkspace_FullMethodName: {Min: auth.RoleViewer}, + control.WorkspaceService_QueryWorkspaceLostRange_FullMethodName: {Min: auth.RoleViewer}, + control.WorkspaceService_PreviewWorkspaceMove_FullMethodName: {Min: auth.RoleViewer}, +} + +// serverAuth returns the interceptor chain of the master's gRPC server: the +// authenticator's when authentication is configured, else development mode +// (plaintext, loopback only; every call marked as such). +func serverAuth(a *auth.Authenticator) link.ServerConfig { + if a == nil { + return link.ServerConfig{ + Unary: []grpc.UnaryServerInterceptor{auth.DevUnaryInterceptor()}, + Stream: []grpc.StreamServerInterceptor{auth.DevStreamInterceptor()}, + } + } + return link.ServerConfig{ + Unary: []grpc.UnaryServerInterceptor{a.UnaryInterceptor(masterRules)}, + Stream: []grpc.StreamServerInterceptor{a.StreamInterceptor(masterRules)}, + } +} diff --git a/seaweed-block/core/host/master/authz_test.go b/seaweed-block/core/host/master/authz_test.go new file mode 100644 index 0000000000..54208a4e2e --- /dev/null +++ b/seaweed-block/core/host/master/authz_test.go @@ -0,0 +1,42 @@ +package master + +import ( + "sort" + "testing" +) + +// T2 (phase 0): every gRPC method the master registers has a row in the +// authorization table, and every row names a registered method; a new RPC +// cannot ship without a row (an unlisted method is refused at run time). +func TestMasterAuthorizationTableCoversEveryMethod(t *testing.T) { + h, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir()}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { closeTestMaster(t, h) }) + registered := map[string]bool{} + for svc, info := range h.grpc.GetServiceInfo() { + for _, m := range info.Methods { + registered["/"+svc+"/"+m.Name] = true + } + } + var missing, stale []string + for m := range registered { + if _, ok := masterRules[m]; !ok { + missing = append(missing, m) + } + } + for m := range masterRules { + if !registered[m] { + stale = append(stale, m) + } + } + sort.Strings(missing) + sort.Strings(stale) + if len(missing) > 0 || len(stale) > 0 { + t.Fatalf("authorization table out of date: methods without a rule %v; rules without a method %v", missing, stale) + } + if len(registered) != 24 { + t.Fatalf("%d registered methods; the table was written for 24: review the new ones", len(registered)) + } +} diff --git a/seaweed-block/core/host/master/host.go b/seaweed-block/core/host/master/host.go index 6b19c836e0..5e0f187669 100644 --- a/seaweed-block/core/host/master/host.go +++ b/seaweed-block/core/host/master/host.go @@ -27,6 +27,7 @@ import ( "sync/atomic" "time" + "github.com/seaweedfs/seaweed-block/core/auth" "github.com/seaweedfs/seaweed-block/core/authority" "github.com/seaweedfs/seaweed-block/core/host/bootstrap" "github.com/seaweedfs/seaweed-block/core/lifecycle" @@ -39,6 +40,14 @@ import ( // Config holds the master host construction inputs. Flag parsing // lives in cmd/blockmaster; this type is the testable seam. type Config struct { + // Auth authenticates and authorizes every gRPC call (phase 0): nil is + // development mode (plaintext; every call is marked so, and the node + // checks admit it). + Auth *auth.Authenticator + // ServerOptions are added to the gRPC server (transport credentials, + // connection age). + ServerOptions []grpc.ServerOption + // AuthorityStoreDir is the directory passed to // authority.AcquireStoreLock + NewFileAuthorityStore. Must be // non-empty. @@ -320,7 +329,7 @@ func New(cfg Config) (*Host, error) { WriteTimeout: statusWriteTimeout, IdleTimeout: statusIdleTimeout} } - grpcSrv := link.NewServer(link.ServerConfig{}) + grpcSrv := link.NewServer(serverAuth(cfg.Auth), cfg.ServerOptions...) svc := newServices(h) control.RegisterObservationServiceServer(grpcSrv, svc) control.RegisterAssignmentServiceServer(grpcSrv, svc) From 54855c1e254205231b5e799246cee4b553d1458a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 08:41:01 -0800 Subject: [PATCH 04/36] feat(link): mutual TLS for the master links only Phase 0, S4 (transport): TLSFiles (cert, key, CA: all or none, checked at start), ServerCredentials (client certificate required and verified to the CA), ClientCredentials, DialMaster (TLS or development-mode plaintext), and a 24 h connection age. Both sides read their certificate at every handshake, so a rotated file takes effect without a restart. Dial (the SeaweedFS filer links) is unchanged. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/rpc/link/tls.go | 128 ++++++++++++++++++++++++ seaweed-block/core/rpc/link/tls_test.go | 90 +++++++++++++++++ 2 files changed, 218 insertions(+) create mode 100644 seaweed-block/core/rpc/link/tls.go create mode 100644 seaweed-block/core/rpc/link/tls_test.go diff --git a/seaweed-block/core/rpc/link/tls.go b/seaweed-block/core/rpc/link/tls.go new file mode 100644 index 0000000000..83c2386d3d --- /dev/null +++ b/seaweed-block/core/rpc/link/tls.go @@ -0,0 +1,128 @@ +package link + +import ( + "crypto/tls" + "crypto/x509" + "fmt" + "os" + "time" + + "google.golang.org/grpc" + "google.golang.org/grpc/credentials" + "google.golang.org/grpc/keepalive" +) + +// TLSFiles names one side's files for a mutual-TLS link to or from +// blockmaster (phase 0): its own certificate and key, and the CA the other +// side's certificate must verify against. All three or none. +type TLSFiles struct { + Cert, Key, CA string +} + +// Enabled reports whether any file is named. +func (f TLSFiles) Enabled() bool { return f.Cert != "" || f.Key != "" || f.CA != "" } + +// Check refuses a partial set and loads every file once, so a wrong path or +// a key that does not match its certificate fails at start, not at the +// first handshake. +func (f TLSFiles) Check() error { + if !f.Enabled() { + return nil + } + if f.Cert == "" || f.Key == "" || f.CA == "" { + return fmt.Errorf("mutual TLS needs a certificate, its key and a CA: got cert=%q key=%q ca=%q", f.Cert, f.Key, f.CA) + } + if _, err := tls.LoadX509KeyPair(f.Cert, f.Key); err != nil { + return fmt.Errorf("TLS certificate %s / key %s: %w", f.Cert, f.Key, err) + } + _, err := f.pool() + return err +} + +func (f TLSFiles) pool() (*x509.CertPool, error) { + raw, err := os.ReadFile(f.CA) + if err != nil { + return nil, fmt.Errorf("TLS CA: %w", err) + } + p := x509.NewCertPool() + if !p.AppendCertsFromPEM(raw) { + return nil, fmt.Errorf("TLS CA %s holds no PEM certificate", f.CA) + } + return p, nil +} + +// loadPair reads the certificate and key at every handshake, so a rotated +// file takes effect at the next connection without a restart. +func (f TLSFiles) loadPair() (*tls.Certificate, error) { + c, err := tls.LoadX509KeyPair(f.Cert, f.Key) + if err != nil { + return nil, fmt.Errorf("TLS certificate %s / key %s: %w", f.Cert, f.Key, err) + } + return &c, nil +} + +// ServerCredentials is blockmaster's mutual-TLS server: every client must +// present a certificate that verifies against f.CA (who it is, and what it +// may do, is the role file's: auth.PeerIdentity). +func ServerCredentials(f TLSFiles) (grpc.ServerOption, error) { + if err := f.Check(); err != nil { + return nil, err + } + pool, err := f.pool() + if err != nil { + return nil, err + } + cfg := &tls.Config{ + MinVersion: tls.VersionTLS12, + ClientAuth: tls.RequireAndVerifyClientCert, + ClientCAs: pool, + GetCertificate: func(*tls.ClientHelloInfo) (*tls.Certificate, error) { + return f.loadPair() + }, + } + return grpc.Creds(credentials.NewTLS(cfg)), nil +} + +// ClientCredentials is a mutual-TLS client of blockmaster: it presents +// f.Cert and verifies the master's certificate against f.CA. serverName +// overrides the name checked against the master's certificate ("" uses +// the dialed host). +func ClientCredentials(f TLSFiles, serverName string) (grpc.DialOption, error) { + if err := f.Check(); err != nil { + return nil, err + } + pool, err := f.pool() + if err != nil { + return nil, err + } + cfg := &tls.Config{ + MinVersion: tls.VersionTLS12, + RootCAs: pool, + ServerName: serverName, + GetClientCertificate: func(*tls.CertificateRequestInfo) (*tls.Certificate, error) { + return f.loadPair() + }, + } + return grpc.WithTransportCredentials(credentials.NewTLS(cfg)), nil +} + +// MasterConnectionAge is how long blockmaster keeps one client connection +// before it asks the client to reconnect (a fresh handshake: a rotated or +// revoked certificate is seen within this bound even on an idle link). +const MasterConnectionAge = 24 * time.Hour + +// ConnectionAge closes each server connection after age (plus a grace for +// calls in flight); clients reconnect. +func ConnectionAge(age time.Duration) grpc.ServerOption { + return grpc.KeepaliveParams(keepalive.ServerParameters{MaxConnectionAge: age, MaxConnectionAgeGrace: 30 * time.Second}) +} + +// DialMaster opens a lazy connection to blockmaster: mutual TLS when tls is +// non-nil (ClientCredentials), plaintext otherwise (development mode); opts +// follow. SeaweedFS filer links keep Dial: they are not master links. +func DialMaster(target string, tls grpc.DialOption, opts ...grpc.DialOption) (*grpc.ClientConn, error) { + if tls == nil { + return Dial(target, opts...) + } + return DialWith(target, append([]grpc.DialOption{tls}, opts...)...) +} diff --git a/seaweed-block/core/rpc/link/tls_test.go b/seaweed-block/core/rpc/link/tls_test.go new file mode 100644 index 0000000000..784be23770 --- /dev/null +++ b/seaweed-block/core/rpc/link/tls_test.go @@ -0,0 +1,90 @@ +package link_test + +import ( + "context" + "net" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/auth/authtest" + "github.com/seaweedfs/seaweed-block/core/rpc/link" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials" + "google.golang.org/grpc/health" + healthpb "google.golang.org/grpc/health/grpc_health_v1" + "google.golang.org/grpc/peer" +) + +// The master link's mutual TLS: a client with a certificate from the CA is +// served, and the server sees its verified leaf (what PeerIdentity reads); a +// client without a certificate, or with one from another CA, is refused at +// the handshake; partial or wrong files are refused at start. +func TestMasterLinkMutualTLS(t *testing.T) { + ca := authtest.NewCA(t, "ca") + dir := t.TempDir() + caPath := ca.WriteCA(t, dir) + srvCert, srvKey := ca.Issue(t, "blockmaster", time.Now().Add(time.Hour)).WriteFiles(t, dir, "master") + nodeCert, nodeKey := ca.Issue(t, "s1", time.Now().Add(time.Hour)).WriteFiles(t, dir, "s1") + + if _, err := link.ServerCredentials(link.TLSFiles{Cert: srvCert, Key: srvKey}); err == nil { + t.Fatal("a server without a CA must be refused at start") + } + if _, err := link.ServerCredentials(link.TLSFiles{Cert: srvCert, Key: nodeKey, CA: caPath}); err == nil { + t.Fatal("a key that does not match its certificate must be refused at start") + } + creds, err := link.ServerCredentials(link.TLSFiles{Cert: srvCert, Key: srvKey, CA: caPath}) + if err != nil { + t.Fatal(err) + } + seen := make(chan string, 4) + srv := link.NewServer(link.ServerConfig{Unary: []grpc.UnaryServerInterceptor{func(ctx context.Context, req any, _ *grpc.UnaryServerInfo, h grpc.UnaryHandler) (any, error) { + if p, ok := peer.FromContext(ctx); ok { + if info, ok := p.AuthInfo.(credentials.TLSInfo); ok && len(info.State.VerifiedChains) > 0 { + seen <- info.State.VerifiedChains[0][0].Subject.CommonName + } + } + return h(ctx, req) + }}}, creds, link.ConnectionAge(time.Hour)) + healthpb.RegisterHealthServer(srv, health.NewServer()) + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + go func() { _ = srv.Serve(ln) }() + t.Cleanup(srv.Stop) + + check := func(dial grpc.DialOption) error { + conn, err := link.DialMaster(ln.Addr().String(), dial) + if err != nil { + return err + } + defer conn.Close() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + _, err = healthpb.NewHealthClient(conn).Check(ctx, &healthpb.HealthCheckRequest{}) + return err + } + client, err := link.ClientCredentials(link.TLSFiles{Cert: nodeCert, Key: nodeKey, CA: caPath}, "") + if err != nil { + t.Fatal(err) + } + if err := check(client); err != nil { + t.Fatalf("a client with the CA's certificate: %v", err) + } + if cn := <-seen; cn != "s1" { + t.Fatalf("server saw verified leaf CN %q; want s1", cn) + } + if err := check(nil); err == nil { + t.Fatal("a plaintext client was served by the TLS master") + } + other := authtest.NewCA(t, "other") + odir := t.TempDir() + oc, ok := other.Issue(t, "s1", time.Now().Add(time.Hour)).WriteFiles(t, odir, "s1") + stray, err := link.ClientCredentials(link.TLSFiles{Cert: oc, Key: ok, CA: caPath}, "") + if err != nil { + t.Fatal(err) + } + if err := check(stray); err == nil { + t.Fatal("a client certificate from another CA was served") + } +} From e125c52624e6de6d247d8df9807a72f51d9bef45 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 08:44:10 -0800 Subject: [PATCH 05/36] feat(blockmaster): mutual TLS and the role file Phase 0, S4 (master side): --tls-cert, --tls-key, --tls-client-ca and --role-file together turn on mutual TLS and per-call authorization; a partial set, or authentication with --insecure-external-bind, is refused; the authenticated listener may bind any address. SIGHUP reloads the role file (a bad file keeps the previous table and says so). The start-up line gives the master's own certificate's expiry; development mode repeats its UNAUTHENTICATED warning once a minute. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/blockmaster/auth.go | 105 ++++++++++++++++++ .../cmd/blockmaster/auth_flags_test.go | 34 ++++++ seaweed-block/cmd/blockmaster/main.go | 28 ++++- 3 files changed, 166 insertions(+), 1 deletion(-) create mode 100644 seaweed-block/cmd/blockmaster/auth.go create mode 100644 seaweed-block/cmd/blockmaster/auth_flags_test.go diff --git a/seaweed-block/cmd/blockmaster/auth.go b/seaweed-block/cmd/blockmaster/auth.go new file mode 100644 index 0000000000..5f28fd30c9 --- /dev/null +++ b/seaweed-block/cmd/blockmaster/auth.go @@ -0,0 +1,105 @@ +package main + +import ( + "crypto/tls" + "crypto/x509" + "fmt" + "os" + "os/signal" + "syscall" + "time" + + "github.com/seaweedfs/seaweed-block/core/auth" + "github.com/seaweedfs/seaweed-block/core/rpc/link" + "google.golang.org/grpc" +) + +// authFlags are blockmaster's phase 0 authentication flags: its own TLS +// certificate and key, the CA every client certificate must verify against, +// and the role file (fingerprint -> role, id). All four or none; none is +// development mode (plaintext, loopback only). +type authFlags struct { + tlsCert, tlsKey, tlsClientCA, roleFile string +} + +func (a authFlags) enabled() bool { + return a.tlsCert != "" || a.tlsKey != "" || a.tlsClientCA != "" || a.roleFile != "" +} + +func (a authFlags) files() link.TLSFiles { + return link.TLSFiles{Cert: a.tlsCert, Key: a.tlsKey, CA: a.tlsClientCA} +} + +// validate refuses a partial set, and the plaintext escape hatch together +// with authentication. +func (a authFlags) validate(insecureExternalBind bool) error { + if !a.enabled() { + return nil + } + if a.tlsCert == "" || a.tlsKey == "" || a.tlsClientCA == "" || a.roleFile == "" { + return fmt.Errorf("authentication needs --tls-cert, --tls-key, --tls-client-ca and --role-file together") + } + if insecureExternalBind { + return fmt.Errorf("--insecure-external-bind cannot be combined with mutual TLS: the authenticated listener may bind any address; drop the flag") + } + return nil +} + +// build returns the authenticator and the server options of an +// authenticated master, or nil and none in development mode. Every file is +// read here, so a wrong one refuses the start. +func (a authFlags) build() (*auth.Authenticator, []grpc.ServerOption, error) { + if !a.enabled() { + return nil, nil, nil + } + creds, err := link.ServerCredentials(a.files()) + if err != nil { + return nil, nil, err + } + table, err := auth.LoadRoleFile(a.roleFile) + if err != nil { + return nil, nil, err + } + return auth.NewAuthenticator(table, nil), []grpc.ServerOption{creds, link.ConnectionAge(link.MasterConnectionAge)}, nil +} + +// certDaysLeft is the days to expiry of the certificate file at path. +func certDaysLeft(certPath, keyPath string, now time.Time) (int, time.Time, error) { + pair, err := tls.LoadX509KeyPair(certPath, keyPath) + if err != nil { + return 0, time.Time{}, err + } + leaf, err := x509.ParseCertificate(pair.Certificate[0]) + if err != nil { + return 0, time.Time{}, err + } + return int(leaf.NotAfter.Sub(now).Hours() / 24), leaf.NotAfter, nil +} + +// reloadRolesOnSIGHUP reloads the role file at every SIGHUP; a malformed or +// unreadable file keeps the current table and says so. Removing a line +// revokes that certificate at the reload (its open streams end). +func reloadRolesOnSIGHUP(a *auth.Authenticator, path string) { + hup := make(chan os.Signal, 1) + signal.Notify(hup, syscall.SIGHUP) + go func() { + for range hup { + if err := a.Reload(path); err != nil { + fmt.Fprintf(os.Stderr, "blockmaster: role file %s NOT reloaded, the previous table stays: %v\n", path, err) + continue + } + fmt.Fprintf(os.Stderr, "blockmaster: role file %s reloaded\n", path) + } + }() +} + +// warnUnauthenticated repeats the development-mode warning once a minute. +func warnUnauthenticated(listen string) { + msg := fmt.Sprintf("blockmaster: UNAUTHENTICATED CONTROL API on %s (development mode)", listen) + fmt.Fprintln(os.Stderr, msg) + go func() { + for range time.Tick(time.Minute) { + fmt.Fprintln(os.Stderr, msg) + } + }() +} diff --git a/seaweed-block/cmd/blockmaster/auth_flags_test.go b/seaweed-block/cmd/blockmaster/auth_flags_test.go new file mode 100644 index 0000000000..943e1b0389 --- /dev/null +++ b/seaweed-block/cmd/blockmaster/auth_flags_test.go @@ -0,0 +1,34 @@ +package main + +import ( + "strings" + "testing" +) + +// Phase 0 flags: the four authentication flags go together; with them the +// listener may bind any address and --insecure-external-bind is refused; +// without them the control listener stays loopback-only. +func TestAuthFlags(t *testing.T) { + base := []string{"--authority-store", t.TempDir()} + all := []string{"--tls-cert", "c.pem", "--tls-key", "k.pem", "--tls-client-ca", "ca.pem", "--role-file", "roles"} + for _, c := range []struct { + name string + args []string + want string // "" = accepted + }{ + {"development mode, loopback", []string{"--listen", "127.0.0.1:9180"}, ""}, + {"development mode, off loopback", []string{"--listen", "10.0.0.5:9180"}, "not a loopback address"}, + {"authenticated, off loopback", append([]string{"--listen", "10.0.0.5:9180"}, all...), ""}, + {"partial: no role file", []string{"--listen", "10.0.0.5:9180", "--tls-cert", "c.pem", "--tls-key", "k.pem", "--tls-client-ca", "ca.pem"}, "together"}, + {"partial: role file only", []string{"--role-file", "roles"}, "together"}, + {"authenticated with --insecure-external-bind", append([]string{"--listen", "10.0.0.5:9180", "--insecure-external-bind"}, all...), "cannot be combined"}, + } { + _, err := parseFlags(append(append([]string{}, base...), c.args...)) + switch { + case c.want == "" && err != nil: + t.Errorf("%s: %v; want accepted", c.name, err) + case c.want != "" && (err == nil || !strings.Contains(err.Error(), c.want)): + t.Errorf("%s: %v; want an error naming %q", c.name, err, c.want) + } + } +} diff --git a/seaweed-block/cmd/blockmaster/main.go b/seaweed-block/cmd/blockmaster/main.go index 7ef0c03597..14f6e4236e 100644 --- a/seaweed-block/cmd/blockmaster/main.go +++ b/seaweed-block/cmd/blockmaster/main.go @@ -71,6 +71,7 @@ type flags struct { // bound, so L2 subprocess tests can parse the ready event. // Not operator-facing; documented in the T0 smoke scenario. printReadyLine bool + auth authFlags } func parseFlags(args []string) (flags, error) { @@ -81,6 +82,10 @@ func parseFlags(args []string) (flags, error) { fs.StringVar(&f.lifecyclePlacementSeed, "lifecycle-placement-seed", "", "placement-only seed JSON; lifecycle volumes must already be registered (CreateVolume)") fs.StringVar(&f.clusterSpec, "cluster-spec", "", "cluster spec YAML; positive size_bytes imports desired volumes before topology/placement publication") fs.StringVar(&f.listen, "listen", "127.0.0.1:0", "gRPC listen address (e.g. 127.0.0.1:9180); non-loopback requires --insecure-external-bind") + fs.StringVar(&f.auth.tlsCert, "tls-cert", "", "blockmaster's TLS certificate (PEM): with --tls-key, --tls-client-ca and --role-file, every gRPC call needs mutual TLS") + fs.StringVar(&f.auth.tlsKey, "tls-key", "", "the key of --tls-cert (PEM)") + fs.StringVar(&f.auth.tlsClientCA, "tls-client-ca", "", "CA (PEM) every client certificate must verify against") + fs.StringVar(&f.auth.roleFile, "role-file", "", "role file: lines 'sha256: '; SIGHUP reloads it") fs.BoolVar(&f.insecureExternalBind, "insecure-external-bind", false, "allow the unauthenticated control listeners (--listen, --frontend-publication-runtime-listen) on non-loopback addresses") fs.StringVar(&f.topology, "topology", "", "path to accepted-topology YAML (required for assignment to mint)") fs.IntVar(&f.expectedSlotsPerVol, "expected-slots-per-volume", 3, "RF/expected slot count per volume; the controller rejects observation snapshots whose slot count differs (default 3, set to 2 for 2-node smoke clusters)") @@ -146,9 +151,14 @@ func parseFlags(args []string) (flags, error) { if err := master.ValidateStatusListen(f.statusListen); err != nil { return flags{}, err } - if err := master.ValidateControlListen("listen", f.listen, f.insecureExternalBind); err != nil { + if err := f.auth.validate(f.insecureExternalBind); err != nil { return flags{}, err } + if !f.auth.enabled() { + if err := master.ValidateControlListen("listen", f.listen, f.insecureExternalBind); err != nil { + return flags{}, err + } + } if f.frontendPublicationRuntimeHTTP { if err := master.ValidateControlListen("frontend-publication-runtime-listen", f.frontendPublicationRuntimeListen, f.insecureExternalBind); err != nil { return flags{}, err @@ -208,6 +218,19 @@ func run(f flags) int { StrictJournalIsolation: f.strictJournalIsolation, StatusListen: f.statusListen, } + authn, serverOpts, err := f.auth.build() + if err != nil { + fmt.Fprintln(os.Stderr, "blockmaster:", err) + return 1 + } + cfg.Auth, cfg.ServerOptions = authn, serverOpts + if authn != nil { + if days, until, err := certDaysLeft(f.auth.tlsCert, f.auth.tlsKey, time.Now()); err == nil { + fmt.Fprintln(os.Stderr, fmt.Sprintf("blockmaster: mutual TLS on; role file %s; own certificate expires %s (%d days)", f.auth.roleFile, until.UTC().Format(time.RFC3339), days)) + } + } else { + warnUnauthenticated(f.listen) + } if f.workspaceRPC { reader, err := master.NewWorkspaceHEADReader(f.workspaceHEADBase) if err != nil { @@ -260,6 +283,9 @@ func run(f flags) int { } h.Start() + if authn != nil { + reloadRolesOnSIGHUP(authn, f.auth.roleFile) + } if f.lifecycleLoop > 0 { go runLifecycleProductLoop(h, f.lifecycleLoop) } From 2b9d446d57b46063cccd8a08f09cc6ed93ec3471 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 08:46:37 -0800 Subject: [PATCH 06/36] feat(blockvolume): mutual TLS on the master links Phase 0, S4 (volume side): --master-tls-cert, --master-tls-key and --master-ca put the volume host's master link and the GC epoch pull on mutual TLS (the filer links are unchanged). The start is refused when the node certificate's CN differs from --server-id, when the set is partial, or together with --allow-external-status-bind. Co-Authored-By: Claude Opus 5.5 --- .../cmd/blockvolume/chunk_maintenance.go | 5 +- .../cmd/blockvolume/chunk_maintenance_test.go | 4 +- seaweed-block/cmd/blockvolume/chunk_remote.go | 5 +- seaweed-block/cmd/blockvolume/main.go | 19 +++++++- seaweed-block/cmd/blockvolume/master_tls.go | 48 +++++++++++++++++++ .../cmd/blockvolume/master_tls_test.go | 44 +++++++++++++++++ .../cmd/blockvolume/single_filer_test.go | 2 +- seaweed-block/core/host/volume/host.go | 5 +- 8 files changed, 122 insertions(+), 10 deletions(-) create mode 100644 seaweed-block/cmd/blockvolume/master_tls.go create mode 100644 seaweed-block/cmd/blockvolume/master_tls_test.go diff --git a/seaweed-block/cmd/blockvolume/chunk_maintenance.go b/seaweed-block/cmd/blockvolume/chunk_maintenance.go index 943619d0dd..daac767323 100644 --- a/seaweed-block/cmd/blockvolume/chunk_maintenance.go +++ b/seaweed-block/cmd/blockvolume/chunk_maintenance.go @@ -9,6 +9,7 @@ import ( "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" "github.com/seaweedfs/seaweed-block/core/rpc/control" "github.com/seaweedfs/seaweed-block/core/rpc/link" + "google.golang.org/grpc" ) // Automatic GC stays default-off until restart-safe unknown-CAS settlement and @@ -16,7 +17,7 @@ import ( // The CLI fixes the maximum cut/copy lifetime at five minutes and the HEAD // hydration reader at thirty seconds. A one-minute mark fits strictly inside // the one-hour grace. No elapsed TTL alone authorizes capture-intent expiry. -func newChunkMaintenance(cat *chunkstore.Catalog, blobs chunkstore.BlobDeleter, collect bool, master string) (func(context.Context, string) error, func() error, error) { +func newChunkMaintenance(cat *chunkstore.Catalog, blobs chunkstore.BlobDeleter, collect bool, master string, masterTLS grpc.DialOption) (func(context.Context, string) error, func() error, error) { closeFn := func() error { return nil } cfg := chunkstore.GCConfig{Grace: defaultChunkGCGrace, IntentTTL: defaultChunkIntentTTL} if collect { @@ -26,7 +27,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 := link.Dial(master) + conn, err := link.DialMaster(master, masterTLS) if err != nil { return nil, closeFn, err } diff --git a/seaweed-block/cmd/blockvolume/chunk_maintenance_test.go b/seaweed-block/cmd/blockvolume/chunk_maintenance_test.go index e086b1846e..b61568b10c 100644 --- a/seaweed-block/cmd/blockvolume/chunk_maintenance_test.go +++ b/seaweed-block/cmd/blockvolume/chunk_maintenance_test.go @@ -76,7 +76,7 @@ func TestMaintenanceRetentionFailureNeverStartsGC(t *testing.T) { } now = time.Now() } - pass, closeFn, err := newChunkMaintenance(cat, maintenanceBlobs{}, true, "unused-master:1234") + pass, closeFn, err := newChunkMaintenance(cat, maintenanceBlobs{}, true, "unused-master:1234", nil) if err != nil { t.Fatal(err) } @@ -103,7 +103,7 @@ func TestMaintenanceDefaultRetainNeedsNoEpochClient(t *testing.T) { if _, err = cat.EnsureVolume(context.Background(), "v", chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}); err != nil { t.Fatal(err) } - pass, closeFn, err := newChunkMaintenance(cat, nil, false, "") + pass, closeFn, err := newChunkMaintenance(cat, nil, false, "", nil) if err != nil { t.Fatal(err) } diff --git a/seaweed-block/cmd/blockvolume/chunk_remote.go b/seaweed-block/cmd/blockvolume/chunk_remote.go index c54a0f7cfd..c6b80aa4ca 100644 --- a/seaweed-block/cmd/blockvolume/chunk_remote.go +++ b/seaweed-block/cmd/blockvolume/chunk_remote.go @@ -18,6 +18,7 @@ import ( "github.com/seaweedfs/seaweed-block/core/frontend/durable" "github.com/seaweedfs/seaweed-block/core/hostlimit" "github.com/seaweedfs/seaweed-block/core/storage" + "google.golang.org/grpc" ) const ( @@ -162,7 +163,7 @@ type chunkWiring struct { // newChunkWiring dials the filer and refuses unless it is the only filer of // its group (chunkstore.CheckSingleFiler). -func newChunkWiring(c chunkFlags, master ...string) (chunkWiring, error) { +func newChunkWiring(c chunkFlags, masterTLS grpc.DialOption, master ...string) (chunkWiring, error) { client, err := chunkstore.DialSWFS(chunkstore.SWFSConfig{ FilerGRPC: c.filer, Collection: c.collection, @@ -186,7 +187,7 @@ func newChunkWiring(c chunkFlags, master ...string) (chunkWiring, error) { if len(master) > 0 { masterAddr = master[0] } - maintenance, closeMaintenance, err := newChunkMaintenance(cat, client, c.automaticGC, masterAddr) + maintenance, closeMaintenance, err := newChunkMaintenance(cat, client, c.automaticGC, masterAddr, masterTLS) if err != nil { _ = client.Close() return chunkWiring{}, err diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index 939191bdcc..8de5ca2de2 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -33,6 +33,7 @@ import ( "github.com/seaweedfs/seaweed-block/core/recovery" "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/storage" "github.com/seaweedfs/seaweed-block/core/storeident" "github.com/seaweedfs/seaweed-block/core/transport" @@ -72,6 +73,7 @@ type flags struct { // External status bind is off by default. Node-loss gates opt in so // blockmaster can probe surviving replicas across Kubernetes nodes. allowExternalStatusBind bool + masterTLS link.TLSFiles // the master link's mutual TLS (phase 0) runtimeRebuildEndpoint bool // iSCSI frontend flags. iscsiListen is the TCP address the iSCSI @@ -180,6 +182,9 @@ func parseFlags(args []string) (flags, error) { fs.Int64Var(&f.memoryLimitMiB, "memory-limit-mib", 4*storage.DefaultCutPayloadMemoryBudget/(1<<20), "process Go soft memory limit in MiB (0 preserves GOMEMLIMIT); explicit GOMEMLIMIT is preserved unless this flag is set") fs.StringVar(&f.masterAddr, "master", "", "master gRPC address (required)") fs.StringVar(&f.serverID, "server-id", "", "this server identity (required)") + fs.StringVar(&f.masterTLS.Cert, "master-tls-cert", "", "this node's certificate (PEM) for mutual TLS to blockmaster; its CN must equal --server-id") + fs.StringVar(&f.masterTLS.Key, "master-tls-key", "", "the key of --master-tls-cert (PEM)") + fs.StringVar(&f.masterTLS.CA, "master-ca", "", "CA (PEM) blockmaster's certificate must verify against") fs.StringVar(&f.volumeID, "volume-id", "", "served volume (required)") fs.StringVar(&f.replicaID, "replica-id", "", "served replica (required)") fs.StringVar(&f.dataAddr, "data-addr", "", "data-path address (required)") @@ -293,6 +298,9 @@ func parseFlags(args []string) (flags, error) { if f.version { return f, nil } + if err := checkMasterTLS(f); err != nil { + return flags{}, err + } if f.volumeLockDirTestOnly != "" && os.Getenv("INVOCATION_ID") != "" { return flags{}, fmt.Errorf("--%s is test-only and refused under systemd (INVOCATION_ID is set): the one-process-per-host guarantee needs %s", volumeLockDirTestOnlyFlag, durable.HostVolumeLockDir) } @@ -617,7 +625,14 @@ func runVolume(f flags, exits *processExit) int { defer stopProfile() readyCh := make(chan adapter.AssignmentInfo, 16) - h, err := volume.New(hostConfig(f, readyCh)) + dialTLS, err := masterDialTLS(f) + if err != nil { + fmt.Fprintln(os.Stderr, "blockvolume:", err) + return 1 + } + hc := hostConfig(f, readyCh) + hc.MasterTLS = dialTLS + h, err := volume.New(hc) if err != nil { fmt.Fprintln(os.Stderr, "blockvolume:", err) return 1 @@ -689,7 +704,7 @@ func runVolume(f flags, exits *processExit) int { var chunkErr error var chunk chunkWiring if cfg.Impl == durable.ImplWALStoreChunk { - chunk, chunkErr = newChunkWiring(f.chunk, f.masterAddr) + chunk, chunkErr = newChunkWiring(f.chunk, dialTLS, f.masterAddr) cfg.ChunkCaptureInterval = f.chunk.captureInterval cfg.ChunkCutTimeout = defaultChunkCutTimeout cfg.ChunkMaintenanceInterval = f.chunk.maintenanceInterval diff --git a/seaweed-block/cmd/blockvolume/master_tls.go b/seaweed-block/cmd/blockvolume/master_tls.go new file mode 100644 index 0000000000..780b4914ce --- /dev/null +++ b/seaweed-block/cmd/blockvolume/master_tls.go @@ -0,0 +1,48 @@ +package main + +import ( + "crypto/tls" + "crypto/x509" + "fmt" + + "github.com/seaweedfs/seaweed-block/core/rpc/link" + "google.golang.org/grpc" +) + +// checkMasterTLS checks the master link's mutual-TLS flags at start (phase +// 0): all three files load; the node certificate's CN equals --server-id +// (one node certificate per server id; the master enforces the same rule +// through the role file); and an authenticated volume never listens off +// loopback. +func checkMasterTLS(f flags) error { + if !f.masterTLS.Enabled() { + return nil + } + if err := f.masterTLS.Check(); err != nil { + return fmt.Errorf("--master-tls-cert/--master-tls-key/--master-ca: %w", err) + } + pair, err := tls.LoadX509KeyPair(f.masterTLS.Cert, f.masterTLS.Key) + if err != nil { + return err + } + leaf, err := x509.ParseCertificate(pair.Certificate[0]) + if err != nil { + return fmt.Errorf("--master-tls-cert %s: %w", f.masterTLS.Cert, err) + } + if leaf.Subject.CommonName != f.serverID { + return fmt.Errorf("--master-tls-cert %s has CN=%q but --server-id is %q: a node certificate names its server id; issue one with CN=%s", f.masterTLS.Cert, leaf.Subject.CommonName, f.serverID, f.serverID) + } + if f.allowExternalStatusBind { + return fmt.Errorf("--allow-external-status-bind cannot be combined with --master-tls-cert: an authenticated volume's status listener stays on loopback") + } + return nil +} + +// masterDialTLS is the master link's dial option: mutual TLS when the flags +// name the files, nil (development-mode plaintext) otherwise. +func masterDialTLS(f flags) (grpc.DialOption, error) { + if !f.masterTLS.Enabled() { + return nil, nil + } + return link.ClientCredentials(f.masterTLS, "") +} diff --git a/seaweed-block/cmd/blockvolume/master_tls_test.go b/seaweed-block/cmd/blockvolume/master_tls_test.go new file mode 100644 index 0000000000..c797e60280 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/master_tls_test.go @@ -0,0 +1,44 @@ +package main + +import ( + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/auth/authtest" +) + +// Phase 0: the volume's master-link TLS flags are checked at start: a node +// certificate whose CN differs from --server-id, a partial set, or TLS with +// --allow-external-status-bind refuses the start with a cure line. +func TestMasterTLSFlags(t *testing.T) { + ca := authtest.NewCA(t, "ca") + dir := t.TempDir() + caPath := ca.WriteCA(t, dir) + good, goodKey := ca.Issue(t, "m02", time.Now().Add(time.Hour)).WriteFiles(t, dir, "m02") // --server-id=m02 in the base args + other, otherKey := ca.Issue(t, "s9", time.Now().Add(time.Hour)).WriteFiles(t, dir, "s9") + base := phase150RequiredBlockvolumeArgs() + for _, c := range []struct { + name string + args []string + want string // "" = accepted + }{ + {"no TLS (development mode)", nil, ""}, + {"CN equals --server-id", []string{"--master-tls-cert", good, "--master-tls-key", goodKey, "--master-ca", caPath}, ""}, + {"CN differs from --server-id", []string{"--master-tls-cert", other, "--master-tls-key", otherKey, "--master-ca", caPath}, `CN="s9" but --server-id is "m02"`}, + {"no CA", []string{"--master-tls-cert", good, "--master-tls-key", goodKey}, "a certificate, its key and a CA"}, + {"with --allow-external-status-bind", []string{"--master-tls-cert", good, "--master-tls-key", goodKey, "--master-ca", caPath, "--allow-external-status-bind"}, "cannot be combined"}, + } { + f, err := parseFlags(append(append([]string{}, base...), c.args...)) + switch { + case c.want == "" && err != nil: + t.Errorf("%s: %v; want accepted", c.name, err) + case c.want != "" && (err == nil || !strings.Contains(err.Error(), c.want)): + t.Errorf("%s: %v; want an error naming %q", c.name, err, c.want) + case c.want == "" && c.args != nil: + if d, err := masterDialTLS(f); err != nil || d == nil { + t.Errorf("%s: dial option %v %v; want mutual TLS", c.name, d, err) + } + } + } +} diff --git a/seaweed-block/cmd/blockvolume/single_filer_test.go b/seaweed-block/cmd/blockvolume/single_filer_test.go index c4cc3ccbd8..74e338f39e 100644 --- a/seaweed-block/cmd/blockvolume/single_filer_test.go +++ b/seaweed-block/cmd/blockvolume/single_filer_test.go @@ -76,7 +76,7 @@ func TestChunkWiringRefusesAMultiFilerGroup(t *testing.T) { filerpb.RegisterSeaweedFilerServer(srv, &groupFiler{master: "127.0.0.1:9333." + mport}) go func() { _ = srv.Serve(lis) }() t.Cleanup(srv.Stop) - w, err := newChunkWiring(chunkFlags{filer: filer, path: defaultChunkPath}) + w, err := newChunkWiring(chunkFlags{filer: filer, path: defaultChunkPath}, nil) if c.ok { if err != nil { t.Fatalf("one filer refused: %v", err) diff --git a/seaweed-block/core/host/volume/host.go b/seaweed-block/core/host/volume/host.go index 78b5613748..2a8ee27965 100644 --- a/seaweed-block/core/host/volume/host.go +++ b/seaweed-block/core/host/volume/host.go @@ -27,6 +27,9 @@ import ( type Config struct { // MasterAddr is the gRPC address of the block master daemon. MasterAddr string + // MasterTLS is the mutual-TLS dial option of the master link + // (link.ClientCredentials); nil dials plaintext (development mode). + MasterTLS grpc.DialOption // ServerID identifies this volume process to the master. // Used as the HeartbeatReport.ServerID field. @@ -267,7 +270,7 @@ func New(cfg Config) (*Host, error) { lg = log.Default() } - conn, err := link.Dial(cfg.MasterAddr) + conn, err := link.DialMaster(cfg.MasterAddr, cfg.MasterTLS) if err != nil { return nil, fmt.Errorf("volume.New: dial master %q: %w", cfg.MasterAddr, err) } From 98b46ecad3619e12ec35f94335a2f28b035674b7 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 08:47:33 -0800 Subject: [PATCH 07/36] test: phase 0 red: forced move needs an admin; a node acts only for its own id Co-Authored-By: Claude Opus 5.5 --- .../core/host/master/auth_red_test.go | 161 ++++++++++++++++++ 1 file changed, 161 insertions(+) create mode 100644 seaweed-block/core/host/master/auth_red_test.go diff --git a/seaweed-block/core/host/master/auth_red_test.go b/seaweed-block/core/host/master/auth_red_test.go new file mode 100644 index 0000000000..e1a122d9c3 --- /dev/null +++ b/seaweed-block/core/host/master/auth_red_test.go @@ -0,0 +1,161 @@ +package master + +import ( + "context" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/auth" + "github.com/seaweedfs/seaweed-block/core/auth/authtest" + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/lifecycle" + 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/status" + "google.golang.org/protobuf/types/known/timestamppb" +) + +// authMaster is a started blockmaster with mutual TLS and a role file: +// node-a and node-b (node), alice (operator), root (admin). dial opens a +// connection as one of them. +type authMaster struct { + h *Host + dial func(who string) *grpc.ClientConn +} + +func startAuthMaster(t *testing.T) authMaster { + t.Helper() + ca := authtest.NewCA(t, "test-ca") + dir := t.TempDir() + caPath := ca.WriteCA(t, dir) + expiry := time.Now().Add(time.Hour) + srvCert, srvKey := ca.Issue(t, "blockmaster", expiry).WriteFiles(t, dir, "master") + leaves := map[string]*authtest.Leaf{} + var lines []string + for who, role := range map[string]string{"node-a": "node", "node-b": "node", "alice": "operator", "root": "admin"} { + leaves[who] = ca.Issue(t, who, expiry) + lines = append(lines, leaves[who].Fingerprint+" "+role+" "+who) + } + table, err := auth.ParseRoleFile(strings.NewReader(strings.Join(lines, "\n"))) + if err != nil { + t.Fatal(err) + } + creds, err := link.ServerCredentials(link.TLSFiles{Cert: srvCert, Key: srvKey, CA: caPath}) + if err != nil { + t.Fatal(err) + } + h, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, + WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { + return authority.WorkspaceHead{Gen: 2, Epoch: 1, Holder: "node-a/r1"}, nil + }, + Auth: auth.NewAuthenticator(table, nil), ServerOptions: []grpc.ServerOption{creds}}) + if err != nil { + t.Fatal(err) + } + h.Start() + t.Cleanup(func() { closeTestMaster(t, h) }) + for _, server := range []string{"node-a", "node-b"} { + if _, err := h.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: server, DataAddr: "127.0.0.1:9200", CtrlAddr: "127.0.0.1:9100"}); err != nil { + t.Fatal(err) + } + } + return authMaster{h: h, dial: func(who string) *grpc.ClientConn { + t.Helper() + cert, key := leaves[who].WriteFiles(t, t.TempDir(), who) + d, err := link.ClientCredentials(link.TLSFiles{Cert: cert, Key: key, CA: caPath}, "") + if err != nil { + t.Fatal(err) + } + c, err := link.DialMaster(h.Addr(), d) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { c.Close() }) + return c + }} +} + +// lineOnNodeA creates v placed on node-a, publishes its line and grants +// node-a its lease, all through authenticated callers. +func (m authMaster) lineOnNodeA(t *testing.T, ctx context.Context) authority.AuthorityBasis { + t.Helper() + root, alice, nodeA := m.dial("root"), m.dial("alice"), m.dial("node-a") + if _, err := control.NewLifecycleServiceClient(alice).CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: "v", SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil { + t.Fatal("operator CreateVolume:", err) + } + b := &control.WorkspaceBinding{VolumeId: "v", ServerId: "node-a", DataAddr: "127.0.0.1:10000", CtrlAddr: "127.0.0.1:10001"} + if _, err := control.NewWorkspaceServiceClient(root).RegisterWorkspaceBinding(ctx, b); err != nil { + t.Fatal("admin RegisterWorkspaceBinding:", err) + } + if _, err := control.NewWorkspaceServiceClient(alice).PlaceWorkspace(ctx, &control.WorkspacePlacement{VolumeId: "v", ServerId: "node-a", ReplicaId: "r1"}); err != nil { + t.Fatal("operator PlaceWorkspace:", err) + } + if _, err := control.NewObservationServiceClient(nodeA).ReportHeartbeat(ctx, &control.HeartbeatReport{ServerId: "node-a", SentAt: timestamppb.Now(), Reachable: true, Eligible: true, + Slots: []*control.HeartbeatSlot{{VolumeId: "v", ReplicaId: "r1", DataAddr: b.DataAddr, CtrlAddr: b.CtrlAddr}}}); err != nil { + t.Fatal("node-a heartbeat:", err) + } + if _, err := m.h.RunLifecycleProductTick(); err != nil { + t.Fatal(err) + } + line := waitAuthorityLine(t, m.h.Publisher(), "v") + if _, err := control.NewWorkspaceServiceClient(nodeA).RenewWorkspaceLease(ctx, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r1", Epoch: line.Epoch, ServerId: "node-a"}); err != nil { + t.Fatal("node-a renewal:", err) + } + return line +} + +// T5 (phase 0 red): an operator's forced move is admitted today; it needs an +// admin (PERMISSION_DENIED before any barrier or lease check). An admin's +// forced move passes authorization (and then meets the barrier). +func TestForcedMoveNeedsAnAdmin(t *testing.T) { + m := startAuthMaster(t) + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + line := m.lineOnNodeA(t, ctx) + move := &control.WorkspaceMove{RequestId: "f1", VolumeId: "v", ExpectedReplicaId: "r1", ExpectedEpoch: line.Epoch, TargetReplicaId: "r1", + TargetServerId: "node-b", TargetDataAddr: "127.0.0.1:20000", TargetCtrlAddr: "127.0.0.1:20001", Kind: "forced", Force: true} + _, err := control.NewWorkspaceServiceClient(m.dial("alice")).MoveWorkspace(ctx, move) + if status.Code(err) != codes.PermissionDenied { + t.Fatalf("an operator's forced move: %v; want PERMISSION_DENIED", err) + } + move.RequestId = "f2" + _, err = control.NewWorkspaceServiceClient(m.dial("root")).MoveWorkspace(ctx, move) + if code := status.Code(err); code == codes.PermissionDenied || code == codes.Unauthenticated { + t.Fatalf("an admin's forced move refused by authorization: %v", err) + } +} + +// T5 / T8 (phase 0 red): a node acts only for its own server id. Today a +// heartbeat that names node-a but comes from node-b's certificate is +// accepted (only the addresses inside the report are compared), and node-b +// can renew node-a's lease (the address check passes on one host). +func TestNodeActsOnlyForItsOwnServerID(t *testing.T) { + m := startAuthMaster(t) + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + line := m.lineOnNodeA(t, ctx) + nodeB := m.dial("node-b") + _, err := control.NewObservationServiceClient(nodeB).ReportHeartbeat(ctx, &control.HeartbeatReport{ServerId: "node-a", SentAt: timestamppb.Now(), Reachable: true, Eligible: true, + Slots: []*control.HeartbeatSlot{{VolumeId: "v", ReplicaId: "r1", DataAddr: "127.0.0.1:10000", CtrlAddr: "127.0.0.1:10001"}}}) + if status.Code(err) != codes.PermissionDenied { + t.Fatalf("node-b's heartbeat naming node-a: %v; want PERMISSION_DENIED", err) + } + _, err = control.NewWorkspaceServiceClient(nodeB).RenewWorkspaceLease(ctx, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r1", Epoch: line.Epoch, ServerId: "node-a"}) + if status.Code(err) != codes.PermissionDenied { + t.Fatalf("node-b renewing node-a's lease: %v; want PERMISSION_DENIED", err) + } + _, err = control.NewWorkspaceServiceClient(nodeB).AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r1", Epoch: line.Epoch, ServerId: "node-a"}, HeadGen: 2}) + if status.Code(err) != codes.PermissionDenied { + t.Fatalf("node-b ACKing for node-a: %v; want PERMISSION_DENIED", err) + } + stream, err := control.NewAssignmentServiceClient(nodeB).SubscribeAssignments(ctx, &control.SubscribeRequest{VolumeId: "v", ReplicaId: "r1", ServerId: "node-a"}) + if err == nil { + _, err = stream.Recv() + } + if status.Code(err) != codes.PermissionDenied { + t.Fatalf("node-b subscribing as node-a: %v; want PERMISSION_DENIED", err) + } +} From ec049adacb704c4d5ac35b7d7f69b5b27f5d29c8 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 09:05:58 -0800 Subject: [PATCH 08/36] feat(master): node calls only for their own server id; forced move needs admin Phase 0, S5: heartbeat, assignment stream (every volume), renewal and ACK require the caller's certificate id to be the request's server id (auth.RequireNode); the registered-host address checks stay beside it. QueryVolumeStatus admits a node only for a volume whose line it holds. A forced MoveWorkspace needs an admin. Development mode admits as before. T2 starts its master. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/host/master/authz.go | 18 ++++++++++++++++++ seaweed-block/core/host/master/authz_test.go | 1 + seaweed-block/core/host/master/services.go | 12 ++++++++++++ .../core/host/master/workspace_service.go | 15 +++++++++++++++ 4 files changed, 46 insertions(+) diff --git a/seaweed-block/core/host/master/authz.go b/seaweed-block/core/host/master/authz.go index c181ce8b03..e7ca02465d 100644 --- a/seaweed-block/core/host/master/authz.go +++ b/seaweed-block/core/host/master/authz.go @@ -1,10 +1,13 @@ package master import ( + "context" "github.com/seaweedfs/seaweed-block/core/auth" 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/status" ) // masterRules is the authorization table of every blockmaster gRPC method @@ -60,3 +63,18 @@ func serverAuth(a *auth.Authenticator) link.ServerConfig { Stream: []grpc.StreamServerInterceptor{a.StreamInterceptor(masterRules)}, } } + +// requireLineHolderNode admits a person (the method's rule already did) or a +// node whose server id owns vol's published line (the GC epoch pull); any +// other node is refused. +func (s *services) requireLineHolderNode(ctx context.Context, vol string) error { + p, ok := auth.FromContext(ctx) + if !ok || p.Role != auth.RoleNode { + return nil + } + line, published := s.host.Publisher().PublishedAuthorityLine(vol) + if published && s.host.workspaceLineOwner(line, vol, line.ReplicaID, line.Epoch) == p.ID { + return nil + } + return status.Errorf(codes.PermissionDenied, "node %s does not hold volume %s's line", p.ID, vol) +} diff --git a/seaweed-block/core/host/master/authz_test.go b/seaweed-block/core/host/master/authz_test.go index 54208a4e2e..a4329ebed7 100644 --- a/seaweed-block/core/host/master/authz_test.go +++ b/seaweed-block/core/host/master/authz_test.go @@ -13,6 +13,7 @@ func TestMasterAuthorizationTableCoversEveryMethod(t *testing.T) { if err != nil { t.Fatal(err) } + h.Start() t.Cleanup(func() { closeTestMaster(t, h) }) registered := map[string]bool{} for svc, info := range h.grpc.GetServiceInfo() { diff --git a/seaweed-block/core/host/master/services.go b/seaweed-block/core/host/master/services.go index ae22453d36..a2ea390bb4 100644 --- a/seaweed-block/core/host/master/services.go +++ b/seaweed-block/core/host/master/services.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "github.com/seaweedfs/seaweed-block/core/auth" "sync/atomic" "time" @@ -286,6 +287,10 @@ func (s *services) ReportHeartbeat(ctx context.Context, r *control.HeartbeatRepo if err := validateHeartbeat(r); err != nil { return nil, err } + // Phase 0: a node reports only for its own server id (TERM-CALLER-001). + if err := auth.RequireNode(ctx, r.ServerId); err != nil { + return nil, err + } // Journal isolation: alarm on a durable root sharing the authority // store's file system; under strict isolation refuse it unless the node // already serves volumes (refusing a serving node stops its renewals). @@ -380,6 +385,10 @@ func (s *services) SubscribeAssignments(req *control.SubscribeRequest, stream co if req.VolumeId == "" { return fmt.Errorf("subscribe: volume_id required") } + // Phase 0: a node subscribes only as its own server id, for every volume. + if err := auth.RequireNode(stream.Context(), req.GetServerId()); err != nil { + return err + } pub := s.host.boot.Publisher ctx := stream.Context() @@ -487,6 +496,9 @@ func (s *services) QueryVolumeStatus(ctx context.Context, req *control.StatusReq if req.VolumeId == "" { return nil, fmt.Errorf("status: volume_id required") } + if err := s.requireLineHolderNode(ctx, req.VolumeId); err != nil { + return nil, err + } pub := s.host.boot.Publisher ctrl := s.host.ctrl diff --git a/seaweed-block/core/host/master/workspace_service.go b/seaweed-block/core/host/master/workspace_service.go index 04981c09fa..fd0d31f601 100644 --- a/seaweed-block/core/host/master/workspace_service.go +++ b/seaweed-block/core/host/master/workspace_service.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "github.com/seaweedfs/seaweed-block/core/auth" "strings" "time" @@ -99,6 +100,10 @@ func (s *services) holderMatches(ctx context.Context, volume, replica, server st } func (s *services) RenewWorkspaceLease(ctx context.Context, q *control.WorkspaceIdentity) (*control.WorkspaceLeaseFact, error) { + // Phase 0: the holder's server id is the caller's certificate's id. + if err := auth.RequireNode(ctx, q.GetServerId()); err != nil { + return nil, err + } if err := s.workspaceVolumeForRenewal(q.GetVolumeId()); err != nil { return nil, err } @@ -130,6 +135,9 @@ func (s *services) RevokeWorkspace(ctx context.Context, q *control.WorkspaceIden } func (s *services) AckWorkspaceRevoked(ctx context.Context, q *control.WorkspaceRevocationAck) (*control.WorkspaceEmpty, error) { + if err := auth.RequireNode(ctx, q.GetIdentity().GetServerId()); err != nil { + return nil, err + } s.host.workspaceMu.Lock() defer s.host.workspaceMu.Unlock() id := q.GetIdentity() @@ -203,6 +211,13 @@ func (s *services) logForcedGrant(g *control.WorkspaceGrant, replay bool, postIs } func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) (_ *control.WorkspaceGrant, resultErr error) { + // Phase 0: a forced move (it may lose acknowledged writes) needs an + // admin; a clean move an operator (the method's rule). + if q.GetKind() == "forced" || q.GetForce() { + if err := auth.RequireRole(ctx, auth.RoleAdmin); err != nil { + return nil, err + } + } // Remote reads never hold the workspace mutation lock. Re-read every // local precondition below; Publisher checks the expected epoch atomically. // A refusal is logged after the lock is released (deferred first, so it From 7b965705050514f400b49367ed18f7a39d857fd0 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 09:07:36 -0800 Subject: [PATCH 09/36] feat(auth): the append-only audit log Phase 0, S6: AuditLog writes one JSON line per event: every operator and admin call (accepted or refused, including a handler's RequireRole refusal), refused node calls at most once a minute per (fingerprint, result, method), and every role-file reload with its outcome; accepted node calls are not recorded. blockmaster --audit-log turns it on (with authentication only). Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/blockmaster/auth.go | 14 ++- .../cmd/blockmaster/auth_flags_test.go | 1 + seaweed-block/cmd/blockmaster/main.go | 1 + seaweed-block/core/auth/audit.go | 112 ++++++++++++++++++ seaweed-block/core/auth/audit_test.go | 76 ++++++++++++ seaweed-block/core/auth/authorize.go | 33 ++++-- seaweed-block/core/auth/identity.go | 6 + 7 files changed, 233 insertions(+), 10 deletions(-) create mode 100644 seaweed-block/core/auth/audit.go create mode 100644 seaweed-block/core/auth/audit_test.go diff --git a/seaweed-block/cmd/blockmaster/auth.go b/seaweed-block/cmd/blockmaster/auth.go index 5f28fd30c9..59ea9c54a3 100644 --- a/seaweed-block/cmd/blockmaster/auth.go +++ b/seaweed-block/cmd/blockmaster/auth.go @@ -20,6 +20,7 @@ import ( // development mode (plaintext, loopback only). type authFlags struct { tlsCert, tlsKey, tlsClientCA, roleFile string + auditLog string // append-only audit log (optional) } func (a authFlags) enabled() bool { @@ -33,6 +34,9 @@ func (a authFlags) files() link.TLSFiles { // validate refuses a partial set, and the plaintext escape hatch together // with authentication. func (a authFlags) validate(insecureExternalBind bool) error { + if a.auditLog != "" && !a.enabled() { + return fmt.Errorf("--audit-log needs authentication (--tls-cert, --tls-key, --tls-client-ca, --role-file)") + } if !a.enabled() { return nil } @@ -60,7 +64,15 @@ func (a authFlags) build() (*auth.Authenticator, []grpc.ServerOption, error) { if err != nil { return nil, nil, err } - return auth.NewAuthenticator(table, nil), []grpc.ServerOption{creds, link.ConnectionAge(link.MasterConnectionAge)}, nil + authn := auth.NewAuthenticator(table, nil) + if a.auditLog != "" { + l, _, err := auth.OpenAuditLog(a.auditLog) + if err != nil { + return nil, nil, err + } + authn.SetAudit(l) + } + return authn, []grpc.ServerOption{creds, link.ConnectionAge(link.MasterConnectionAge)}, nil } // certDaysLeft is the days to expiry of the certificate file at path. diff --git a/seaweed-block/cmd/blockmaster/auth_flags_test.go b/seaweed-block/cmd/blockmaster/auth_flags_test.go index 943e1b0389..e5ae321dc9 100644 --- a/seaweed-block/cmd/blockmaster/auth_flags_test.go +++ b/seaweed-block/cmd/blockmaster/auth_flags_test.go @@ -21,6 +21,7 @@ func TestAuthFlags(t *testing.T) { {"authenticated, off loopback", append([]string{"--listen", "10.0.0.5:9180"}, all...), ""}, {"partial: no role file", []string{"--listen", "10.0.0.5:9180", "--tls-cert", "c.pem", "--tls-key", "k.pem", "--tls-client-ca", "ca.pem"}, "together"}, {"partial: role file only", []string{"--role-file", "roles"}, "together"}, + {"audit log without authentication", []string{"--audit-log", "audit.log"}, "needs authentication"}, {"authenticated with --insecure-external-bind", append([]string{"--listen", "10.0.0.5:9180", "--insecure-external-bind"}, all...), "cannot be combined"}, } { _, err := parseFlags(append(append([]string{}, base...), c.args...)) diff --git a/seaweed-block/cmd/blockmaster/main.go b/seaweed-block/cmd/blockmaster/main.go index 14f6e4236e..7d750695a8 100644 --- a/seaweed-block/cmd/blockmaster/main.go +++ b/seaweed-block/cmd/blockmaster/main.go @@ -85,6 +85,7 @@ func parseFlags(args []string) (flags, error) { fs.StringVar(&f.auth.tlsCert, "tls-cert", "", "blockmaster's TLS certificate (PEM): with --tls-key, --tls-client-ca and --role-file, every gRPC call needs mutual TLS") fs.StringVar(&f.auth.tlsKey, "tls-key", "", "the key of --tls-cert (PEM)") fs.StringVar(&f.auth.tlsClientCA, "tls-client-ca", "", "CA (PEM) every client certificate must verify against") + fs.StringVar(&f.auth.auditLog, "audit-log", "", "append-only audit log (JSON lines): every operator and admin call, refused node calls, role-file reloads") fs.StringVar(&f.auth.roleFile, "role-file", "", "role file: lines 'sha256: '; SIGHUP reloads it") fs.BoolVar(&f.insecureExternalBind, "insecure-external-bind", false, "allow the unauthenticated control listeners (--listen, --frontend-publication-runtime-listen) on non-loopback addresses") fs.StringVar(&f.topology, "topology", "", "path to accepted-topology YAML (required for assignment to mint)") diff --git a/seaweed-block/core/auth/audit.go b/seaweed-block/core/auth/audit.go new file mode 100644 index 0000000000..eb89f8263b --- /dev/null +++ b/seaweed-block/core/auth/audit.go @@ -0,0 +1,112 @@ +package auth + +import ( + "encoding/json" + "fmt" + "io" + "os" + "sync" + "time" + + "google.golang.org/grpc/status" +) + +// AuditEvent is one line of the append-only audit log (JSON). +type AuditEvent struct { + Time time.Time `json:"time"` + Event string `json:"event"` // "call" or "reload" + Method string `json:"method,omitempty"` + Role Role `json:"role,omitempty"` + ID string `json:"id,omitempty"` + Fingerprint string `json:"fingerprint,omitempty"` + Result string `json:"result"` // "ok", or the refusal's gRPC code + Reason string `json:"reason,omitempty"` +} + +// AuditLog appends events to a writer, one JSON object per line. Nothing +// reads it to decide anything. Accepted node calls (renewals, ACKs, +// heartbeats, streams) are not recorded; a refused node call is recorded at +// most once per minute per (fingerprint, reason); every person's call and +// every role-file reload is recorded. +type AuditLog struct { + mu sync.Mutex + w io.Writer + now func() time.Time + refused map[string]time.Time + errs int // writes that failed (the log never fails a call) +} + +// NewAuditLog writes to w; now nil is time.Now. +func NewAuditLog(w io.Writer, now func() time.Time) *AuditLog { + if now == nil { + now = time.Now + } + return &AuditLog{w: w, now: now, refused: map[string]time.Time{}} +} + +// OpenAuditLog appends to the file at path (created 0600 when missing). +func OpenAuditLog(path string) (*AuditLog, *os.File, error) { + f, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0o600) + if err != nil { + return nil, nil, fmt.Errorf("audit log: %w", err) + } + return NewAuditLog(f, nil), f, nil +} + +func (l *AuditLog) write(e AuditEvent) { + raw, err := json.Marshal(e) + if err == nil { + _, err = l.w.Write(append(raw, '\n')) + } + if err != nil { + l.errs++ + } +} + +// call records one call's outcome under the rules above. p is zero when +// the caller could not be authenticated. +func (l *AuditLog) call(method string, p Principal, err error) { + if l == nil { + return + } + l.mu.Lock() + defer l.mu.Unlock() + now := l.now() + e := AuditEvent{Time: now, Event: "call", Method: method, Role: p.Role, ID: p.ID, Fingerprint: p.Fingerprint, Result: "ok"} + if err != nil { + st, _ := status.FromError(err) + e.Result, e.Reason = st.Code().String(), st.Message() + } + if p.Role == RoleNode || (p.Role == "" && err != nil) { + if err == nil { + return // accepted node calls are not audited + } + key := p.Fingerprint + "|" + e.Result + "|" + method + if last, seen := l.refused[key]; seen && now.Sub(last) < time.Minute { + return + } + l.refused[key] = now + } + l.write(e) +} + +// Reload records a role-file reload and its outcome. +func (l *AuditLog) Reload(path string, err error) { + if l == nil { + return + } + l.mu.Lock() + defer l.mu.Unlock() + e := AuditEvent{Time: l.now(), Event: "reload", Result: "ok", Reason: path} + if err != nil { + e.Result, e.Reason = "failed", path+": "+err.Error() + } + l.write(e) +} + +// WriteErrors is how many audit lines could not be written. +func (l *AuditLog) WriteErrors() int { + l.mu.Lock() + defer l.mu.Unlock() + return l.errs +} diff --git a/seaweed-block/core/auth/audit_test.go b/seaweed-block/core/auth/audit_test.go new file mode 100644 index 0000000000..ab333f9a04 --- /dev/null +++ b/seaweed-block/core/auth/audit_test.go @@ -0,0 +1,76 @@ +package auth_test + +import ( + "bytes" + "context" + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/auth" + "github.com/seaweedfs/seaweed-block/core/auth/authtest" + "google.golang.org/grpc" +) + +// The audit log: every person's call (accepted or refused) and every reload +// is a line; an accepted node call is not; a refused node call is a line at +// most once a minute per (fingerprint, reason, method). +func TestAuditLog(t *testing.T) { + ca := authtest.NewCA(t, "ca") + node := ca.Issue(t, "s1", time.Now().Add(time.Hour)) + op := ca.Issue(t, "alice", time.Now().Add(time.Hour)) + a := auth.NewAuthenticator(table(t, node.Fingerprint+" node s1", op.Fingerprint+" operator alice"), nil) + now := time.Unix(2000, 0) + var buf bytes.Buffer + a.SetAudit(auth.NewAuditLog(&buf, func() time.Time { return now })) + rules := map[string]auth.Rule{"/renew": {Node: true}, "/move": {Min: auth.RoleOperator}, "/delete": {Min: auth.RoleAdmin}} + call := func(leaf *authtest.Leaf, method string) { + _, _ = a.UnaryInterceptor(rules)(peerCtx(leaf, ca), nil, &grpc.UnaryServerInfo{FullMethod: method}, func(context.Context, any) (any, error) { return nil, nil }) + } + lines := func() []auth.AuditEvent { + var out []auth.AuditEvent + for _, l := range strings.Split(strings.TrimSpace(buf.String()), "\n") { + if l == "" { + continue + } + var e auth.AuditEvent + if err := json.Unmarshal([]byte(l), &e); err != nil { + t.Fatalf("audit line %q: %v", l, err) + } + out = append(out, e) + } + return out + } + call(node, "/renew") // accepted node call: not audited + call(op, "/move") // person, accepted + call(op, "/delete") // person, refused + call(node, "/delete") // node, refused + call(node, "/delete") // the same refusal within the minute: not again + now = now.Add(61 * time.Second) + call(node, "/delete") // a minute later: again + got := lines() + if len(got) != 4 { + t.Fatalf("%d audit lines; want 4: %s", len(got), buf.String()) + } + if got[0].ID != "alice" || got[0].Method != "/move" || got[0].Result != "ok" || + got[1].ID != "alice" || got[1].Result != "PermissionDenied" || + got[2].ID != "s1" || got[2].Result != "PermissionDenied" || got[3].ID != "s1" { + t.Fatalf("audit lines %+v", got) + } + path := filepath.Join(t.TempDir(), "roles") + if err := os.WriteFile(path, []byte("not a role file\n"), 0o600); err != nil { + t.Fatal(err) + } + _ = a.Reload(path) + if err := os.WriteFile(path, []byte(op.Fingerprint+" operator alice\n"), 0o600); err != nil { + t.Fatal(err) + } + _ = a.Reload(path) + got = lines() + if len(got) != 6 || got[4].Event != "reload" || got[4].Result != "failed" || got[5].Event != "reload" || got[5].Result != "ok" { + t.Fatalf("reload audit lines %+v", got[4:]) + } +} diff --git a/seaweed-block/core/auth/authorize.go b/seaweed-block/core/auth/authorize.go index 639434ceb5..6ce12712b9 100644 --- a/seaweed-block/core/auth/authorize.go +++ b/seaweed-block/core/auth/authorize.go @@ -96,30 +96,43 @@ func RequireRole(ctx context.Context, min Role) error { return nil } -func (a *Authenticator) admit(ctx context.Context, method string, rules map[string]Rule) (context.Context, error) { +func (a *Authenticator) admit(ctx context.Context, method string, rules map[string]Rule) (context.Context, Principal, error) { p, err := a.PeerIdentity(ctx) if err != nil { - return nil, err + return nil, Principal{}, err } r, ok := rules[method] if !ok { - return nil, forbidden("method %s has no authorization rule", method) + return nil, p, forbidden("method %s has no authorization rule", method) } if !r.Allows(p) { - return nil, forbidden("%s %s may not call %s", p.Role, p.ID, method) + return nil, p, forbidden("%s %s may not call %s", p.Role, p.ID, method) } - return context.WithValue(ctx, ctxKey{}, callAuth{p: p}), nil + return context.WithValue(ctx, ctxKey{}, callAuth{p: p}), p, nil +} + +// authzRefusal is err when it is an authentication or authorization refusal +// (raised by the interceptor or by a handler's RequireNode / RequireRole). +func authzRefusal(err error) error { + switch status.Code(err) { + case codes.Unauthenticated, codes.PermissionDenied: + return err + } + return nil } // UnaryInterceptor authenticates every call (PeerIdentity) and applies its // method's rule. func (a *Authenticator) UnaryInterceptor(rules map[string]Rule) grpc.UnaryServerInterceptor { return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { - ctx, err := a.admit(ctx, info.FullMethod, rules) + ctx, p, err := a.admit(ctx, info.FullMethod, rules) if err != nil { + a.audit.call(info.FullMethod, p, err) return nil, err } - return handler(ctx, req) + resp, err := handler(ctx, req) + a.audit.call(info.FullMethod, p, authzRefusal(err)) + return resp, err } } @@ -130,8 +143,9 @@ func (a *Authenticator) UnaryInterceptor(rules map[string]Rule) grpc.UnaryServer func (a *Authenticator) StreamInterceptor(rules map[string]Rule) grpc.StreamServerInterceptor { return func(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { changed := a.Changed() - ctx, err := a.admit(ss.Context(), info.FullMethod, rules) + ctx, p, err := a.admit(ss.Context(), info.FullMethod, rules) if err != nil { + a.audit.call(info.FullMethod, p, err) return err } ctx, cancel := context.WithCancelCause(ctx) @@ -152,8 +166,9 @@ func (a *Authenticator) StreamInterceptor(rules map[string]Rule) grpc.StreamServ }() err = handler(srv, &authStream{ServerStream: ss, ctx: ctx, a: a}) if cause := context.Cause(ctx); cause != nil && status.Code(cause) == codes.Unauthenticated { - return cause + err = cause } + a.audit.call(info.FullMethod, p, authzRefusal(err)) return err } } diff --git a/seaweed-block/core/auth/identity.go b/seaweed-block/core/auth/identity.go index b9f5d30edf..351c7f1ae0 100644 --- a/seaweed-block/core/auth/identity.go +++ b/seaweed-block/core/auth/identity.go @@ -117,8 +117,13 @@ type Authenticator struct { mu sync.Mutex changed chan struct{} // closed (and replaced) by every Swap + audit *AuditLog // nil: no audit log } +// SetAudit sends every call's authorization outcome and every reload to l. +// Set before serving. +func (a *Authenticator) SetAudit(l *AuditLog) { a.audit = l } + // NewAuthenticator starts with t; now nil is time.Now. func NewAuthenticator(t *Table, now func() time.Time) *Authenticator { if now == nil { @@ -149,6 +154,7 @@ func (a *Authenticator) Changed() <-chan struct{} { // Reload parses path and installs it; on any error the current table stays. func (a *Authenticator) Reload(path string) error { t, err := LoadRoleFile(path) + a.audit.Reload(path, err) if err != nil { return err } From dc359e16c815e5e77c423b38bc6f7daa1779661f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 09:12:42 -0800 Subject: [PATCH 10/36] sw-block: mutual TLS to blockmaster from SW_BLOCK_TLS_CERT/_KEY/_CA Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/sw-block/chunk_gc.go | 2 +- .../cmd/sw-block/chunk_volume_delete.go | 2 +- seaweed-block/cmd/sw-block/main.go | 2 +- seaweed-block/core/ops/live_sources.go | 2 +- seaweed-block/core/rpc/link/tls.go | 34 +++++++++++++++++++ seaweed-block/core/rpc/wsclient/wsclient.go | 2 +- 6 files changed, 39 insertions(+), 5 deletions(-) diff --git a/seaweed-block/cmd/sw-block/chunk_gc.go b/seaweed-block/cmd/sw-block/chunk_gc.go index a354999357..0b323b1304 100644 --- a/seaweed-block/cmd/sw-block/chunk_gc.go +++ b/seaweed-block/cmd/sw-block/chunk_gc.go @@ -77,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 := link.Dial(master) + conn, e := link.DialMasterFromEnv(master) if e != nil { return nil, nil, e } diff --git a/seaweed-block/cmd/sw-block/chunk_volume_delete.go b/seaweed-block/cmd/sw-block/chunk_volume_delete.go index 72645a1186..75099b092b 100644 --- a/seaweed-block/cmd/sw-block/chunk_volume_delete.go +++ b/seaweed-block/cmd/sw-block/chunk_volume_delete.go @@ -50,7 +50,7 @@ func chunkVolumeDelete(args []string, stdout, stderr io.Writer) int { return exit } defer closeFn() - conn, err := link.Dial(master) + conn, err := link.DialMasterFromEnv(master) if err != nil { return chunkResult("volume-delete", nil, err, stdout, stderr) } diff --git a/seaweed-block/cmd/sw-block/main.go b/seaweed-block/cmd/sw-block/main.go index da6722bf6a..14ade59525 100644 --- a/seaweed-block/cmd/sw-block/main.go +++ b/seaweed-block/cmd/sw-block/main.go @@ -1157,7 +1157,7 @@ func liveNodeEvidenceNamespace(namespace string) string { } func readMasterClusterEvidence(ctx context.Context, masterAddr string) (ops.ClusterEvidence, error) { - conn, err := link.Dial(masterAddr) + conn, err := link.DialMasterFromEnv(masterAddr) if err != nil { return ops.ClusterEvidence{}, err } diff --git a/seaweed-block/core/ops/live_sources.go b/seaweed-block/core/ops/live_sources.go index 36ba994c57..c5e5642b67 100644 --- a/seaweed-block/core/ops/live_sources.go +++ b/seaweed-block/core/ops/live_sources.go @@ -94,7 +94,7 @@ func NewLiveVolumeStatusReportCollector(cfg LiveVolumeStatusConfig) VolumeStatus } func queryLiveMasterStatus(ctx context.Context, masterAddr, volumeID string) (*control.StatusResponse, error) { - conn, err := link.Dial(masterAddr) + conn, err := link.DialMasterFromEnv(masterAddr) if err != nil { return nil, fmt.Errorf("dial master: %w", err) } diff --git a/seaweed-block/core/rpc/link/tls.go b/seaweed-block/core/rpc/link/tls.go index 83c2386d3d..199ac68e13 100644 --- a/seaweed-block/core/rpc/link/tls.go +++ b/seaweed-block/core/rpc/link/tls.go @@ -126,3 +126,37 @@ func DialMaster(target string, tls grpc.DialOption, opts ...grpc.DialOption) (*g } return DialWith(target, append([]grpc.DialOption{tls}, opts...)...) } + +// The environment variables a command-line tool (sw-block) reads for its +// mutual-TLS identity toward blockmaster: a person's or tool's certificate, +// its key, and the CA the master's certificate must verify against. +const ( + EnvTLSCert = "SW_BLOCK_TLS_CERT" + EnvTLSKey = "SW_BLOCK_TLS_KEY" + EnvTLSCA = "SW_BLOCK_TLS_CA" +) + +// MasterTLSFromEnv is the dial option for a tool's master link: mutual TLS +// when SW_BLOCK_TLS_CERT/_KEY/_CA name files (all three), nil (plaintext, +// development mode) when none is set. +func MasterTLSFromEnv() (grpc.DialOption, error) { + f := TLSFiles{Cert: os.Getenv(EnvTLSCert), Key: os.Getenv(EnvTLSKey), CA: os.Getenv(EnvTLSCA)} + if !f.Enabled() { + return nil, nil + } + d, err := ClientCredentials(f, "") + if err != nil { + return nil, fmt.Errorf("%s/%s/%s: %w", EnvTLSCert, EnvTLSKey, EnvTLSCA, err) + } + return d, nil +} + +// DialMasterFromEnv opens a tool's lazy connection to blockmaster with the +// identity from the environment (MasterTLSFromEnv). +func DialMasterFromEnv(target string, opts ...grpc.DialOption) (*grpc.ClientConn, error) { + d, err := MasterTLSFromEnv() + if err != nil { + return nil, err + } + return DialMaster(target, d, opts...) +} diff --git a/seaweed-block/core/rpc/wsclient/wsclient.go b/seaweed-block/core/rpc/wsclient/wsclient.go index 78e980abff..ba54eb2f06 100644 --- a/seaweed-block/core/rpc/wsclient/wsclient.go +++ b/seaweed-block/core/rpc/wsclient/wsclient.go @@ -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 := link.Dial(addr) + conn, err := link.DialMasterFromEnv(addr) if err != nil { return nil, err } From 979b859ae57353affa4809e60154e6ea04410adc Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 09:13:56 -0800 Subject: [PATCH 11/36] auth: DevCall marks in-process handler calls in tests as development mode Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/auth/authorize.go | 7 +++++++ .../core/host/master/recovery_watchdog_master_test.go | 9 +++++---- .../core/host/master/server_host_identity_test.go | 3 ++- .../host/master/workspace_uncertain_precedence_test.go | 7 ++++--- 4 files changed, 18 insertions(+), 8 deletions(-) diff --git a/seaweed-block/core/auth/authorize.go b/seaweed-block/core/auth/authorize.go index 6ce12712b9..f97a255922 100644 --- a/seaweed-block/core/auth/authorize.go +++ b/seaweed-block/core/auth/authorize.go @@ -209,3 +209,10 @@ type devStream struct { } func (s *devStream) Context() context.Context { return s.ctx } + +// DevCall marks an in-process call (a test calling a handler directly, with +// no gRPC server and so no interceptor) as development mode. Every network +// call is decided by the server's interceptor instead. +func DevCall(ctx context.Context) context.Context { + return context.WithValue(ctx, ctxKey{}, callAuth{dev: true}) +} diff --git a/seaweed-block/core/host/master/recovery_watchdog_master_test.go b/seaweed-block/core/host/master/recovery_watchdog_master_test.go index 8744e1e1cb..fa2ecffa72 100644 --- a/seaweed-block/core/host/master/recovery_watchdog_master_test.go +++ b/seaweed-block/core/host/master/recovery_watchdog_master_test.go @@ -9,6 +9,7 @@ import ( "google.golang.org/protobuf/types/known/timestamppb" + "github.com/seaweedfs/seaweed-block/core/auth" "github.com/seaweedfs/seaweed-block/core/authority" control "github.com/seaweedfs/seaweed-block/core/rpc/control" ) @@ -32,7 +33,7 @@ func reportRF3(t *testing.T, svc *services, r1, r2, r3 wireSlot) { }{ {"node-a", "r1", r1}, {"node-b", "r2", r2}, {"node-c", "r3", r3}, } { - _, err := svc.ReportHeartbeat(context.Background(), &control.HeartbeatReport{ + _, err := svc.ReportHeartbeat(auth.DevCall(context.Background()), &control.HeartbeatReport{ ServerId: s.server, SentAt: timestamppb.Now(), Reachable: true, Eligible: true, Slots: []*control.HeartbeatSlot{{ VolumeId: "vol-rf3", @@ -72,7 +73,7 @@ func watchdogMaster(t *testing.T) (*Host, *services) { func unhealthyReplicas(t *testing.T, svc *services) map[string]string { t.Helper() - resp, err := svc.QueryVolumeStatus(context.Background(), &control.StatusRequest{VolumeId: "vol-rf3"}) + resp, err := svc.QueryVolumeStatus(auth.DevCall(context.Background()), &control.StatusRequest{VolumeId: "vol-rf3"}) if err != nil { t.Fatalf("QueryVolumeStatus: %v", err) } @@ -168,7 +169,7 @@ func TestRecoveryWatchdog_MasterLaterDegradationFollowsNormalRules(t *testing.T) func reportR1(t *testing.T, svc *services, slot wireSlot, sentAt time.Time) { t.Helper() - _, err := svc.ReportHeartbeat(context.Background(), &control.HeartbeatReport{ + _, err := svc.ReportHeartbeat(auth.DevCall(context.Background()), &control.HeartbeatReport{ ServerId: "node-a", SentAt: timestamppb.New(sentAt), Reachable: true, Eligible: true, Slots: []*control.HeartbeatSlot{{ VolumeId: "vol-rf3", ReplicaId: "r1", DataAddr: "127.0.0.1:19101", CtrlAddr: "127.0.0.1:19102", @@ -276,7 +277,7 @@ func TestRecoveryWatchdog_MasterDuplicateSlotHeartbeatRefused(t *testing.T) { {slot(""), slot("recovery_timeout")}, // conflicting {slot("recovery_timeout"), slot("recovery_timeout")}, // identical } { - _, err := svc.ReportHeartbeat(context.Background(), &control.HeartbeatReport{ + _, err := svc.ReportHeartbeat(auth.DevCall(context.Background()), &control.HeartbeatReport{ ServerId: "node-a", SentAt: timestamppb.New(t0.Add(time.Duration(i+1) * time.Millisecond)), Reachable: true, Eligible: true, Slots: slots, }) diff --git a/seaweed-block/core/host/master/server_host_identity_test.go b/seaweed-block/core/host/master/server_host_identity_test.go index 1067bda980..ddd79a481e 100644 --- a/seaweed-block/core/host/master/server_host_identity_test.go +++ b/seaweed-block/core/host/master/server_host_identity_test.go @@ -9,6 +9,7 @@ import ( "testing" "time" + "github.com/seaweedfs/seaweed-block/core/auth" "github.com/seaweedfs/seaweed-block/core/authority" "github.com/seaweedfs/seaweed-block/core/csi" "github.com/seaweedfs/seaweed-block/core/lifecycle" @@ -295,7 +296,7 @@ func TestWorkspaceHolderRefusedFromAnotherHostAtRenewAckAndStream(t *testing.T) // loopbackPeer is ctx as an RPC from 127.0.0.1 arrives at the master (in-process service calls carry no peer). func loopbackPeer(ctx context.Context) context.Context { - return peer.NewContext(ctx, &peer.Peer{Addr: &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 40000}}) + return peer.NewContext(auth.DevCall(ctx), &peer.Peer{Addr: &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 40000}}) } // registerWorkspaceHolder registers server on 127.0.0.1 (a workspace holder must be registered). diff --git a/seaweed-block/core/host/master/workspace_uncertain_precedence_test.go b/seaweed-block/core/host/master/workspace_uncertain_precedence_test.go index 91d381a3bd..649d8d94f2 100644 --- a/seaweed-block/core/host/master/workspace_uncertain_precedence_test.go +++ b/seaweed-block/core/host/master/workspace_uncertain_precedence_test.go @@ -3,6 +3,7 @@ package master import ( "context" "errors" + "github.com/seaweedfs/seaweed-block/core/auth" "github.com/seaweedfs/seaweed-block/core/authority" control "github.com/seaweedfs/seaweed-block/core/rpc/control" "google.golang.org/grpc/codes" @@ -96,7 +97,7 @@ func TestWorkspaceMoveUnknownPrecedesAdmissionRefusals(t *testing.T) { liveParent := context.Background() for _, mode := range []int32{2, 3} { headFailure.Store(mode) - _, err := (&services{host: h}).MoveWorkspace(liveParent, request("clean")) + _, err := (&services{host: h}).MoveWorkspace(auth.DevCall(liveParent), request("clean")) if liveParent.Err() != nil || (mode == 2 && !childDeadlineObserved.Load()) { t.Fatal("dependency-end witness did not preserve live request") } @@ -107,7 +108,7 @@ func TestWorkspaceMoveUnknownPrecedesAdmissionRefusals(t *testing.T) { caller, cancelCaller := context.WithCancel(context.Background()) cancelRequest = cancelCaller headFailure.Store(4) - _, err := (&services{host: h}).MoveWorkspace(caller, request("clean")) + _, err := (&services{host: h}).MoveWorkspace(auth.DevCall(caller), request("clean")) cancelCaller() if caller.Err() != context.Canceled || status.Code(err) != codes.Canceled { t.Errorf("actual caller end lost to dependency status: %v", err) @@ -125,7 +126,7 @@ func TestWorkspaceMoveUnknownPrecedesAdmissionRefusals(t *testing.T) { ended, end = context.WithCancel(ctx) end() } - _, err := (&services{host: h}).MoveWorkspace(ended, request("forced")) + _, err := (&services{host: h}).MoveWorkspace(auth.DevCall(ended), request("forced")) end() if status.Code(err) != want { t.Errorf("server caller-end classification changed: %v want %v", err, want) From 0f0da4a7f0ca7e0b1f947f20a3a186ed0b87a190 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 09:20:02 -0800 Subject: [PATCH 12/36] blockcsi: --master-tls-cert/--master-tls-key/--master-ca; tests for tool TLS identity Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/blockcsi/main.go | 19 +++++++- seaweed-block/cmd/blockcsi/main_test.go | 23 +++++++++ seaweed-block/core/rpc/link/tls_env_test.go | 53 +++++++++++++++++++++ 3 files changed, 94 insertions(+), 1 deletion(-) create mode 100644 seaweed-block/core/rpc/link/tls_env_test.go diff --git a/seaweed-block/cmd/blockcsi/main.go b/seaweed-block/cmd/blockcsi/main.go index 4229e19743..a34a995e41 100644 --- a/seaweed-block/cmd/blockcsi/main.go +++ b/seaweed-block/cmd/blockcsi/main.go @@ -37,6 +37,7 @@ type flags struct { rejectLoopbackPublishTargets bool version bool printReadyLine bool + masterTLS link.TLSFiles // mutual TLS to blockmaster (all three or none) } func parseFlags(args []string) (flags, error) { @@ -44,6 +45,9 @@ func parseFlags(args []string) (flags, error) { fs := flag.NewFlagSet("blockcsi", flag.ContinueOnError) fs.StringVar(&f.endpoint, "endpoint", "unix:///var/lib/kubelet/plugins/block.csi.seaweedfs.com/csi.sock", "CSI endpoint, e.g. unix:///path/csi.sock or tcp://127.0.0.1:0") fs.StringVar(&f.masterAddr, "master", "", "blockmaster gRPC address for read-only publish-target lookup") + fs.StringVar(&f.masterTLS.Cert, "master-tls-cert", "", "certificate presented to blockmaster (mutual TLS; with --master-tls-key and --master-ca)") + fs.StringVar(&f.masterTLS.Key, "master-tls-key", "", "key of --master-tls-cert") + fs.StringVar(&f.masterTLS.CA, "master-ca", "", "CA that blockmaster's certificate must verify against") fs.StringVar(&f.nodeID, "node-id", "", "CSI node ID; defaults to hostname") fs.StringVar(&f.iqnPrefix, "iqn-prefix", "iqn.2026-05.io.seaweedfs", "fallback IQN prefix for unstage after plugin restart") fs.BoolVar(&f.pvcUIDLookup, "kubernetes-pvc-uid-lookup", false, "opt-in: resolve PVC UID through the in-cluster Kubernetes API before CreateVolume is sent to blockmaster") @@ -67,6 +71,12 @@ func parseFlags(args []string) (flags, error) { if f.masterAddr == "" && (f.stage2Multipath || f.nvmeReconnectOwner || f.rejectLoopbackPublishTargets || f.pvcUIDLookup || f.swBlockVolumeCRNamespace != "") { return flags{}, fmt.Errorf("--stage2-multipath, --nvme-reconnect-owner, --reject-loopback-publish-targets, --kubernetes-pvc-uid-lookup, and --swblockvolume-cr-namespace require --master") } + if f.masterTLS.Enabled() && f.masterAddr == "" { + return flags{}, fmt.Errorf("--master-tls-cert, --master-tls-key and --master-ca require --master") + } + if err := f.masterTLS.Check(); err != nil { + return flags{}, err + } if f.nodeID == "" { host, err := os.Hostname() if err != nil || host == "" { @@ -127,7 +137,14 @@ func run(f flags) int { registrar blockcsi.VolumeObjectRegistrar ) if f.masterAddr != "" { - masterConn, err = link.Dial(f.masterAddr) + var tls grpc.DialOption + if f.masterTLS.Enabled() { + if tls, err = link.ClientCredentials(f.masterTLS, ""); err != nil { + fmt.Fprintln(os.Stderr, "blockcsi: master TLS:", err) + return 1 + } + } + masterConn, err = link.DialMaster(f.masterAddr, tls) if err != nil { fmt.Fprintln(os.Stderr, "blockcsi: master dial:", err) return 1 diff --git a/seaweed-block/cmd/blockcsi/main_test.go b/seaweed-block/cmd/blockcsi/main_test.go index 4cd5f69ae9..324d0ec270 100644 --- a/seaweed-block/cmd/blockcsi/main_test.go +++ b/seaweed-block/cmd/blockcsi/main_test.go @@ -14,6 +14,7 @@ import ( "time" csipb "github.com/container-storage-interface/spec/lib/go/csi" + "github.com/seaweedfs/seaweed-block/core/auth/authtest" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" ) @@ -441,3 +442,25 @@ func buildBlockCSIBinary(t *testing.T) string { } return out } + +// The master TLS flags come as a set, need --master, and every file is read +// at parse time. +func TestParseFlags_MasterTLS(t *testing.T) { + dir := t.TempDir() + ca := authtest.NewCA(t, "ca") + caPath := ca.WriteCA(t, dir) + cert, key := ca.Issue(t, "csi", time.Now().Add(time.Hour)).WriteFiles(t, dir, "csi") + base := []string{"--endpoint", "unix:///tmp/csi.sock", "--node-id", "node-a"} + tlsArgs := []string{"--master-tls-cert", cert, "--master-tls-key", key, "--master-ca", caPath} + + f, err := parseFlags(append(append(base, "--master", "blockmaster:9333"), tlsArgs...)) + if err != nil || !f.masterTLS.Enabled() { + t.Fatalf("full set: %v (enabled=%t)", err, f.masterTLS.Enabled()) + } + if _, err := parseFlags(append(base, tlsArgs...)); err == nil || !strings.Contains(err.Error(), "require --master") { + t.Fatalf("TLS without --master: %v", err) + } + if _, err := parseFlags(append(base, "--master", "blockmaster:9333", "--master-tls-cert", cert)); err == nil { + t.Fatal("a partial TLS set was accepted") + } +} diff --git a/seaweed-block/core/rpc/link/tls_env_test.go b/seaweed-block/core/rpc/link/tls_env_test.go new file mode 100644 index 0000000000..72e8a1049a --- /dev/null +++ b/seaweed-block/core/rpc/link/tls_env_test.go @@ -0,0 +1,53 @@ +package link + +import ( + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/auth/authtest" +) + +// A tool (sw-block) takes its master identity from SW_BLOCK_TLS_CERT/_KEY/_CA: +// none is plaintext, a partial set or a wrong file is refused before a dial. +func TestMasterTLSFromEnv(t *testing.T) { + dir := t.TempDir() + ca := authtest.NewCA(t, "ca") + caPath := ca.WriteCA(t, dir) + cert, key := ca.Issue(t, "alice", time.Now().Add(time.Hour)).WriteFiles(t, dir, "alice") + + for _, c := range []struct { + name string + cert, key, ca string + want string // "" plaintext, "tls", or a refusal substring + }{ + {name: "none"}, + {name: "all three", cert: cert, key: key, ca: caPath, want: "tls"}, + {name: "no CA", cert: cert, key: key, want: "needs a certificate, its key and a CA"}, + {name: "missing key file", cert: cert, key: key + ".gone", ca: caPath, want: "key"}, + } { + t.Run(c.name, func(t *testing.T) { + t.Setenv(EnvTLSCert, c.cert) + t.Setenv(EnvTLSKey, c.key) + t.Setenv(EnvTLSCA, c.ca) + d, err := MasterTLSFromEnv() + switch c.want { + case "": + if err != nil || d != nil { + t.Fatalf("no variables: got option=%v err=%v, want plaintext", d != nil, err) + } + case "tls": + if err != nil || d == nil { + t.Fatalf("all three: got option=%v err=%v, want mutual TLS", d != nil, err) + } + default: + if err == nil || !strings.Contains(err.Error(), c.want) || !strings.Contains(err.Error(), EnvTLSCert) { + t.Fatalf("got %v, want a refusal naming %s and containing %q", err, EnvTLSCert, c.want) + } + if _, err := DialMasterFromEnv("127.0.0.1:1"); err == nil { + t.Fatal("DialMasterFromEnv dialed with a bad identity") + } + } + }) + } +} From 1962369a92c2457874d3f9c9f307291a6b80aa79 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 09:28:45 -0800 Subject: [PATCH 13/36] docs: caller identity term, control API authorization row, operator guide authentication section Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/design/invariants.md | 8 +++-- seaweed-block/docs/operator-guide.md | 41 +++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 3 deletions(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index ace443cffe..0d3fff077e 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -497,7 +497,7 @@ Tests: `TestSnapshotSchedule_SlotsAreOffsetPerVolume`, `_FailureIsTypedAndBacksO ## Part B. Invariant ledger -324 rows: 254 ACTIVE, 67 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 309 new. +325 rows: 255 ACTIVE, 67 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 310 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. @@ -672,7 +672,8 @@ Notes: | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | |---|---|---|---|---|---|---| -| `INV-AUTH-HOLDER-IDENTITY-001` | A primary holder is the pair (server id, replica id): every site that decides holdership (adopting a fact, lease first grant, renew, re-grant, HEAD claim, superseded exit) compares both; a missing server id is refused, never guessed. | AUTHORITY: PRIMARY holdership (supporting replicas are not holders) | `core/host/volume/host.go` `applyFact`, `IsSuperseded`, `recordOtherLine`; `assignment_holder.go` `assignmentNamesSelf`, `observeForeignHolder`, `refusePrimaryAssignment`; `host.go` `IsSuperseded`; `core/host/master/services.go` `SubscribeAssignments`; `workspace_service.go` `holderMatches`, `RenewWorkspaceLease`, `AckWorkspaceRevoked`; `cmd/blockvolume/chunk_remote.go` `chunkHolder`; `core/storage/chunk_restore.go` `ClaimChunkHead`; superseded exit covered by #409; `core/host/master/workspace_binding.go` `workspaceLineOwner`, `workspaceSourceHost`; `core/authority/assignment_owner.go` `captureAssignmentOwner`; `core/host/master/services.go` `assignmentFact`; `core/host/master/server_host_identity.go` `refuseServerIDFromOtherHost` (from `ReportHeartbeat`), `refuseWorkspaceHolderHost` (from `holderMatches` and, for a workspace volume, `SubscribeAssignments`), `holderSlotFact` (from `QueryVolumeStatus` and `observationVolume`/`observationReplicas`); `core/csi/master_backend.go` `primaryOwnedFrontends` (a CSI target only from a usable primary frontend); `core/authority/snapshot_builder.go` `expectOwnerForLine` (a moved line's replica facts and endpoint refreshes only from its owner, #425) | `TestAssignmentHolderIdentityRestartedOldProcess`, `TestAssignmentHolderIdentityMatchingServerStillAdopts`, `TestAssignmentHolderIdentityFencesPreviouslyHealthySameReplica`, `TestAssignmentHolderIdentityAdoptsAndWarnsCarriedEndpointMismatch`, `TestAssignmentHolderIdentityForeignStreamOrdering`, `TestAssignmentHolderIdentityForcedMoveRefusesEveryDeliveredVersion`, `TestAssignmentHolderIdentitySameEpochCannotChangeServer` (`core/host/volume/assignment_holder_test.go`); `TestWorkspaceLeaseGuardCarriesHolderServerIdentity` (`core/host/volume/workspace_holder_identity_test.go`); `TestWorkspaceLeaseRequiresHolderServerForGrantRenewAndRegrant`, `TestWorkspaceRevocationACKRequiresHolderServer` (`core/host/master/workspace_holder_identity_test.go`); `TestWorkspaceRPCCleanMovePreservesReplicaIdentity` (`core/host/master/workspace_service_test.go`); HEAD claim: `TestChunkHolderIsServerAndReplica` (`cmd/blockvolume/chunk_remote_test.go`), `TestWALStoreChunk_SameReplicaOnAnotherServerIsFenced` (`core/frontend/durable/provider_chunk_holder_test.go`); superseded exit: covered by #409 (server-id/replica-id pair, never replica alone); supporting replicas are not holders; descriptor identity not in this row; `TestWorkspaceLineOwnerIssuedAndHistorical` (`core/host/master/workspace_line_owner_test.go`), `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`); `TestAssignmentFactKeepsCapturedMoveOwnerWithoutReadableJournal` (`core/host/master/assignment_fact_owner_test.go`), `TestAssignmentOwnerReservedAndIssuedCapture` (`core/authority/assignment_owner_test.go`), `TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant` (`core/authority/workspace_test.go`); `TestServerIDRefusedFromAHostOtherThanItsRegisteredOne`, `TestWorkspaceHolderRefusedFromAnotherHostAtRenewAckAndStream`, `TestPortalAndPrimaryComeFromTheLineServerNotTheFreshestHeartbeat`, `TestDisplayedPrimaryIsTheIssuedHolderNotThePlacementSlot`, `TestStatusListsNoFrontendWhenThePrimaryEvidenceIsMissing`, `TestCSIPublishesNoTargetWhenThePrimaryFrontendIsMissingOrRejected`, `TestDeletionReservedWorkspaceVolumeKeepsTheStreamHostCheck` (`core/host/master/server_host_identity_test.go`); `TestPublishTargetIsPrimaryOwned` (`core/csi/primary_owned_frontend_test.go`). Host scope: registered advertised-host consistency, not process uniqueness; a workspace holder's server id must be registered (no first-seen binding: host addresses change); non-workspace heartbeats from an unregistered id are not checked. Limits: trusts the network peer address (no NAT or proxy between volume and master in OSS); not authentication; `TestBuildSnapshotTakesTheMovedLinesReplicaFromItsOwner` (`core/authority/line_owner_snapshot_test.go`); `TestProcedureForcedMoveWithTheOldHostReturning` (`cmd/blockvolume/procedure_gate_integration_test.go`, tags subprocess chunkstore_integration: every forced-epoch line carries the new owner's endpoints) | `WorkspaceRegrant` `NoForeignAdoption`, `TargetNotFencedByOwnLine` (round 4 pinned simulations only; exhaustive combo10 pending) | ACTIVE | +| `INV-AUTH-HOLDER-IDENTITY-001` | A primary holder is the pair (server id, replica id): every site that decides holdership (adopting a fact, lease first grant, renew, re-grant, HEAD claim, superseded exit) compares both; a missing server id is refused, never guessed. | AUTHORITY: PRIMARY holdership (supporting replicas are not holders) | `core/host/volume/host.go` `applyFact`, `IsSuperseded`, `recordOtherLine`; `assignment_holder.go` `assignmentNamesSelf`, `observeForeignHolder`, `refusePrimaryAssignment`; `host.go` `IsSuperseded`; `core/host/master/services.go` `SubscribeAssignments`; `workspace_service.go` `holderMatches`, `RenewWorkspaceLease`, `AckWorkspaceRevoked`; `cmd/blockvolume/chunk_remote.go` `chunkHolder`; `core/storage/chunk_restore.go` `ClaimChunkHead`; superseded exit covered by #409; `core/host/master/workspace_binding.go` `workspaceLineOwner`, `workspaceSourceHost`; `core/authority/assignment_owner.go` `captureAssignmentOwner`; `core/host/master/services.go` `assignmentFact`; `core/host/master/server_host_identity.go` `refuseServerIDFromOtherHost` (from `ReportHeartbeat`), `refuseWorkspaceHolderHost` (from `holderMatches` and, for a workspace volume, `SubscribeAssignments`), `holderSlotFact` (from `QueryVolumeStatus` and `observationVolume`/`observationReplicas`); `core/csi/master_backend.go` `primaryOwnedFrontends` (a CSI target only from a usable primary frontend); `core/authority/snapshot_builder.go` `expectOwnerForLine` (a moved line's replica facts and endpoint refreshes only from its owner, #425) | `TestAssignmentHolderIdentityRestartedOldProcess`, `TestAssignmentHolderIdentityMatchingServerStillAdopts`, `TestAssignmentHolderIdentityFencesPreviouslyHealthySameReplica`, `TestAssignmentHolderIdentityAdoptsAndWarnsCarriedEndpointMismatch`, `TestAssignmentHolderIdentityForeignStreamOrdering`, `TestAssignmentHolderIdentityForcedMoveRefusesEveryDeliveredVersion`, `TestAssignmentHolderIdentitySameEpochCannotChangeServer` (`core/host/volume/assignment_holder_test.go`); `TestWorkspaceLeaseGuardCarriesHolderServerIdentity` (`core/host/volume/workspace_holder_identity_test.go`); `TestWorkspaceLeaseRequiresHolderServerForGrantRenewAndRegrant`, `TestWorkspaceRevocationACKRequiresHolderServer` (`core/host/master/workspace_holder_identity_test.go`); `TestWorkspaceRPCCleanMovePreservesReplicaIdentity` (`core/host/master/workspace_service_test.go`); HEAD claim: `TestChunkHolderIsServerAndReplica` (`cmd/blockvolume/chunk_remote_test.go`), `TestWALStoreChunk_SameReplicaOnAnotherServerIsFenced` (`core/frontend/durable/provider_chunk_holder_test.go`); superseded exit: covered by #409 (server-id/replica-id pair, never replica alone); supporting replicas are not holders; descriptor identity not in this row; `TestWorkspaceLineOwnerIssuedAndHistorical` (`core/host/master/workspace_line_owner_test.go`), `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`); `TestAssignmentFactKeepsCapturedMoveOwnerWithoutReadableJournal` (`core/host/master/assignment_fact_owner_test.go`), `TestAssignmentOwnerReservedAndIssuedCapture` (`core/authority/assignment_owner_test.go`), `TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant` (`core/authority/workspace_test.go`); `TestServerIDRefusedFromAHostOtherThanItsRegisteredOne`, `TestWorkspaceHolderRefusedFromAnotherHostAtRenewAckAndStream`, `TestPortalAndPrimaryComeFromTheLineServerNotTheFreshestHeartbeat`, `TestDisplayedPrimaryIsTheIssuedHolderNotThePlacementSlot`, `TestStatusListsNoFrontendWhenThePrimaryEvidenceIsMissing`, `TestCSIPublishesNoTargetWhenThePrimaryFrontendIsMissingOrRejected`, `TestDeletionReservedWorkspaceVolumeKeepsTheStreamHostCheck` (`core/host/master/server_host_identity_test.go`); `TestPublishTargetIsPrimaryOwned` (`core/csi/primary_owned_frontend_test.go`). Host scope: registered advertised-host consistency, not process uniqueness; a workspace holder's server id must be registered (no first-seen binding: host addresses change); non-workspace heartbeats from an unregistered id are not checked. Limits: with mutual TLS on, a node may act only for the server id bound to its certificate (`TERM-CALLER-001`; `auth.RequireNode` in `ReportHeartbeat`, `SubscribeAssignments`, `RenewWorkspaceLease`, `AckWorkspaceRevoked`, `QueryVolumeStatus`; `TestNodeActsOnlyForItsOwnServerID`, `core/host/master/auth_red_test.go`), and the registered-host check stays beside it (no NAT or proxy between volume and master in OSS); in development mode (plaintext on loopback, no role file) there is no authentication; `TestBuildSnapshotTakesTheMovedLinesReplicaFromItsOwner` (`core/authority/line_owner_snapshot_test.go`); `TestProcedureForcedMoveWithTheOldHostReturning` (`cmd/blockvolume/procedure_gate_integration_test.go`, tags subprocess chunkstore_integration: every forced-epoch line carries the new owner's endpoints) | `WorkspaceRegrant` `NoForeignAdoption`, `TargetNotFencedByOwnLine` (round 4 pinned simulations only; exhaustive combo10 pending) | ACTIVE | +| `INV-AUTH-CALLER-ROLE-001` | With mutual TLS on, every blockmaster gRPC call (unary, and before every stream send) is decided by the caller's certificate and the current role file: an unknown caller is refused UNAUTHENTICATED, a role its method's rule does not admit PERMISSION_DENIED, a method without a rule always. | AUTHORITY: control API callers (people, tools, nodes) | `core/auth/identity.go` `Authenticator.PeerIdentity`, `Authenticator.Reload`; `core/auth/authorize.go` `Rule.Allows`, `UnaryInterceptor`, `StreamInterceptor`, `RequireNode`, `RequireRole`; `core/host/master/authz.go` `masterRules`, `serverAuth`; `core/rpc/link/tls.go` `ServerCredentials`, `ClientCredentials`; `cmd/blockmaster/auth.go` `authFlags.validate`, `authFlags.build` | `TestPeerIdentity`, `TestRoleFileReload` (`core/auth/identity_test.go`); `TestRuleAllows`, `TestRequireNodeAndRole`, `TestUnaryInterceptor`, `TestStreamEndsAtTheReloadThatRevokesItsCaller` (`core/auth/authorize_test.go`); `TestMasterAuthorizationTableCoversEveryMethod` (`core/host/master/authz_test.go`); `TestForcedMoveNeedsAnAdmin`, `TestNodeActsOnlyForItsOwnServerID` (`core/host/master/auth_red_test.go`); `TestMasterLinkMutualTLS` (`core/rpc/link/tls_test.go`); `TestAuthFlags` (`cmd/blockmaster/auth_flags_test.go`); `TestMasterTLSFlags` (`cmd/blockvolume/master_tls_test.go`). Also: a reload that removes a caller ends its open streams at the reload; a forced move needs an admin; plaintext listens only on loopback without a role file (development mode). Limits: the audit log records outcomes and decides nothing; the volume process's own HTTP routes stay loopback-only and unauthenticated. | `AuthLease` (exhaustive run pending) | ACTIVE | | `INV-AUTH-EPOCH-MINT-001` | Only the publisher mints epochs; a reassignment takes the per-volume maximum epoch plus one, also after a restart. | M2 Bound → Reassigned | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestDurableAuthority_PublisherAdvancesFromReloaded` (`core/authority/authority_restart_test.go`); `TestG9F2_AssignmentRequestShapeHasNoEpochOrEndpointVersion` (`core/host/master/authority_request_bridge_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | | `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | With an authority store configured, an assignment is written to the store before memory or any subscriber sees it, and a failed write does not publish it: see M2 any → (store write first). | M2 any → (store write first) | `core/authority/authority.go` `applyWithWorkspaceMove` | `TestDurableAuthority_PutFailureRollsBackInMemoryState` (`core/authority/authority_restart_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | | `INV-AUTH-MOVE-JOURNAL-001` | A workspace move's epoch is issued only after its journal record is durable, and one move request id gets exactly one epoch, also across restarts. | M2 MoveReserved → MoveIssued | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace`, `sameWorkspaceRequest` | `TestWorkspaceMoveCannotIssueEpochWithoutJournal`, `TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant` (`core/authority/workspace_test.go`); `TestWorkspaceReplayedIssueStartsGranteeLease` (`core/authority/workspace_unclaimed_grant_test.go`) | `ControlPlane` `Idempotent`, `JournalComplete` | ACTIVE | @@ -1100,10 +1101,11 @@ A reviewer applies the rule to every pull request: A row that names a function existing only on an open pull request says so ("on #N"). The qualifier is dropped when that pull request merges. Code references name a file and a function, as in the rest of this document. A checker will later verify that every deciding function named here exists on `main`. -10 rows for 5 terms. They name 14 deciding functions: 10 on `main` and 4 only on open pull requests (2 on #411, 1 on #409, 1 on #439). One row (`TERM-STOP-STALE-ROOT-001`) has no named function yet. +11 rows for 6 terms. They name 15 deciding functions: 10 on `main` and 5 only on open pull requests (2 on #411, 1 on #409, 1 on #439, 1 on the phase 0 authentication pull request). One row (`TERM-STOP-STALE-ROOT-001`) has no named function yet. | Term | Meaning | Field(s) | Deciding function (one per side) | Known second derivations to remove | Owner role | |---|---|---|---|---|---| +| `TERM-CALLER-001` Caller identity (blockmaster control API) | Who is calling blockmaster is the role-file line whose fingerprint is the sha256 of the verified client leaf certificate, with CN equal to the line's id and the certificate not expired on the master clock. A request field never names the caller. A node's id is its server id: a node may act only for that server id. | the TLS peer's verified chain (`credentials.TLSInfo`); the role file's lines `sha256: ` (`auth.Table`); `auth.Principal` `Role`, `ID`, `Fingerprint`, `NotAfter` | Master: `core/auth/identity.go` `Authenticator.PeerIdentity`, on the phase 0 authentication pull request; called by the interceptors on every call and before every stream send, and by `auth.RequireNode` / `auth.RequireRole` through the call's decision. | The registered-host check (`refuseWorkspaceHolderHost`, `refuseServerIDFromOtherHost`) is kept beside it by decision, not a second derivation of the caller: it checks the network address, not the certificate. | authority (master side) | | `TERM-HOLDER-001` Holder identity (the primary of a single-copy workspace volume only; supporting replicas are not holders) | The process that may act as primary of a single-copy workspace volume at an epoch is the pair (server id, replica id) at that epoch. A matching replica id or endpoint alone never names it, and a missing server id is refused. No local-root nonce joins it (V1-SPEC r2.45); one live process per volume on a host is the host lock (`TERM-ONE-PROCESS-001`). | `AssignmentFact` `server_id`, `replica_id`, `epoch` (`core/rpc/proto/control.proto`; `server_id` on [#411](https://github.com/seaweedfs/seaweed-block/pull/411)); `WorkspaceIdentity` `server_id`, `replica_id`, `epoch` (`core/rpc/proto/workspace.proto`; `server_id` on #411); the published line's `PublishedLine.IssuedHost` (`core/authority/workspace_lease_view.go`) and the move journal's `WorkspaceMoveRecord.NewHost` (`core/authority/workspace.go`); the volume's `Config.ServerID`, `Config.ReplicaID` (`core/host/volume/host.go`, from `--server-id`, `--replica-id`); the HEAD `Holder`, written as `/` (`cmd/blockvolume/chunk_remote.go` `chunkHolder`) | Master: `core/host/master/workspace_service.go` `services.holderMatches(volume, replica, server, epoch)`, on #411; it gates `RenewWorkspaceLease` and `AckWorkspaceRevoked`, after the host check of #416, and takes the line's owner server from `core/host/master/workspace_binding.go` `Host.workspaceLineOwner`, on #423, the one owner decision for current and historical lines (through `PublishedLine.Owner`, which the snapshot builder's `expectOwnerForLine` also calls). The line's owner server is carried in the published line; a move's line names the move's new host; placement names the owner only for the initial line; an unknown owner is sent empty and never adopted. A volume that has seen an epoch owned by one server never adopts that epoch for another (this covers replays). The safety rule is the refusal to adopt a line naming another server; fencing on a foreign line is defence in depth, and only a process that has adopted a lineage fences, on a strictly newer foreign line. Volume: `core/host/volume/assignment_holder.go` `Host.assignmentNamesSelf`, on #411; called by `applyFact` and `IsSuperseded`. | `Host.applyFact` adopts a fact on the replica id alone. `Host.IsSuperseded` ignores a same-replica line from another server. `Host.recordOtherLine` lets an older line overwrite a newer one. Lease renewals and revocation ACKs carry no server id. All four are removed by #411. The master's status frontends and CSI publish target take the freshest same-replica heartbeat from any server (`ObservationStore.SlotFact` via `statusFrontendsForAssignedVolume`), and the operator's primary node is the placement slot (`serverForReplica`). Both are removed by [#416](https://github.com/seaweedfs/seaweed-block/pull/416), stacked on #411. The master computed the line's owner server twice; #423 makes it one function. | authority (master side); volume host (volume side) | | `TERM-LEASE-NOW-001` Lease valid now | The holder may act on its workspace lease at this instant only while the guard has not fenced and host monotonic time is before the start of its last successful renewal plus the granted validity. The granted validity is the master expiry less half the clock-skew bound, capped by the configured TTL. The takeover margin (half the skew bound) exceeds the configured fence-exit budget (watch cadence 50 ms + drain timeout 5 s), assuming normal scheduling; blockmaster refuses a smaller or equal margin at startup, deriving the budget from `durable.ChunkFenceWatchInterval` and `volume.WorkspaceDrainTimeout`. Safety premise for v1.0, alongside one live process per holder (`TERM-ONE-PROCESS-001`): blockmaster's host slews its wall clock, not steps it, while volumes are served; a step larger than the configured skew bound while a lease is live is unsupported (see `docs/operator-guide.md`, Clock safety requirement). This closes coverage gap 8 by a documented premise, not a wall-step test. | `WorkspaceLease` `ExpiresAtNS`, `MaxClockSkewNS`, and the lease view's durable horizon and granted deadline (`core/authority/workspace_lease_view.go`); `WorkspaceLeaseFact` `valid_for_ns`, `expires_at_ns`, `revoking` (`core/rpc/proto/workspace.proto`); `WorkspaceLeaseGuard` `until`, `fenced` (`core/host/volume/workspace_lease.go`) | Holder: `core/host/volume/workspace_lease.go` `WorkspaceLeaseGuard.permits`. Master: `core/authority/workspace_lease_view.go` `Publisher.WorkspaceLeaseValidity` / `workspaceLeaseValidityAt` is shared by renewal admission, `leaseFact` and `AckWorkspaceRevocation`. `WorkspaceLeaseValidity` reads the publisher clock; its leaf calculation uses the larger configured/persisted skew and configured TTL. `Publisher.RenewWorkspaceLease`. `firstWorkspaceGrant` and `regrantWorkspaceLease` are reached only from it, and only it starts the extender `extendWorkspaceLease`. | `WorkspaceLeaseGuard.drain` checks `now < until` again inline before the ACK, and `WorkspaceLeaseGuard.Refresh` repeats the expiry check of `permits`: open (both should call one predicate). The host reply sanity bound in `Refresh` still repeats the publisher's default 30 s TTL: open. Not a duplicate: `Publisher.forcedMoveBarrierLocked` decides the opposite term, "the lease is over for the master" (the horizon and the deadline each plus the full skew bound), which a forced move and a re-grant need. Follow-up for 1.0.1: split `workspaceNow` into wall and monotonic sources so the barrier for in-memory lines uses monotonic time, and add a real independent wall-step test. No new clock seam is added in v1.0. | authority (grant); volume host (guard) | | `TERM-SERVING-001` Serving / ready | A workspace primary claims HEAD, listens, reports ready and admits I/O only while its lease guard permits now and its durable backend is operational. Without a granted lease it holds at the gate and exits 75 after the start-time wait. | `frontend.Projection.Healthy`; the `StorageBackend` operational flag and its evidence, reported as `VolumeStatus.Operational` (`core/frontend/durable`); `StatusProjection.FrontendPrimaryReady` (and `NotReadyReason`, on [#410](https://github.com/seaweedfs/seaweed-block/pull/410)); the ALUA and ANA state; `HeartbeatSlot.frontends` | Authority side: `core/host/volume/projection_bridge.go` `AdapterProjectionView.projectionWithSupersede`, which ANDs in `WorkspaceLeaseGuard.permits` for workspace volumes. Storage side: the `StorageBackend` operational flag (`core/frontend/durable/storage_adapter.go`), written only by `SetOperational` and read by `readyCheck`. The one decision of both sides together is `StorageBackend.AdmitsIO` (the guarded AND), read by the status, the frontend start gate and every I/O: on #410 (today `StorageBackend.gate` on `main`). | `StatusServer.authorityProjection` derives `FrontendPrimaryReady` from the authority view alone, and it repeats the supersede and supporting tests that `Healthy` already contains. #410 adds the backend half in `statusProjection`; the repeated tests remain open. The frontends listen whether or not the backend admits I/O: #410 holds them in `awaitBackendAdmitsIO` until it does. #410 replaces its earlier `backendAdmitsIO` (which read only `VolumeStatus.Operational`) with `StorageBackend.AdmitsIO`. A later lease fence ends the process on [#409](https://github.com/seaweedfs/seaweed-block/pull/409). `projectionALUAProvider.ALUAState` and `projectionANAProvider.ANAState` (`cmd/blockvolume`) follow the projection only: open. The start-time wait (`chunkAuthorityWait`; `ProviderConfig.ChunkAssignmentTimeout`, 30 s by default) ends once, and the process then stays up without serving: #409 makes it exit 75. iSCSI reports a not-ready or busy backend as a medium error, while NVMe retries the same error: [#415](https://github.com/seaweedfs/seaweed-block/pull/415) (`frontend.ClassifyBackendError`). The heartbeat `Frontends` are set when the listeners start and cleared only at shutdown: open. | volume host | diff --git a/seaweed-block/docs/operator-guide.md b/seaweed-block/docs/operator-guide.md index 98e32a3f93..8629ee30aa 100644 --- a/seaweed-block/docs/operator-guide.md +++ b/seaweed-block/docs/operator-guide.md @@ -48,6 +48,47 @@ one live blockvolume per volume ([one process per volume](releases/one-process-p - Without it, blockvolume exits at start with `host volume lock directory unavailable`. Install the entry, or chown the directory to the unit's user. +## Authenticate the control API + +`blockmaster` authenticates every gRPC call with mutual TLS when it starts with all four of `--tls-cert`, +`--tls-key`, `--tls-client-ca` and `--role-file`. Without them it is in development mode: plaintext, loopback only, +and it logs `UNAUTHENTICATED CONTROL API on (development mode)` once a minute. `--insecure-external-bind` +cannot be combined with mutual TLS. + +**Who may call.** The role file has one line per certificate: `sha256: `. The role is +`viewer`, `operator`, `admin` (people and tools; each includes the one before it) or `node` (a volume host; its id is +its `--server-id`). A certificate's CN must equal its line's id. A node may act only for its own server id. A forced +move needs `admin`. `kill -HUP` reloads the file. A removed line is refused from the next call, and its open streams +end at the reload. A malformed file keeps the previous table and says so in the log. `--audit-log ` appends +one JSON line per person's call, per role-file reload and per refused node call (at most once a minute per +certificate and method). + +**Issue the certificates** (one CA, one key per host or person; a node key gives control of that host's volumes, so +never copy it into a host image): + +```bash +openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -days 3650 \ + -subj "/CN=sw-block CA" -keyout ca.key -out ca.crt +# blockmaster: the name volume hosts dial must be in subjectAltName +openssl req -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -subj "/CN=blockmaster" \ + -keyout master.key -out master.csr +openssl x509 -req -in master.csr -CA ca.crt -CAkey ca.key -CAcreateserial -days 825 \ + -extfile <(printf "subjectAltName=DNS:master.example,IP:10.0.0.10") -out master.crt +# a volume host: CN = its --server-id +openssl req -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -subj "/CN=node-a" \ + -keyout node-a.key -out node-a.csr +openssl x509 -req -in node-a.csr -CA ca.crt -CAkey ca.key -CAcreateserial -days 825 -out node-a.crt +# its role-file line +echo "sha256:$(openssl x509 -in node-a.crt -outform DER | sha256sum | cut -d' ' -f1) node node-a" >> roles +``` + +**Volume hosts** dial with `--master-tls-cert`, `--master-tls-key` and `--master-ca`. A volume refuses to start +when its certificate's CN differs from `--server-id`. **sw-block** reads `SW_BLOCK_TLS_CERT`, `SW_BLOCK_TLS_KEY` and +`SW_BLOCK_TLS_CA`. **blockcsi** takes `--master-tls-cert`, `--master-tls-key` and `--master-ca`. Certificate and key +files are read at every new connection, so a rotated file takes effect without a restart. blockmaster closes each +client connection after 24 hours, so a rotated or removed certificate is seen within a day even on an idle link. +The volume's own HTTP routes (`/status`, chunk routes) are not authenticated and stay on loopback. + ## Size a host - **Geometry:** a volume's size is `--durable-blocks` x `--durable-blocksize` on `blockvolume`. It must equal From 9ec7ed821416417d6583b06959234af9717621c0 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 09:29:45 -0800 Subject: [PATCH 14/36] docs: the caller identity term is on #548 Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/design/invariants.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 0d3fff077e..221cc6d279 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -1101,11 +1101,11 @@ A reviewer applies the rule to every pull request: A row that names a function existing only on an open pull request says so ("on #N"). The qualifier is dropped when that pull request merges. Code references name a file and a function, as in the rest of this document. A checker will later verify that every deciding function named here exists on `main`. -11 rows for 6 terms. They name 15 deciding functions: 10 on `main` and 5 only on open pull requests (2 on #411, 1 on #409, 1 on #439, 1 on the phase 0 authentication pull request). One row (`TERM-STOP-STALE-ROOT-001`) has no named function yet. +11 rows for 6 terms. They name 15 deciding functions: 10 on `main` and 5 only on open pull requests (2 on #411, 1 on #409, 1 on #439, 1 on #548). One row (`TERM-STOP-STALE-ROOT-001`) has no named function yet. | Term | Meaning | Field(s) | Deciding function (one per side) | Known second derivations to remove | Owner role | |---|---|---|---|---|---| -| `TERM-CALLER-001` Caller identity (blockmaster control API) | Who is calling blockmaster is the role-file line whose fingerprint is the sha256 of the verified client leaf certificate, with CN equal to the line's id and the certificate not expired on the master clock. A request field never names the caller. A node's id is its server id: a node may act only for that server id. | the TLS peer's verified chain (`credentials.TLSInfo`); the role file's lines `sha256: ` (`auth.Table`); `auth.Principal` `Role`, `ID`, `Fingerprint`, `NotAfter` | Master: `core/auth/identity.go` `Authenticator.PeerIdentity`, on the phase 0 authentication pull request; called by the interceptors on every call and before every stream send, and by `auth.RequireNode` / `auth.RequireRole` through the call's decision. | The registered-host check (`refuseWorkspaceHolderHost`, `refuseServerIDFromOtherHost`) is kept beside it by decision, not a second derivation of the caller: it checks the network address, not the certificate. | authority (master side) | +| `TERM-CALLER-001` Caller identity (blockmaster control API) | Who is calling blockmaster is the role-file line whose fingerprint is the sha256 of the verified client leaf certificate, with CN equal to the line's id and the certificate not expired on the master clock. A request field never names the caller. A node's id is its server id: a node may act only for that server id. | the TLS peer's verified chain (`credentials.TLSInfo`); the role file's lines `sha256: ` (`auth.Table`); `auth.Principal` `Role`, `ID`, `Fingerprint`, `NotAfter` | Master: `core/auth/identity.go` `Authenticator.PeerIdentity`, on [#548](https://github.com/seaweedfs/seaweed-block/pull/548); called by the interceptors on every call and before every stream send, and by `auth.RequireNode` / `auth.RequireRole` through the call's decision. | The registered-host check (`refuseWorkspaceHolderHost`, `refuseServerIDFromOtherHost`) is kept beside it by decision, not a second derivation of the caller: it checks the network address, not the certificate. | authority (master side) | | `TERM-HOLDER-001` Holder identity (the primary of a single-copy workspace volume only; supporting replicas are not holders) | The process that may act as primary of a single-copy workspace volume at an epoch is the pair (server id, replica id) at that epoch. A matching replica id or endpoint alone never names it, and a missing server id is refused. No local-root nonce joins it (V1-SPEC r2.45); one live process per volume on a host is the host lock (`TERM-ONE-PROCESS-001`). | `AssignmentFact` `server_id`, `replica_id`, `epoch` (`core/rpc/proto/control.proto`; `server_id` on [#411](https://github.com/seaweedfs/seaweed-block/pull/411)); `WorkspaceIdentity` `server_id`, `replica_id`, `epoch` (`core/rpc/proto/workspace.proto`; `server_id` on #411); the published line's `PublishedLine.IssuedHost` (`core/authority/workspace_lease_view.go`) and the move journal's `WorkspaceMoveRecord.NewHost` (`core/authority/workspace.go`); the volume's `Config.ServerID`, `Config.ReplicaID` (`core/host/volume/host.go`, from `--server-id`, `--replica-id`); the HEAD `Holder`, written as `/` (`cmd/blockvolume/chunk_remote.go` `chunkHolder`) | Master: `core/host/master/workspace_service.go` `services.holderMatches(volume, replica, server, epoch)`, on #411; it gates `RenewWorkspaceLease` and `AckWorkspaceRevoked`, after the host check of #416, and takes the line's owner server from `core/host/master/workspace_binding.go` `Host.workspaceLineOwner`, on #423, the one owner decision for current and historical lines (through `PublishedLine.Owner`, which the snapshot builder's `expectOwnerForLine` also calls). The line's owner server is carried in the published line; a move's line names the move's new host; placement names the owner only for the initial line; an unknown owner is sent empty and never adopted. A volume that has seen an epoch owned by one server never adopts that epoch for another (this covers replays). The safety rule is the refusal to adopt a line naming another server; fencing on a foreign line is defence in depth, and only a process that has adopted a lineage fences, on a strictly newer foreign line. Volume: `core/host/volume/assignment_holder.go` `Host.assignmentNamesSelf`, on #411; called by `applyFact` and `IsSuperseded`. | `Host.applyFact` adopts a fact on the replica id alone. `Host.IsSuperseded` ignores a same-replica line from another server. `Host.recordOtherLine` lets an older line overwrite a newer one. Lease renewals and revocation ACKs carry no server id. All four are removed by #411. The master's status frontends and CSI publish target take the freshest same-replica heartbeat from any server (`ObservationStore.SlotFact` via `statusFrontendsForAssignedVolume`), and the operator's primary node is the placement slot (`serverForReplica`). Both are removed by [#416](https://github.com/seaweedfs/seaweed-block/pull/416), stacked on #411. The master computed the line's owner server twice; #423 makes it one function. | authority (master side); volume host (volume side) | | `TERM-LEASE-NOW-001` Lease valid now | The holder may act on its workspace lease at this instant only while the guard has not fenced and host monotonic time is before the start of its last successful renewal plus the granted validity. The granted validity is the master expiry less half the clock-skew bound, capped by the configured TTL. The takeover margin (half the skew bound) exceeds the configured fence-exit budget (watch cadence 50 ms + drain timeout 5 s), assuming normal scheduling; blockmaster refuses a smaller or equal margin at startup, deriving the budget from `durable.ChunkFenceWatchInterval` and `volume.WorkspaceDrainTimeout`. Safety premise for v1.0, alongside one live process per holder (`TERM-ONE-PROCESS-001`): blockmaster's host slews its wall clock, not steps it, while volumes are served; a step larger than the configured skew bound while a lease is live is unsupported (see `docs/operator-guide.md`, Clock safety requirement). This closes coverage gap 8 by a documented premise, not a wall-step test. | `WorkspaceLease` `ExpiresAtNS`, `MaxClockSkewNS`, and the lease view's durable horizon and granted deadline (`core/authority/workspace_lease_view.go`); `WorkspaceLeaseFact` `valid_for_ns`, `expires_at_ns`, `revoking` (`core/rpc/proto/workspace.proto`); `WorkspaceLeaseGuard` `until`, `fenced` (`core/host/volume/workspace_lease.go`) | Holder: `core/host/volume/workspace_lease.go` `WorkspaceLeaseGuard.permits`. Master: `core/authority/workspace_lease_view.go` `Publisher.WorkspaceLeaseValidity` / `workspaceLeaseValidityAt` is shared by renewal admission, `leaseFact` and `AckWorkspaceRevocation`. `WorkspaceLeaseValidity` reads the publisher clock; its leaf calculation uses the larger configured/persisted skew and configured TTL. `Publisher.RenewWorkspaceLease`. `firstWorkspaceGrant` and `regrantWorkspaceLease` are reached only from it, and only it starts the extender `extendWorkspaceLease`. | `WorkspaceLeaseGuard.drain` checks `now < until` again inline before the ACK, and `WorkspaceLeaseGuard.Refresh` repeats the expiry check of `permits`: open (both should call one predicate). The host reply sanity bound in `Refresh` still repeats the publisher's default 30 s TTL: open. Not a duplicate: `Publisher.forcedMoveBarrierLocked` decides the opposite term, "the lease is over for the master" (the horizon and the deadline each plus the full skew bound), which a forced move and a re-grant need. Follow-up for 1.0.1: split `workspaceNow` into wall and monotonic sources so the barrier for in-memory lines uses monotonic time, and add a real independent wall-step test. No new clock seam is added in v1.0. | authority (grant); volume host (guard) | | `TERM-SERVING-001` Serving / ready | A workspace primary claims HEAD, listens, reports ready and admits I/O only while its lease guard permits now and its durable backend is operational. Without a granted lease it holds at the gate and exits 75 after the start-time wait. | `frontend.Projection.Healthy`; the `StorageBackend` operational flag and its evidence, reported as `VolumeStatus.Operational` (`core/frontend/durable`); `StatusProjection.FrontendPrimaryReady` (and `NotReadyReason`, on [#410](https://github.com/seaweedfs/seaweed-block/pull/410)); the ALUA and ANA state; `HeartbeatSlot.frontends` | Authority side: `core/host/volume/projection_bridge.go` `AdapterProjectionView.projectionWithSupersede`, which ANDs in `WorkspaceLeaseGuard.permits` for workspace volumes. Storage side: the `StorageBackend` operational flag (`core/frontend/durable/storage_adapter.go`), written only by `SetOperational` and read by `readyCheck`. The one decision of both sides together is `StorageBackend.AdmitsIO` (the guarded AND), read by the status, the frontend start gate and every I/O: on #410 (today `StorageBackend.gate` on `main`). | `StatusServer.authorityProjection` derives `FrontendPrimaryReady` from the authority view alone, and it repeats the supersede and supporting tests that `Healthy` already contains. #410 adds the backend half in `statusProjection`; the repeated tests remain open. The frontends listen whether or not the backend admits I/O: #410 holds them in `awaitBackendAdmitsIO` until it does. #410 replaces its earlier `backendAdmitsIO` (which read only `VolumeStatus.Operational`) with `StorageBackend.AdmitsIO`. A later lease fence ends the process on [#409](https://github.com/seaweedfs/seaweed-block/pull/409). `projectionALUAProvider.ALUAState` and `projectionANAProvider.ANAState` (`cmd/blockvolume`) follow the projection only: open. The start-time wait (`chunkAuthorityWait`; `ProviderConfig.ChunkAssignmentTimeout`, 30 s by default) ends once, and the process then stays up without serving: #409 makes it exit 75. iSCSI reports a not-ready or busy backend as a medium error, while NVMe retries the same error: [#415](https://github.com/seaweedfs/seaweed-block/pull/415) (`frontend.ClassifyBackendError`). The heartbeat `Frontends` are set when the listeners start and cleared only at shutdown: open. | volume host | From 9c77bc66f1b3e2407a67691d6e56447e296957ab Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 11:08:35 -0800 Subject: [PATCH 15/36] test: guard: the node registry is written only by the start-up import Co-Authored-By: Claude Opus 5.5 --- .../blockmaster/node_registry_guard_test.go | 71 +++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 seaweed-block/cmd/blockmaster/node_registry_guard_test.go diff --git a/seaweed-block/cmd/blockmaster/node_registry_guard_test.go b/seaweed-block/cmd/blockmaster/node_registry_guard_test.go new file mode 100644 index 0000000000..08f6512bdc --- /dev/null +++ b/seaweed-block/cmd/blockmaster/node_registry_guard_test.go @@ -0,0 +1,71 @@ +package main + +import ( + "go/ast" + "go/parser" + "go/token" + "io/fs" + "path/filepath" + "sort" + "strings" + "testing" +) + +// The node registry (server id -> registered host) is static after start: +// the identity checks (the registered-host refusal beside the certificate +// identity) assume no one rewrites it while blockmaster serves. Its only +// writer is the cluster-spec import at start-up. This guard fails when a +// new non-test caller of RegisterNode or RemoveNode appears anywhere. +func TestNodeRegistryIsWrittenOnlyAtStartup(t *testing.T) { + root, err := filepath.Abs(filepath.Join("..", "..")) + if err != nil { + t.Fatal(err) + } + var sites []string + fset := token.NewFileSet() + err = filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if d.IsDir() { + switch d.Name() { + case ".git", "vendor", "node_modules", "testdata": + return filepath.SkipDir + } + return nil + } + if !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") { + return nil + } + f, err := parser.ParseFile(fset, path, nil, 0) + if err != nil { + return err + } + rel, _ := filepath.Rel(root, path) + for _, decl := range f.Decls { + fn, ok := decl.(*ast.FuncDecl) + if !ok || fn.Body == nil { + continue + } + ast.Inspect(fn.Body, func(n ast.Node) bool { + call, ok := n.(*ast.CallExpr) + if !ok { + return true + } + if sel, ok := call.Fun.(*ast.SelectorExpr); ok && (sel.Sel.Name == "RegisterNode" || sel.Sel.Name == "RemoveNode") { + sites = append(sites, filepath.ToSlash(rel)+":"+fn.Name.Name+"."+sel.Sel.Name) + } + return true + }) + } + return nil + }) + if err != nil { + t.Fatal(err) + } + sort.Strings(sites) + want := []string{"cmd/blockmaster/main.go:importLifecycleNodeInventory.RegisterNode"} + if strings.Join(sites, ",") != strings.Join(want, ",") { + t.Fatalf("node registry writers = %v, want only %v: a writer after start breaks the static-registry assumption of the identity checks", sites, want) + } +} From 8165ac9414a05e1f4d52a18dde558e8c92abac70 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 14:28:40 -0800 Subject: [PATCH 16/36] test(auth): T10 renewal-path cost at 32 volumes; the per-call check never waits for a reload Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/auth/cost_test.go | 152 ++++++++++++++++++ .../core/auth/nonblocking_internal_test.go | 54 +++++++ 2 files changed, 206 insertions(+) create mode 100644 seaweed-block/core/auth/cost_test.go create mode 100644 seaweed-block/core/auth/nonblocking_internal_test.go diff --git a/seaweed-block/core/auth/cost_test.go b/seaweed-block/core/auth/cost_test.go new file mode 100644 index 0000000000..823ca5411a --- /dev/null +++ b/seaweed-block/core/auth/cost_test.go @@ -0,0 +1,152 @@ +package auth_test + +import ( + "context" + "fmt" + "net" + "os" + "path/filepath" + "sort" + "strings" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/auth" + "github.com/seaweedfs/seaweed-block/core/auth/authtest" + "github.com/seaweedfs/seaweed-block/core/rpc/link" + "google.golang.org/grpc" + "google.golang.org/grpc/health" + healthpb "google.golang.org/grpc/health/grpc_health_v1" +) + +const costVolumes = 32 + +// costServer serves the health check behind the given server options and +// interceptor, and returns its address. +func costServer(t *testing.T, opts ...grpc.ServerOption) string { + t.Helper() + srv := grpc.NewServer(opts...) + healthpb.RegisterHealthServer(srv, health.NewServer()) + lis, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + go srv.Serve(lis) + t.Cleanup(srv.Stop) + return lis.Addr().String() +} + +// costRun dials one connection per volume and makes calls unary calls on +// each, all volumes at once (a renewal tick of 32 volumes). It returns every +// volume's first call (the handshake included) and every later call. +func costRun(t *testing.T, addr string, dial func(i int) grpc.DialOption, calls int) (first, rest []time.Duration) { + t.Helper() + var mu sync.Mutex + var wg sync.WaitGroup + errs := make(chan error, costVolumes) + for i := 0; i < costVolumes; i++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + conn, err := link.DialMaster(addr, dial(i)) + if err != nil { + errs <- err + return + } + defer conn.Close() + c := healthpb.NewHealthClient(conn) + var f time.Duration + var r []time.Duration + for k := 0; k < calls; k++ { + start := time.Now() + if _, err := c.Check(context.Background(), &healthpb.HealthCheckRequest{}); err != nil { + errs <- fmt.Errorf("volume %d call %d: %w", i, k, err) + return + } + d := time.Since(start) + if k == 0 { + f = d + } else { + r = append(r, d) + } + } + mu.Lock() + first, rest = append(first, f), append(rest, r...) + mu.Unlock() + }(i) + } + wg.Wait() + close(errs) + for err := range errs { + t.Fatal(err) + } + return first, rest +} + +func pct(d []time.Duration, p float64) time.Duration { + s := append([]time.Duration(nil), d...) + sort.Slice(s, func(i, j int) bool { return s[i] < s[j] }) + return s[int(float64(len(s)-1)*p)] +} + +// T10: the cost of mutual TLS and the per-call authentication on the renewal +// path, 32 volumes renewing at once, against the same calls in plaintext +// development mode. The bounds are loose (they catch a regression of an order +// of magnitude, not jitter); the measured numbers are logged. +func TestRenewalPathCostAt32Volumes(t *testing.T) { + if testing.Short() { + t.Skip("cost measurement") + } + dir := t.TempDir() + ca := authtest.NewCA(t, "ca") + caPath := ca.WriteCA(t, dir) + mc, mk := ca.Issue(t, "blockmaster", time.Now().Add(time.Hour)).WriteFiles(t, dir, "master") + var roles strings.Builder + nodes := make([]link.TLSFiles, costVolumes) + for i := range nodes { + id := fmt.Sprintf("s%02d", i) + leaf := ca.Issue(t, id, time.Now().Add(time.Hour)) + c, k := leaf.WriteFiles(t, dir, id) + nodes[i] = link.TLSFiles{Cert: c, Key: k, CA: caPath} + fmt.Fprintln(&roles, leaf.Fingerprint, "node", id) + } + rolePath := filepath.Join(dir, "roles") + if err := os.WriteFile(rolePath, []byte(roles.String()), 0o600); err != nil { + t.Fatal(err) + } + table, err := auth.LoadRoleFile(rolePath) + if err != nil { + t.Fatal(err) + } + a := auth.NewAuthenticator(table, nil) + rules := map[string]auth.Rule{"/grpc.health.v1.Health/Check": {Node: true}} + creds, err := link.ServerCredentials(link.TLSFiles{Cert: mc, Key: mk, CA: caPath}) + if err != nil { + t.Fatal(err) + } + const calls = 50 + + tlsAddr := costServer(t, creds, grpc.UnaryInterceptor(a.UnaryInterceptor(rules))) + tlsFirst, tlsRest := costRun(t, tlsAddr, func(i int) grpc.DialOption { + d, err := link.ClientCredentials(nodes[i], "") + if err != nil { + t.Fatal(err) + } + return d + }, calls) + + devAddr := costServer(t, grpc.UnaryInterceptor(auth.DevUnaryInterceptor())) + devFirst, devRest := costRun(t, devAddr, func(int) grpc.DialOption { return nil }, calls) + + t.Logf("T10 %d volumes x %d calls: first call (handshake) p50 %v p99 %v (plaintext %v / %v); per call p50 %v p99 %v (plaintext %v / %v)", + costVolumes, calls, + pct(tlsFirst, 0.5), pct(tlsFirst, 0.99), pct(devFirst, 0.5), pct(devFirst, 0.99), + pct(tlsRest, 0.5), pct(tlsRest, 0.99), pct(devRest, 0.5), pct(devRest, 0.99)) + if p := pct(tlsFirst, 0.99); p > 2*time.Second { + t.Fatalf("handshake p99 %v at %d volumes: far above the lease renewal budget", p, costVolumes) + } + if p := pct(tlsRest, 0.99); p > 100*time.Millisecond { + t.Fatalf("authenticated per-call p99 %v at %d volumes: far above the lease renewal budget", p, costVolumes) + } +} diff --git a/seaweed-block/core/auth/nonblocking_internal_test.go b/seaweed-block/core/auth/nonblocking_internal_test.go new file mode 100644 index 0000000000..72b5e1c140 --- /dev/null +++ b/seaweed-block/core/auth/nonblocking_internal_test.go @@ -0,0 +1,54 @@ +package auth + +import ( + "context" + "crypto/tls" + "crypto/x509" + "net" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/auth/authtest" + "google.golang.org/grpc/credentials" + "google.golang.org/grpc/peer" +) + +// The per-call check never blocks on the role file: while a reload holds the +// authenticator's only lock (the stream wake-up channel), PeerIdentity still +// answers, from the table installed last. +func TestPeerIdentityNeverWaitsForAReload(t *testing.T) { + ca := authtest.NewCA(t, "ca") + leaf := ca.Issue(t, "s1", time.Now().Add(time.Hour)) + table, err := ParseRoleFile(strings.NewReader(leaf.Fingerprint + " node s1\n")) + if err != nil { + t.Fatal(err) + } + a := NewAuthenticator(table, nil) + ctx := peer.NewContext(context.Background(), &peer.Peer{ + Addr: &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 1}, + AuthInfo: credentials.TLSInfo{State: tls.ConnectionState{ + VerifiedChains: [][]*x509.Certificate{{leaf.Cert, ca.Cert}}, + }}, + }) + + a.mu.Lock() // a reload in progress + done := make(chan error, 1) + go func() { + p, err := a.PeerIdentity(ctx) + if err == nil && (p.Role != RoleNode || p.ID != "s1") { + err = context.Canceled + } + done <- err + }() + select { + case err := <-done: + a.mu.Unlock() + if err != nil { + t.Fatalf("PeerIdentity during a reload: %v", err) + } + case <-time.After(2 * time.Second): + a.mu.Unlock() + t.Fatal("PeerIdentity blocked while a reload held the authenticator's lock") + } +} From bf91dce8b488df8d5649f7de7747ec3853536e21 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 14:30:32 -0800 Subject: [PATCH 17/36] test: the procedure harness runs on mutual TLS (SW_BLOCK_PROCEDURE_TLS=1) Co-Authored-By: Claude Opus 5.5 --- .../planned_handoff_integration_test.go | 38 +++++- .../blockvolume/procedure_tls_harness_test.go | 119 ++++++++++++++++++ 2 files changed, 156 insertions(+), 1 deletion(-) create mode 100644 seaweed-block/cmd/blockvolume/procedure_tls_harness_test.go diff --git a/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go b/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go index 0d0ebdb81c..dd4e1bed7d 100644 --- a/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go +++ b/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go @@ -185,6 +185,8 @@ type handoffEnv struct { // A crash test restarts exactly this owned master with the same stores. masterProcess *daemon masterArgs []string + // tls, when set, runs every process with mutual TLS (procedure_tls_harness_test.go). + tls *procedureTLS } // bvHost is one host's blockvolume: its server id, endpoints, local root @@ -210,6 +212,17 @@ func startHandoffEnv(t *testing.T, n int, masterArgs ...string) *handoffEnv { // own, named after it, with its own endpoints and local root (a restore // target, for example). func startHandoffEnvWith(t *testing.T, n int, targets []string, masterArgs ...string) *handoffEnv { + t.Helper() + var tlsCfg map[string]time.Time + if procedureTLSOn() { + tlsCfg = map[string]time.Time{} + } + return startHandoffEnvTLS(t, n, targets, tlsCfg, masterArgs...) +} + +// startHandoffEnvTLS is startHandoffEnvWith with mutual TLS when tlsNotAfter +// is non-nil (it overrides chosen node certificates' expiry). +func startHandoffEnvTLS(t *testing.T, n int, targets []string, tlsNotAfter map[string]time.Time, masterArgs ...string) *handoffEnv { t.Helper() h := newPlannedHandoffHarness(t) env := &handoffEnv{h: h, cluster: startWorkspaceWeed(t), chunkPath: fmt.Sprintf("/handoff-%d", time.Now().UnixNano()), hosts: map[string]bvHost{}} @@ -224,6 +237,15 @@ func startHandoffEnvWith(t *testing.T, n int, targets []string, masterArgs ...st env.hosts[id] = bvHost{id: id, data: handoffAddress(t), ctrl: handoffAddress(t), status: handoffAddress(t), nvme: handoffAddress(t), root: filepath.Join(h.dir, "vol-"+id), volume: v} } cluster, chunkPath := env.cluster, env.chunkPath + if tlsNotAfter != nil { + servers := make([]string, 0, len(env.hosts)) + for _, b := range env.hosts { + servers = append(servers, b.id) + } + env.tls = newProcedureTLS(t, h.dir, servers, tlsNotAfter) + h.cliEnv = env.tls.cliEnv("admin") + masterArgs = append(env.tls.masterArgs(), masterArgs...) + } // 1. The cluster spec. var nodes, volumes strings.Builder @@ -290,7 +312,15 @@ func (env *handoffEnv) volArgsFor(b bvHost) []string { "--durable-root", b.root, "--durable-impl", "walstore-chunk", "--durable-blocks", "65536", "--durable-blocksize", "4096", "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath, "--chunk-control-endpoint", - "--workspace-lease", "--nvme-listen", b.nvme, "--nvme-subsysnqn", plannedHandoffNQN}, env.volExtra...) + "--workspace-lease", "--nvme-listen", b.nvme, "--nvme-subsysnqn", plannedHandoffNQN}, append(env.tlsVolumeArgs(server), env.volExtra...)...) +} + +// tlsVolumeArgs is server's node identity when the env runs with mutual TLS. +func (env *handoffEnv) tlsVolumeArgs(server string) []string { + if env.tls == nil { + return nil + } + return env.tls.volumeArgs(server) } func fatalOn(t *testing.T) (func(error), func(uint64, error) uint64) { @@ -318,6 +348,9 @@ type plannedHandoffHarness struct { t *testing.T logMu sync.Mutex logDone bool + // cliEnv is added to every sw-block command's environment (its master + // TLS identity when the env runs with mutual TLS). + cliEnv []string } func newPlannedHandoffHarness(t *testing.T) *plannedHandoffHarness { @@ -559,6 +592,9 @@ func (h *plannedHandoffHarness) run(t *testing.T, args ...string) (string, strin defer cancel() cmd := exec.CommandContext(ctx, h.cli, args...) cmd.Dir = h.dir + if len(h.cliEnv) > 0 { + cmd.Env = append(os.Environ(), h.cliEnv...) + } cmd.WaitDelay = 5 * time.Second var stdout, stderr strings.Builder cmd.Stdout, cmd.Stderr = &stdout, &stderr diff --git a/seaweed-block/cmd/blockvolume/procedure_tls_harness_test.go b/seaweed-block/cmd/blockvolume/procedure_tls_harness_test.go new file mode 100644 index 0000000000..159580b0fa --- /dev/null +++ b/seaweed-block/cmd/blockvolume/procedure_tls_harness_test.go @@ -0,0 +1,119 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "fmt" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/auth/authtest" +) + +// procedureTLS is the procedure harness's mutual-TLS setup: one CA, the +// master's certificate, one node certificate per server id (CN = server id), +// an admin and an operator certificate, and the role file. With it the +// harness runs blockmaster with --tls-*/--role-file, every blockvolume with +// --master-tls-*, and every sw-block command with SW_BLOCK_TLS_* (admin). +type procedureTLS struct { + dir string + ca *authtest.CA + roles string + notAfter map[string]time.Time // per certificate name, when set +} + +// procedureTLSOn reports whether the procedure gate runs on the TLS binaries +// (T14): SW_BLOCK_PROCEDURE_TLS=1. +func procedureTLSOn() bool { return os.Getenv("SW_BLOCK_PROCEDURE_TLS") == "1" } + +func (p *procedureTLS) path(name, ext string) string { return filepath.Join(p.dir, name+ext) } + +// issue writes name.crt/name.key for CN cn and adds its role-file line. +func (p *procedureTLS) issue(t *testing.T, name, cn, role string, notAfter time.Time) { + t.Helper() + leaf := p.ca.Issue(t, cn, notAfter) + leaf.WriteFiles(t, p.dir, name) + if role != "" { + p.addRole(t, leaf.Fingerprint, role, cn) + } +} + +func (p *procedureTLS) addRole(t *testing.T, fingerprint, role, id string) { + t.Helper() + f, err := os.OpenFile(p.roles, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0o600) + if err != nil { + t.Fatal(err) + } + defer f.Close() + if _, err := fmt.Fprintln(f, fingerprint, role, id); err != nil { + t.Fatal(err) + } +} + +// removeRole drops id's line from the role file (a revocation before SIGHUP +// or a restart). +func (p *procedureTLS) removeRole(t *testing.T, id string) { + t.Helper() + raw, err := os.ReadFile(p.roles) + if err != nil { + t.Fatal(err) + } + var keep []string + for _, l := range strings.Split(strings.TrimRight(string(raw), "\n"), "\n") { + if f := strings.Fields(l); len(f) == 3 && f[2] == id { + continue + } + keep = append(keep, l) + } + if err := os.WriteFile(p.roles, []byte(strings.Join(keep, "\n")+"\n"), 0o600); err != nil { + t.Fatal(err) + } +} + +// newProcedureTLS issues the master, admin and operator certificates and one +// node certificate per server id (notAfter overrides a node's expiry). +func newProcedureTLS(t *testing.T, dir string, servers []string, notAfter map[string]time.Time) *procedureTLS { + t.Helper() + p := &procedureTLS{dir: filepath.Join(dir, "tls"), notAfter: notAfter} + if err := os.MkdirAll(p.dir, 0o700); err != nil { + t.Fatal(err) + } + p.roles = p.path("roles", "") + p.ca = authtest.NewCA(t, "procedure CA") + p.ca.WriteCA(t, p.dir) + day := time.Now().Add(24 * time.Hour) + p.issue(t, "master", "blockmaster", "", day) + p.issue(t, "admin", "procedure-admin", "admin", day) + p.issue(t, "operator", "procedure-operator", "operator", day) + seen := map[string]bool{} + for _, s := range servers { + if seen[s] { + continue + } + seen[s] = true + exp := day + if at, ok := notAfter[s]; ok { + exp = at + } + p.issue(t, s, s, "node", exp) + } + return p +} + +func (p *procedureTLS) masterArgs() []string { + return []string{"--tls-cert", p.path("master", ".crt"), "--tls-key", p.path("master", ".key"), + "--tls-client-ca", p.path("ca", ".crt"), "--role-file", p.roles} +} + +// volumeArgs is the node identity of server for blockvolume. +func (p *procedureTLS) volumeArgs(server string) []string { + return []string{"--master-tls-cert", p.path(server, ".crt"), "--master-tls-key", p.path(server, ".key"), "--master-ca", p.path("ca", ".crt")} +} + +// cliEnv is the identity name (admin, operator, a server id) for sw-block. +func (p *procedureTLS) cliEnv(name string) []string { + return []string{"SW_BLOCK_TLS_CERT=" + p.path(name, ".crt"), "SW_BLOCK_TLS_KEY=" + p.path(name, ".key"), "SW_BLOCK_TLS_CA=" + p.path("ca", ".crt")} +} From b842582d5f44691c92c65523abea97da0b547142 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 14:42:46 -0800 Subject: [PATCH 18/36] test: the revoke-crash procedure renews as its holder over mutual TLS when the gate runs on TLS Co-Authored-By: Claude Opus 5.5 --- ...ure_master_revoke_crash_integration_test.go | 3 +-- .../blockvolume/procedure_tls_harness_test.go | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/procedure_master_revoke_crash_integration_test.go b/seaweed-block/cmd/blockvolume/procedure_master_revoke_crash_integration_test.go index 90c2b456c9..7b3c70b1f7 100644 --- a/seaweed-block/cmd/blockvolume/procedure_master_revoke_crash_integration_test.go +++ b/seaweed-block/cmd/blockvolume/procedure_master_revoke_crash_integration_test.go @@ -16,7 +16,6 @@ import ( "github.com/seaweedfs/seaweed-block/core/rpc/control" "google.golang.org/grpc" - "google.golang.org/grpc/credentials/insecure" ) // P13.6 / INV-WS-CLEAN-MOVE-001 / INV-WS-REVOKE-ACK-001: @@ -43,7 +42,7 @@ func masterKilledWhileRevoking(t *testing.T, freeze bool) { l := env.sealedLSN(t, e, g) // Freeze only the owned holder so it cannot race an ACK past the // observed Revoking/no-ACK boundary. This is not a graceful master stop. - conn, err := grpc.NewClient(env.h.masterAddr, grpc.WithTransportCredentials(insecure.NewCredentials())) + conn, err := grpc.NewClient(env.h.masterAddr, env.masterDialOption(t, "s1")) // it renews as the holder if err != nil { t.Fatal(err) } diff --git a/seaweed-block/cmd/blockvolume/procedure_tls_harness_test.go b/seaweed-block/cmd/blockvolume/procedure_tls_harness_test.go index 159580b0fa..5144bdd0ee 100644 --- a/seaweed-block/cmd/blockvolume/procedure_tls_harness_test.go +++ b/seaweed-block/cmd/blockvolume/procedure_tls_harness_test.go @@ -11,6 +11,9 @@ import ( "time" "github.com/seaweedfs/seaweed-block/core/auth/authtest" + "github.com/seaweedfs/seaweed-block/core/rpc/link" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" ) // procedureTLS is the procedure harness's mutual-TLS setup: one CA, the @@ -117,3 +120,18 @@ func (p *procedureTLS) volumeArgs(server string) []string { func (p *procedureTLS) cliEnv(name string) []string { return []string{"SW_BLOCK_TLS_CERT=" + p.path(name, ".crt"), "SW_BLOCK_TLS_KEY=" + p.path(name, ".key"), "SW_BLOCK_TLS_CA=" + p.path("ca", ".crt")} } + +// masterDialOption is the transport for a test's own gRPC client of the env's +// master, acting as name (admin, operator or a server id) with mutual TLS, +// plaintext otherwise. +func (env *handoffEnv) masterDialOption(t *testing.T, name string) grpc.DialOption { + t.Helper() + if env.tls == nil { + return grpc.WithTransportCredentials(insecure.NewCredentials()) + } + d, err := link.ClientCredentials(link.TLSFiles{Cert: env.tls.path(name, ".crt"), Key: env.tls.path(name, ".key"), CA: env.tls.path("ca", ".crt")}, "") + if err != nil { + t.Fatal(err) + } + return d +} From 3c38ad18ef6680c8f1b75643707079a0097e9176 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 14:45:02 -0800 Subject: [PATCH 19/36] test: phase 0 procedure tests T8, T11, T12 on the TLS binaries Co-Authored-By: Claude Opus 5.5 --- .../procedure_tls_integration_test.go | 150 ++++++++++++++++++ 1 file changed, 150 insertions(+) create mode 100644 seaweed-block/cmd/blockvolume/procedure_tls_integration_test.go diff --git a/seaweed-block/cmd/blockvolume/procedure_tls_integration_test.go b/seaweed-block/cmd/blockvolume/procedure_tls_integration_test.go new file mode 100644 index 0000000000..95c7698398 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/procedure_tls_integration_test.go @@ -0,0 +1,150 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "bytes" + "context" + "os" + "syscall" + "testing" + "time" + + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// Phase 0 procedure tests on the TLS binaries (the gate's T6-T13). Each runs +// real blockmaster, blockvolume and sw-block processes with mutual TLS. + +func startTLSEnv(t *testing.T, n int, targets []string, notAfter map[string]time.Time) *handoffEnv { + t.Helper() + if notAfter == nil { + notAfter = map[string]time.Time{} + } + return startHandoffEnvTLS(t, n, targets, notAfter) +} + +func (env *handoffEnv) dialAs(t *testing.T, name string) *grpc.ClientConn { + t.Helper() + conn, err := grpc.NewClient(env.h.masterAddr, env.masterDialOption(t, name)) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = conn.Close() }) + return conn +} + +func wantCode(t *testing.T, what string, err error, want codes.Code) { + t.Helper() + if status.Code(err) != want { + t.Fatalf("%s: %v; want %s", what, err, want) + } +} + +// T8: a node certificate acting for another server's volume (s2's identity +// renewing, ACKing, heartbeating and subscribing as s1) is refused at each +// call, and s1's lease and service are unaffected. +func TestProcedureTLSWrongNodeCertificateIsRefused(t *testing.T) { + env := startTLSEnv(t, 2, nil, nil) + d := env.start(t, "blockvolume-s1", "s1") + e := env.adopt(t, d, "s1") + block := pattern("wrong-node-cert!") + env.writeBlock(t, "s1", 0, block) + + conn := env.dialAs(t, "s2") + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + id := &control.WorkspaceIdentity{VolumeId: "v1", ReplicaId: "r1", Epoch: e, ServerId: "s1"} + ws := control.NewWorkspaceServiceClient(conn) + _, err := ws.RenewWorkspaceLease(ctx, id) + wantCode(t, "s2's certificate renewing s1's lease", err, codes.PermissionDenied) + _, err = ws.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: id, HeadGen: 1}) + wantCode(t, "s2's certificate ACKing for s1", err, codes.PermissionDenied) + _, err = control.NewObservationServiceClient(conn).ReportHeartbeat(ctx, &control.HeartbeatReport{ServerId: "s1"}) + wantCode(t, "s2's certificate heartbeating as s1", err, codes.PermissionDenied) + stream, err := control.NewAssignmentServiceClient(conn).SubscribeAssignments(ctx, &control.SubscribeRequest{VolumeId: "v1", ReplicaId: "r1", ServerId: "s1"}) + if err == nil { + _, err = stream.Recv() + } + wantCode(t, "s2's certificate subscribing as s1", err, codes.PermissionDenied) + + // s1 keeps its lease past one TTL and still serves the block. + time.Sleep(35 * time.Second) + if d.has("workspace lease: fenced") || !env.frontendReadyAt("s1") { + t.Fatal("s1 lost its lease or its frontend after the refused calls") + } + if !bytes.Equal(env.readBlock(t, "s1", 0), block) { + t.Fatal("s1 no longer reads its block") + } +} + +// T11: a role file corrupted and reloaded (SIGHUP) under load keeps the +// previous table: no fence, no change. +func TestProcedureTLSCorruptRoleFileAtReloadChangesNothing(t *testing.T) { + env := startTLSEnv(t, 1, nil, nil) + d := env.start(t, "blockvolume-s1", "s1") + env.adopt(t, d, "s1") + good, err := os.ReadFile(env.tls.roles) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(env.tls.roles, []byte("sha256:not-a-fingerprint node s1\n"), 0o600); err != nil { + t.Fatal(err) + } + if err := env.masterProcess.proc.Signal(syscall.SIGHUP); err != nil { + t.Fatal(err) + } + env.masterProcess.waitLog(t, 10*time.Second, "NOT reloaded, the previous table stays") + deadline := time.Now().Add(40 * time.Second) // more than one lease TTL under writes + for i := uint64(0); time.Now().Before(deadline); i++ { + b := bytes.Repeat([]byte{byte(i)}, 4096) + env.writeBlock(t, "s1", i%64, b) + if !bytes.Equal(env.readBlock(t, "s1", i%64), b) { + t.Fatalf("write %d did not read back after the corrupt reload", i) + } + time.Sleep(500 * time.Millisecond) + } + if d.has("workspace lease: fenced") || !env.frontendReadyAt("s1") { + t.Fatal("the holder fenced after a corrupt role file was refused") + } + if err := os.WriteFile(env.tls.roles, good, 0o600); err != nil { + t.Fatal(err) + } +} + +// T12: blockmaster restarted with one holder removed from the role file: +// that holder fences (its renewals are refused until its lease ends); the +// other holder keeps serving. +func TestProcedureTLSMasterRestartWithAHolderRemoved(t *testing.T) { + env := startTLSEnv(t, 1, []string{"v2"}, nil) + d1 := env.start(t, "blockvolume-s1", "s1") + env.adopt(t, d1, "s1") + d2 := env.h.start(t, "blockvolume-n-v2", env.h.volume, env.volArgsFor(env.hosts["n-v2"])...) + d2.waitLog(t, 60*time.Second, "blockvolume: volume v2 adopted as PRIMARY at r1@") + + env.tls.removeRole(t, "s1") + env.masterProcess.kill(t) + env.masterProcess = env.h.start(t, "blockmaster-restarted", env.h.master, env.masterArgs...) + env.masterProcess.waitLog(t, 30*time.Second, "blockmaster: lock acquired, reloaded=") + + // s1 cannot renew any more: it fences within its lease and exits. + if err := d1.wait(90 * time.Second); err == nil { + t.Fatal("s1 exited 0; want the fence exit") + } + if !d1.has("workspace lease: fenced volume=v1") { + t.Fatalf("s1 exited without a lease fence line (log %s)", d1.log) + } + // n-v2 keeps renewing and serving. + time.Sleep(5 * time.Second) + select { + case <-d2.done: + t.Fatalf("n-v2 exited although its line is still in the role file: %v", d2.err) + default: + } + if d2.has("workspace lease: fenced") { + t.Fatal("n-v2 fenced although its line is still in the role file") + } +} From d5b96e782624aae381e065b94a5eade7033dcc63 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 14:47:56 -0800 Subject: [PATCH 20/36] fix(master): a heartbeat for another server id is refused before its report is validated Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/host/master/services.go | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/seaweed-block/core/host/master/services.go b/seaweed-block/core/host/master/services.go index 195d72b8d3..1e3c82f6ac 100644 --- a/seaweed-block/core/host/master/services.go +++ b/seaweed-block/core/host/master/services.go @@ -307,11 +307,13 @@ func (s *services) ExecuteFailback(ctx context.Context, req *control.FailbackReq // authority.HeartbeatMessage, and calls the observation host's // Ingest path. func (s *services) ReportHeartbeat(ctx context.Context, r *control.HeartbeatReport) (*control.HeartbeatAck, error) { - if err := validateHeartbeat(r); err != nil { + // Phase 0: a node reports only for its own server id (TERM-CALLER-001), + // decided before the report is validated: a caller acting for another + // server is refused whatever it sends. + if err := auth.RequireNode(ctx, r.GetServerId()); err != nil { return nil, err } - // Phase 0: a node reports only for its own server id (TERM-CALLER-001). - if err := auth.RequireNode(ctx, r.ServerId); err != nil { + if err := validateHeartbeat(r); err != nil { return nil, err } // Journal isolation: alarm on a durable root sharing the authority From 8578b80cc97e512fe6a4a88cce9d7a3790797ec7 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 14:55:56 -0800 Subject: [PATCH 21/36] sw-block: 'not authorized' (exit 5) with the cure for a refused caller or a plaintext client of a TLS master; T13 Co-Authored-By: Claude Opus 5.5 --- .../procedure_tls_integration_test.go | 26 +++++++++++ seaweed-block/cmd/sw-block/workspace.go | 7 ++- .../core/rpc/wsclient/notauthorized_test.go | 45 +++++++++++++++++++ seaweed-block/core/rpc/wsclient/wsclient.go | 15 ++++++- 4 files changed, 91 insertions(+), 2 deletions(-) create mode 100644 seaweed-block/core/rpc/wsclient/notauthorized_test.go diff --git a/seaweed-block/cmd/blockvolume/procedure_tls_integration_test.go b/seaweed-block/cmd/blockvolume/procedure_tls_integration_test.go index 95c7698398..aa05b10576 100644 --- a/seaweed-block/cmd/blockvolume/procedure_tls_integration_test.go +++ b/seaweed-block/cmd/blockvolume/procedure_tls_integration_test.go @@ -6,6 +6,7 @@ import ( "bytes" "context" "os" + "strings" "syscall" "testing" "time" @@ -148,3 +149,28 @@ func TestProcedureTLSMasterRestartWithAHolderRemoved(t *testing.T) { t.Fatal("n-v2 fenced although its line is still in the role file") } } + +// T13: sw-block without a client certificate against the TLS master is +// refused at the handshake; it exits "not authorized" (5) and names the cure. +// With an operator certificate, a forced move is refused as not authorized +// too (it needs admin). +func TestProcedureTLSPlaintextClientIsRefusedWithTheCure(t *testing.T) { + env := startTLSEnv(t, 1, nil, nil) + admin := env.h.cliEnv + env.h.cliEnv = []string{"SW_BLOCK_TLS_CERT=", "SW_BLOCK_TLS_KEY=", "SW_BLOCK_TLS_CA="} + _, stderr, code := env.h.run(t, env.show...) + if code != 5 || !strings.Contains(stderr, "SW_BLOCK_TLS_CERT") || !strings.Contains(stderr, "mutual TLS") { + t.Fatalf("plaintext sw-block against the TLS master: exit %d, stderr %q; want 5 naming SW_BLOCK_TLS_CERT and mutual TLS", code, stderr) + } + env.h.cliEnv = env.tls.cliEnv("operator") + _, stderr, code = env.h.run(t, "ops", "workspace", "force-move", "--master", env.h.masterAddr, "--volume", "v1", + "--target-host", "s1", "--target-data", env.hosts["s1"].data, "--target-ctrl", env.hosts["s1"].ctrl, + "--request-id", "t13-operator", "--confirm-forced", "v1@1") + if code != 5 || !strings.Contains(stderr, "admin") { + t.Fatalf("operator forced move: exit %d, stderr %q; want 5 naming admin", code, stderr) + } + env.h.cliEnv = admin + if _, _, code := env.h.run(t, env.show...); code != 0 { + t.Fatalf("admin show: exit %d", code) + } +} diff --git a/seaweed-block/cmd/sw-block/workspace.go b/seaweed-block/cmd/sw-block/workspace.go index c1c5368ef9..afc06e0cc6 100644 --- a/seaweed-block/cmd/sw-block/workspace.go +++ b/seaweed-block/cmd/sw-block/workspace.go @@ -19,6 +19,7 @@ const ( wsExitRefusedLocally = 2 // bad usage or confirmation; no RPC was sent wsExitUnknown = 3 // outcome unknown: rerun with the SAME --request-id wsExitReadoutUnproven = 4 // move issued (or ranges exist) but the lost range is not proven + wsExitNotAuthorized = 5 // blockmaster did not accept this caller; nothing was done wsDefaultTimeout = 30 * time.Second workspaceForceMoveName = "sw-block ops workspace force-move" workspaceLostRangeName = "sw-block ops workspace lost-range" @@ -68,7 +69,9 @@ for a forced move whose record is missing or fails its checks. exit: 0 done; 1 refused by the master (nothing moved); 2 refused locally (usage or confirmation; nothing sent); 3 outcome unknown: rerun with the SAME --request-id; 4 the move is issued but its lost range is not proven (or a -stored range is unreadable). +stored range is unreadable); 5 not authorized by blockmaster (no client +certificate where it requires mutual TLS, or a certificate or role its role +file does not admit; set SW_BLOCK_TLS_CERT, SW_BLOCK_TLS_KEY, SW_BLOCK_TLS_CA). ` // workspaceDial is swapped by tests. @@ -111,6 +114,8 @@ func workspaceExit(o wsclient.Outcome) int { return wsExitRefused case wsclient.OutcomeReadoutUnproven: return wsExitReadoutUnproven + case wsclient.OutcomeNotAuthorized: + return wsExitNotAuthorized } return wsExitUnknown } diff --git a/seaweed-block/core/rpc/wsclient/notauthorized_test.go b/seaweed-block/core/rpc/wsclient/notauthorized_test.go new file mode 100644 index 0000000000..6cd1a0ca91 --- /dev/null +++ b/seaweed-block/core/rpc/wsclient/notauthorized_test.go @@ -0,0 +1,45 @@ +package wsclient + +import ( + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/rpc/link" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// Refusals by authentication or authorization are "not authorized", and a +// plaintext client against a TLS master is told the cure; a transport error +// with a client identity configured stays unknown. +func TestClassifyNotAuthorized(t *testing.T) { + preface := status.Error(codes.Unavailable, `connection error: desc = "error reading server preface: EOF"`) + for _, c := range []struct { + name string + err error + tlsEnv bool + want Outcome + message string + }{ + {"unauthenticated", status.Error(codes.Unauthenticated, "certificate sha256:ab (CN=x) is not in the role file"), false, OutcomeNotAuthorized, "role file"}, + {"permission denied", status.Error(codes.PermissionDenied, "operator alice may not do this: it needs admin"), false, OutcomeNotAuthorized, "needs admin"}, + {"plaintext against TLS", preface, false, OutcomeNotAuthorized, link.EnvTLSCert}, + {"preface error with an identity configured", preface, true, OutcomeUnknown, ""}, + {"master down", status.Error(codes.Unavailable, "connection refused"), false, OutcomeUnknown, ""}, + } { + t.Run(c.name, func(t *testing.T) { + v := "" + if c.tlsEnv { + v = "/some/cert.pem" + } + t.Setenv(link.EnvTLSCert, v) + err := classify("show", c.err) + if got := OutcomeOf(err); got != c.want { + t.Fatalf("outcome %v; want %v (%v)", got, c.want, err) + } + if c.message != "" && !strings.Contains(err.Error(), c.message) { + t.Fatalf("message %q does not name %q", err, c.message) + } + }) + } +} diff --git a/seaweed-block/core/rpc/wsclient/wsclient.go b/seaweed-block/core/rpc/wsclient/wsclient.go index ba54eb2f06..fa65cf6f7a 100644 --- a/seaweed-block/core/rpc/wsclient/wsclient.go +++ b/seaweed-block/core/rpc/wsclient/wsclient.go @@ -12,6 +12,7 @@ import ( "context" "errors" "fmt" + "os" "strconv" "strings" "time" @@ -41,6 +42,10 @@ const ( // OutcomeReadoutUnproven: the lost range cannot be read (missing record // or failed checks); it must never be reported as "no loss". OutcomeReadoutUnproven + // OutcomeNotAuthorized: blockmaster did not accept this caller (no + // certificate, one not in its role file, or a role that may not do this); + // nothing was done. + OutcomeNotAuthorized ) // ErrConfirmation refuses a forced move locally: the confirmation must be @@ -76,7 +81,15 @@ func classify(op string, err error) error { return nil } switch status.Code(err) { - case codes.FailedPrecondition, codes.InvalidArgument, codes.NotFound, codes.PermissionDenied, codes.Unimplemented: + case codes.Unauthenticated, codes.PermissionDenied: + return &Error{Outcome: OutcomeNotAuthorized, Op: op, Err: fmt.Errorf("not authorized by blockmaster: %s (its role file must list this certificate's fingerprint with a role allowed to do this)", status.Convert(err).Message())} + case codes.Unavailable: + // A plaintext client against blockmaster with mutual TLS: the server + // closes the connection before its HTTP/2 preface. + if os.Getenv(link.EnvTLSCert) == "" && strings.Contains(status.Convert(err).Message(), "error reading server preface") { + return &Error{Outcome: OutcomeNotAuthorized, Op: op, Err: fmt.Errorf("blockmaster refused this plaintext connection: it requires mutual TLS; set %s, %s and %s to a certificate in its role file and its CA", link.EnvTLSCert, link.EnvTLSKey, link.EnvTLSCA)} + } + case codes.FailedPrecondition, codes.InvalidArgument, codes.NotFound, codes.Unimplemented: return &Error{Outcome: OutcomeRefused, Op: op, Err: errors.New(status.Convert(err).Message())} case codes.DataLoss: return &Error{Outcome: OutcomeReadoutUnproven, Op: op, Err: errors.New(status.Convert(err).Message())} From bfaf9aec1920c3a23a1551dbdea4019e18d00690 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 14:58:56 -0800 Subject: [PATCH 22/36] test: T13 keeps the plaintext refusal; the operator's forced move is T7's Co-Authored-By: Claude Opus 5.5 --- .../cmd/blockvolume/procedure_tls_integration_test.go | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/procedure_tls_integration_test.go b/seaweed-block/cmd/blockvolume/procedure_tls_integration_test.go index aa05b10576..0f2184bb5d 100644 --- a/seaweed-block/cmd/blockvolume/procedure_tls_integration_test.go +++ b/seaweed-block/cmd/blockvolume/procedure_tls_integration_test.go @@ -152,8 +152,8 @@ func TestProcedureTLSMasterRestartWithAHolderRemoved(t *testing.T) { // T13: sw-block without a client certificate against the TLS master is // refused at the handshake; it exits "not authorized" (5) and names the cure. -// With an operator certificate, a forced move is refused as not authorized -// too (it needs admin). +// (A forced move by an operator is refused at the master: T7 and +// TestForcedMoveNeedsAnAdmin.) func TestProcedureTLSPlaintextClientIsRefusedWithTheCure(t *testing.T) { env := startTLSEnv(t, 1, nil, nil) admin := env.h.cliEnv @@ -162,13 +162,6 @@ func TestProcedureTLSPlaintextClientIsRefusedWithTheCure(t *testing.T) { if code != 5 || !strings.Contains(stderr, "SW_BLOCK_TLS_CERT") || !strings.Contains(stderr, "mutual TLS") { t.Fatalf("plaintext sw-block against the TLS master: exit %d, stderr %q; want 5 naming SW_BLOCK_TLS_CERT and mutual TLS", code, stderr) } - env.h.cliEnv = env.tls.cliEnv("operator") - _, stderr, code = env.h.run(t, "ops", "workspace", "force-move", "--master", env.h.masterAddr, "--volume", "v1", - "--target-host", "s1", "--target-data", env.hosts["s1"].data, "--target-ctrl", env.hosts["s1"].ctrl, - "--request-id", "t13-operator", "--confirm-forced", "v1@1") - if code != 5 || !strings.Contains(stderr, "admin") { - t.Fatalf("operator forced move: exit %d, stderr %q; want 5 naming admin", code, stderr) - } env.h.cliEnv = admin if _, _, code := env.h.run(t, env.show...); code != 0 { t.Fatalf("admin show: exit %d", code) From 29c917aac129bfe0942cfc084167b73339769f86 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 15:00:19 -0800 Subject: [PATCH 23/36] test: T6 expired and T7 revoked holder certificate: fence, admin forced move, lost range Co-Authored-By: Claude Opus 5.5 --- .../procedure_tls_integration_test.go | 87 +++++++++++++++++++ 1 file changed, 87 insertions(+) diff --git a/seaweed-block/cmd/blockvolume/procedure_tls_integration_test.go b/seaweed-block/cmd/blockvolume/procedure_tls_integration_test.go index 0f2184bb5d..2a87af65c3 100644 --- a/seaweed-block/cmd/blockvolume/procedure_tls_integration_test.go +++ b/seaweed-block/cmd/blockvolume/procedure_tls_integration_test.go @@ -5,6 +5,7 @@ package main_test import ( "bytes" "context" + "fmt" "os" "strings" "syscall" @@ -167,3 +168,89 @@ func TestProcedureTLSPlaintextClientIsRefusedWithTheCure(t *testing.T) { t.Fatalf("admin show: exit %d", code) } } + +// fencedHolderThenForcedMove is T6/T7's flow: s1 serves, publishes block 0 +// (seal), writes block 8 after it (unpublished), then lose() takes its +// certificate away. s1 fences and exits; when operatorFirst, an operator's +// forced move is refused as not authorized; the admin's forced move is +// admitted, s2 serves block 0, block 8 is the recorded lost range. +func fencedHolderThenForcedMove(t *testing.T, env *handoffEnv, lose func(), operatorFirst bool) { + t.Helper() + must, mustU := fatalOn(t) + d := env.start(t, "blockvolume-s1", "s1") + e := env.adopt(t, d, "s1") + kept := pattern("published-block!") + env.writeBlock(t, "s1", 0, kept) + g := env.seal(t, "s1", e) + l := env.sealedLSN(t, e, g) + env.writeBlock(t, "s1", 8, pattern("after-the-seal!!")) + + lose() + if err := d.wait(150 * time.Second); err == nil { + t.Fatal("s1 exited 0 after losing its certificate; want the fence exit") + } + if !d.has("workspace lease: fenced volume=v1") { + t.Fatalf("s1 exited without a lease fence line (log %s)", d.log) + } + + if operatorFirst { + admin := env.h.cliEnv + env.h.cliEnv = env.tls.cliEnv("operator") + b := env.hosts["s2"] + args := []string{"ops", "workspace", "force-move", "--master", env.h.masterAddr, "--volume", "v1", + "--target-host", b.id, "--target-data", b.data, "--target-ctrl", b.ctrl, + "--request-id", "force-by-operator", "--confirm-forced", fmt.Sprintf("v1@%d", e)} + poll(t, 120*time.Second, "the forced move preview never admitted (operator)", func() bool { + out, _, _ := env.h.run(t, append(args, "--dry-run")...) + return previewAdmitted(out) + }) + _, stderr, code := env.h.run(t, args...) + if code != 5 || !strings.Contains(stderr, "admin") { + t.Fatalf("operator forced move: exit %d, stderr %q; want 5 (not authorized) naming admin", code, stderr) + } + env.h.cliEnv = admin + } + + out := env.forceMove(t, e, "s2", "force-v1-tls") + e2 := mustU(forcedEpoch(out, e, "s1", "s2")) + if got := mustU(forcedKeptLSN(out)); got != l { + t.Fatalf("the forced move kept LSN %d; want the sealed HEAD's %d", got, l) + } + ranges, _ := env.h.command(t, "ops", "workspace", "lost-range", "--master", env.h.masterAddr, "--volume", "v1") + if !strings.Contains(ranges, "range 1 of 1: request force-v1-tls, r1@") { + t.Fatalf("lost-range does not show the forced move:\n%s", ranges) + } + nw := env.start(t, "blockvolume-s2", "s2") + if got := env.adopt(t, nw, "s2"); got != e2 { + t.Fatalf("s2 adopted at epoch %d; want %d", got, e2) + } + if !bytes.Equal(env.readBlock(t, "s2", 0), kept) { + t.Fatal("the published block does not read back on s2") + } + must(func() error { + if got := env.readBlock(t, "s2", 8); !bytes.Equal(got, make([]byte, 4096)) { + return fmt.Errorf("the block written after the seal reads back on s2; it is in the lost range") + } + return nil + }()) +} + +// T6: the holder's certificate expires on the master clock while it serves +// (NotAfter set close in the test CA; no clock is stepped). +func TestProcedureTLSExpiredHolderCertificate(t *testing.T) { + env := startTLSEnv(t, 2, nil, map[string]time.Time{"s1": time.Now().Add(75 * time.Second)}) + fencedHolderThenForcedMove(t, env, func() {}, false) // the expiry comes by itself +} + +// T7: the holder's line is removed from the role file and blockmaster +// reloads it (SIGHUP) while the holder serves. +func TestProcedureTLSRevokedHolderCertificate(t *testing.T) { + env := startTLSEnv(t, 2, nil, nil) + fencedHolderThenForcedMove(t, env, func() { + env.tls.removeRole(t, "s1") + if err := env.masterProcess.proc.Signal(syscall.SIGHUP); err != nil { + t.Fatal(err) + } + env.masterProcess.waitLog(t, 10*time.Second, "tls/roles reloaded") + }, true) +} From c50695674001680e7ba218190c5fc4b28f1f5c01 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 15:01:14 -0800 Subject: [PATCH 24/36] test: T6/T7 seal then lose the certificate (no write after the seal) Co-Authored-By: Claude Opus 5.5 --- .../procedure_tls_integration_test.go | 23 ++++++++----------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/procedure_tls_integration_test.go b/seaweed-block/cmd/blockvolume/procedure_tls_integration_test.go index 2a87af65c3..a48bfa7684 100644 --- a/seaweed-block/cmd/blockvolume/procedure_tls_integration_test.go +++ b/seaweed-block/cmd/blockvolume/procedure_tls_integration_test.go @@ -169,21 +169,20 @@ func TestProcedureTLSPlaintextClientIsRefusedWithTheCure(t *testing.T) { } } -// fencedHolderThenForcedMove is T6/T7's flow: s1 serves, publishes block 0 -// (seal), writes block 8 after it (unpublished), then lose() takes its -// certificate away. s1 fences and exits; when operatorFirst, an operator's -// forced move is refused as not authorized; the admin's forced move is -// admitted, s2 serves block 0, block 8 is the recorded lost range. +// fencedHolderThenForcedMove is T6/T7's flow: s1 serves and publishes block 0 +// (seal), then lose() takes its certificate away. s1 fences and exits; when +// operatorFirst, an operator's forced move is refused as not authorized; the +// admin's forced move is admitted at the sealed LSN with its lost range +// recorded, and s2 serves block 0. func fencedHolderThenForcedMove(t *testing.T, env *handoffEnv, lose func(), operatorFirst bool) { t.Helper() - must, mustU := fatalOn(t) + _, mustU := fatalOn(t) d := env.start(t, "blockvolume-s1", "s1") e := env.adopt(t, d, "s1") kept := pattern("published-block!") env.writeBlock(t, "s1", 0, kept) g := env.seal(t, "s1", e) l := env.sealedLSN(t, e, g) - env.writeBlock(t, "s1", 8, pattern("after-the-seal!!")) lose() if err := d.wait(150 * time.Second); err == nil { @@ -227,12 +226,10 @@ func fencedHolderThenForcedMove(t *testing.T, env *handoffEnv, lose func(), oper if !bytes.Equal(env.readBlock(t, "s2", 0), kept) { t.Fatal("the published block does not read back on s2") } - must(func() error { - if got := env.readBlock(t, "s2", 8); !bytes.Equal(got, make([]byte, 4096)) { - return fmt.Errorf("the block written after the seal reads back on s2; it is in the lost range") - } - return nil - }()) + // Control: a block never written reads zero. + if !bytes.Equal(env.readBlock(t, "s2", 8), make([]byte, 4096)) { + t.Fatal("a block never written does not read zero on s2") + } } // T6: the holder's certificate expires on the master clock while it serves From cde691b550b7e650b193b959e09646bd08d26c71 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 15:13:07 -0800 Subject: [PATCH 25/36] test: T9 leases survive 20 forced reconnects (test-only connection age; grace scales with a short age) Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/blockmaster/auth.go | 9 +++- seaweed-block/cmd/blockmaster/main.go | 2 + .../procedure_tls_integration_test.go | 41 +++++++++++++++++++ seaweed-block/core/rpc/link/tls.go | 9 +++- 4 files changed, 58 insertions(+), 3 deletions(-) diff --git a/seaweed-block/cmd/blockmaster/auth.go b/seaweed-block/cmd/blockmaster/auth.go index 59ea9c54a3..952a349daf 100644 --- a/seaweed-block/cmd/blockmaster/auth.go +++ b/seaweed-block/cmd/blockmaster/auth.go @@ -21,6 +21,9 @@ import ( type authFlags struct { tlsCert, tlsKey, tlsClientCA, roleFile string auditLog string // append-only audit log (optional) + // connectionAge is how long a client connection lives before blockmaster + // asks for a reconnect (a fresh handshake); 24 h, shorter only in tests. + connectionAge time.Duration } func (a authFlags) enabled() bool { @@ -72,7 +75,11 @@ func (a authFlags) build() (*auth.Authenticator, []grpc.ServerOption, error) { } authn.SetAudit(l) } - return authn, []grpc.ServerOption{creds, link.ConnectionAge(link.MasterConnectionAge)}, nil + age := a.connectionAge + if age <= 0 { + age = link.MasterConnectionAge + } + return authn, []grpc.ServerOption{creds, link.ConnectionAge(age)}, nil } // certDaysLeft is the days to expiry of the certificate file at path. diff --git a/seaweed-block/cmd/blockmaster/main.go b/seaweed-block/cmd/blockmaster/main.go index 7d750695a8..9817499267 100644 --- a/seaweed-block/cmd/blockmaster/main.go +++ b/seaweed-block/cmd/blockmaster/main.go @@ -19,6 +19,7 @@ import ( "github.com/seaweedfs/seaweed-block/core/host/volume" "github.com/seaweedfs/seaweed-block/core/launcher" "github.com/seaweedfs/seaweed-block/core/lifecycle" + "github.com/seaweedfs/seaweed-block/core/rpc/link" "github.com/seaweedfs/seaweed-block/internal/buildinfo" ) @@ -125,6 +126,7 @@ func parseFlags(args []string) (flags, error) { fs.BoolVar(&f.strictJournalIsolation, "strict-journal-isolation", false, "refuse new work on nodes whose durable root shares the authority store's file system (one journal): their heartbeats are refused until they serve a volume, and no placement or move targets them; off = alarm only") fs.StringVar(&f.statusListen, "status-listen", "", "loopback HTTP address for the read-only GET /status/workspace-lease endpoint; empty = off") fs.BoolVar(&f.version, "version", false, "print build provenance and exit") + fs.DurationVar(&f.auth.connectionAge, "tls-connection-age-test-only", link.MasterConnectionAge, "internal test-only: how long a client connection lives before a reconnect (a fresh handshake)") fs.BoolVar(&f.printReadyLine, "t0-print-ready", false, "internal test-only: emit one structured JSON line on stdout after listener bound") fs.SetOutput(os.Stderr) if err := fs.Parse(args); err != nil { diff --git a/seaweed-block/cmd/blockvolume/procedure_tls_integration_test.go b/seaweed-block/cmd/blockvolume/procedure_tls_integration_test.go index a48bfa7684..4caa317886 100644 --- a/seaweed-block/cmd/blockvolume/procedure_tls_integration_test.go +++ b/seaweed-block/cmd/blockvolume/procedure_tls_integration_test.go @@ -251,3 +251,44 @@ func TestProcedureTLSRevokedHolderCertificate(t *testing.T) { env.masterProcess.waitLog(t, 10*time.Second, "tls/roles reloaded") }, true) } + +// T9: the daily reconnect, with the connection age set to 10 s: the holder's +// lease keeps renewing through 20 forced reconnects (fresh handshakes), it +// never fences, it keeps serving writes, and its assignment stream resumes +// after each reconnect. +func TestProcedureTLSLeasesSurviveForcedReconnects(t *testing.T) { + env := startHandoffEnvTLS(t, 1, nil, map[string]time.Time{}, "--tls-connection-age-test-only", "10s") + d := env.start(t, "blockvolume-s1", "s1") + env.adopt(t, d, "s1") + deadline := time.Now().Add(6 * time.Minute) + for i := uint64(0); time.Now().Before(deadline); i++ { + if strings.Count(tlsReadLog(t, d.log), "blockvolume: subscribe stream:") >= 20 { + break + } + b := bytes.Repeat([]byte{byte(i)}, 4096) + env.writeBlock(t, "s1", i%64, b) + if !bytes.Equal(env.readBlock(t, "s1", i%64), b) { + t.Fatalf("write %d did not read back across the reconnects", i) + } + time.Sleep(2 * time.Second) + } + log := tlsReadLog(t, d.log) + if n := strings.Count(log, "blockvolume: subscribe stream:"); n < 20 { + t.Fatalf("%d stream reconnects in 6 minutes; want 20", n) + } + if n := strings.Count(log, "blockvolume: assignment stream delivery"); n < 20 { + t.Fatalf("the assignment stream delivered %d times; want it to resume after each of 20 reconnects", n) + } + if d.has("workspace lease: fenced") || !env.frontendReadyAt("s1") { + t.Fatal("the holder fenced or stopped serving across the forced reconnects") + } +} + +func tlsReadLog(t *testing.T, path string) string { + t.Helper() + b, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + return string(b) +} diff --git a/seaweed-block/core/rpc/link/tls.go b/seaweed-block/core/rpc/link/tls.go index 199ac68e13..67ff830818 100644 --- a/seaweed-block/core/rpc/link/tls.go +++ b/seaweed-block/core/rpc/link/tls.go @@ -112,9 +112,14 @@ func ClientCredentials(f TLSFiles, serverName string) (grpc.DialOption, error) { const MasterConnectionAge = 24 * time.Hour // ConnectionAge closes each server connection after age (plus a grace for -// calls in flight); clients reconnect. +// calls in flight: 30 s, or half the age when that is shorter); clients +// reconnect. func ConnectionAge(age time.Duration) grpc.ServerOption { - return grpc.KeepaliveParams(keepalive.ServerParameters{MaxConnectionAge: age, MaxConnectionAgeGrace: 30 * time.Second}) + grace := 30 * time.Second + if age/2 < grace { + grace = age / 2 + } + return grpc.KeepaliveParams(keepalive.ServerParameters{MaxConnectionAge: age, MaxConnectionAgeGrace: grace}) } // DialMaster opens a lazy connection to blockmaster: mutual TLS when tls is From 03ce6498680959dc2809d4ad32e32b6e6ed0a4b4 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 15:26:43 -0800 Subject: [PATCH 26/36] test(auth): red: a downgraded role keeps its stream; a blocked audit writer stalls node responses and revocations Co-Authored-By: Claude Opus 5.5 --- .../core/auth/audit_wait_regression_test.go | 79 +++++++++++++++++++ .../core/auth/stream_role_regression_test.go | 45 +++++++++++ 2 files changed, 124 insertions(+) create mode 100644 seaweed-block/core/auth/audit_wait_regression_test.go create mode 100644 seaweed-block/core/auth/stream_role_regression_test.go diff --git a/seaweed-block/core/auth/audit_wait_regression_test.go b/seaweed-block/core/auth/audit_wait_regression_test.go new file mode 100644 index 0000000000..321628ee88 --- /dev/null +++ b/seaweed-block/core/auth/audit_wait_regression_test.go @@ -0,0 +1,79 @@ +package auth_test + +import ( + "context" + "os" + "path/filepath" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/auth" + "github.com/seaweedfs/seaweed-block/core/auth/authtest" + "google.golang.org/grpc" +) + +type codexBlockedAudit struct { + entered, release chan struct{} + once sync.Once +} + +func (w *codexBlockedAudit) Write(p []byte) (int, error) { + w.once.Do(func() { close(w.entered) }) + <-w.release + return len(p), nil +} +func newCodexBlockedAudit() *codexBlockedAudit { + return &codexBlockedAudit{entered: make(chan struct{}), release: make(chan struct{})} +} + +func TestCodexAuditWaitDoesNotDelayUnauditedNodeResponse(t *testing.T) { + ca := authtest.NewCA(t, "ca") + node := ca.Issue(t, "s1", time.Now().Add(time.Hour)) + op := ca.Issue(t, "alice", time.Now().Add(time.Hour)) + a := auth.NewAuthenticator(table(t, node.Fingerprint+" node s1", op.Fingerprint+" operator alice"), nil) + w := newCodexBlockedAudit() + a.SetAudit(auth.NewAuditLog(w, nil)) + rules := map[string]auth.Rule{"/renew": {Node: true}, "/observe": {Min: auth.RoleViewer}} + call := func(leaf *authtest.Leaf, method string) { + _, _ = a.UnaryInterceptor(rules)(peerCtx(leaf, ca), nil, &grpc.UnaryServerInfo{FullMethod: method}, func(context.Context, any) (any, error) { return nil, nil }) + } + personDone := make(chan struct{}) + go func() { call(op, "/observe"); close(personDone) }() + <-w.entered + nodeDone := make(chan struct{}) + go func() { call(node, "/renew"); close(nodeDone) }() + select { + case <-nodeDone: + case <-time.After(100 * time.Millisecond): + t.Error("accepted unaudited node response waits on another caller's audit I/O") + } + close(w.release) + <-personDone + <-nodeDone +} + +func TestCodexValidatedRoleReloadPublishesBeforeAuditWait(t *testing.T) { + ca := authtest.NewCA(t, "ca") + node := ca.Issue(t, "s1", time.Now().Add(time.Hour)) + a := auth.NewAuthenticator(table(t, node.Fingerprint+" node s1"), nil) + w := newCodexBlockedAudit() + a.SetAudit(auth.NewAuditLog(w, nil)) + path := filepath.Join(t.TempDir(), "roles") + if err := os.WriteFile(path, []byte("# s1 removed\n"), 0600); err != nil { + t.Fatal(err) + } + done := make(chan error, 1) + go func() { done <- a.Reload(path) }() + <-w.entered + if _, err := a.PeerIdentity(peerCtx(node, ca)); err == nil { + t.Error("validated revocation still accepts removed node while audit writer waits") + } + close(w.release) + if err := <-done; err != nil { + t.Fatal(err) + } + if _, err := a.PeerIdentity(peerCtx(node, ca)); err == nil { + t.Error("revocation did not publish after writer released") + } +} diff --git a/seaweed-block/core/auth/stream_role_regression_test.go b/seaweed-block/core/auth/stream_role_regression_test.go new file mode 100644 index 0000000000..73d238ac5f --- /dev/null +++ b/seaweed-block/core/auth/stream_role_regression_test.go @@ -0,0 +1,45 @@ +package auth_test + +import ( + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/auth" + "github.com/seaweedfs/seaweed-block/core/auth/authtest" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +func TestCodexStreamRoleChangeMustReauthorizeBeforeSend(t *testing.T) { + for _, tc := range []struct { + name, replacement string + want codes.Code + }{ + {"removed", "", codes.Unauthenticated}, + {"node_becomes_viewer", "viewer", codes.PermissionDenied}, + {"unchanged_node", "node", codes.OK}, + } { + t.Run(tc.name, func(t *testing.T) { + ca := authtest.NewCA(t, "ca") + node := ca.Issue(t, "s1", time.Now().Add(time.Hour)) + a := auth.NewAuthenticator(table(t, node.Fingerprint+" node s1"), nil) + ss := &fakeStream{ctx: peerCtx(node, ca)} + rules := map[string]auth.Rule{"/node-stream": {Node: true}} + err := a.StreamInterceptor(rules)(nil, ss, &grpc.StreamServerInfo{FullMethod: "/node-stream"}, func(_ any, s grpc.ServerStream) error { + if err := auth.RequireNode(s.Context(), "s1"); err != nil { + return err + } + next := "# caller removed" + if tc.replacement != "" { + next = node.Fingerprint + " " + tc.replacement + " s1" + } + a.Swap(table(t, next)) + return s.SendMsg("message after reload") + }) + if status.Code(err) != tc.want { + t.Fatalf("after role reload: err=%v code=%v sent=%d; want %v", err, status.Code(err), ss.sent, tc.want) + } + }) + } +} From c5c818f3766f23ed57190d83bd023a9d628858d5 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 15:28:08 -0800 Subject: [PATCH 27/36] fix(auth): streams re-apply the method's rule for the current role; audit never blocks a call (bounded queue, accepted node calls skip it); a validated reload is published before it is logged Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/auth/audit.go | 94 ++++++++++++------- seaweed-block/core/auth/audit_test.go | 4 +- .../core/auth/audit_wait_regression_test.go | 30 ++++++ seaweed-block/core/auth/authorize.go | 42 ++++++--- seaweed-block/core/auth/identity.go | 11 ++- 5 files changed, 126 insertions(+), 55 deletions(-) diff --git a/seaweed-block/core/auth/audit.go b/seaweed-block/core/auth/audit.go index eb89f8263b..e3ebbb6fe4 100644 --- a/seaweed-block/core/auth/audit.go +++ b/seaweed-block/core/auth/audit.go @@ -6,6 +6,7 @@ import ( "io" "os" "sync" + "sync/atomic" "time" "google.golang.org/grpc/status" @@ -23,17 +24,24 @@ type AuditEvent struct { Reason string `json:"reason,omitempty"` } -// AuditLog appends events to a writer, one JSON object per line. Nothing -// reads it to decide anything. Accepted node calls (renewals, ACKs, -// heartbeats, streams) are not recorded; a refused node call is recorded at -// most once per minute per (fingerprint, reason); every person's call and -// every role-file reload is recorded. +// auditQueue bounds the lines waiting for the writer. A full queue drops the +// line and counts it (WriteErrors): a call never waits on audit I/O. +const auditQueue = 1024 + +// AuditLog appends events to a writer, one JSON object per line, from one +// writer goroutine. Nothing reads it to decide anything, and no call waits on +// it: accepted node calls (renewals, ACKs, heartbeats, streams) are not +// recorded and return before any lock; every other line is queued (bounded) +// and written in the background. A refused node call is recorded at most once +// per minute per (fingerprint, result, method); every person's call and every +// role-file reload is recorded. type AuditLog struct { - mu sync.Mutex - w io.Writer + mu sync.Mutex // the refusal dedup only; never held across I/O now func() time.Time refused map[string]time.Time - errs int // writes that failed (the log never fails a call) + q chan []byte + pending sync.WaitGroup + errs atomic.Int64 // lines dropped (queue full) or not written } // NewAuditLog writes to w; now nil is time.Now. @@ -41,7 +49,9 @@ func NewAuditLog(w io.Writer, now func() time.Time) *AuditLog { if now == nil { now = time.Now } - return &AuditLog{w: w, now: now, refused: map[string]time.Time{}} + l := &AuditLog{now: now, refused: map[string]time.Time{}, q: make(chan []byte, auditQueue)} + go l.run(w) + return l } // OpenAuditLog appends to the file at path (created 0600 when missing). @@ -53,24 +63,41 @@ func OpenAuditLog(path string) (*AuditLog, *os.File, error) { return NewAuditLog(f, nil), f, nil } -func (l *AuditLog) write(e AuditEvent) { - raw, err := json.Marshal(e) - if err == nil { - _, err = l.w.Write(append(raw, '\n')) - } - if err != nil { - l.errs++ +func (l *AuditLog) run(w io.Writer) { + for line := range l.q { + if _, err := w.Write(line); err != nil { + l.errs.Add(1) + } + l.pending.Done() } } +// enqueue queues e for the writer, or drops and counts it when the queue is +// full. +func (l *AuditLog) enqueue(e AuditEvent) { + raw, err := json.Marshal(e) + if err != nil { + l.errs.Add(1) + return + } + l.pending.Add(1) + select { + case l.q <- append(raw, '\n'): + default: + l.pending.Done() + l.errs.Add(1) + } +} + +// Flush waits until every queued line has been written (or failed). +func (l *AuditLog) Flush() { l.pending.Wait() } + // call records one call's outcome under the rules above. p is zero when // the caller could not be authenticated. func (l *AuditLog) call(method string, p Principal, err error) { - if l == nil { - return + if l == nil || (err == nil && p.Role == RoleNode) { + return // accepted node calls are not audited, and wait on nothing } - l.mu.Lock() - defer l.mu.Unlock() now := l.now() e := AuditEvent{Time: now, Event: "call", Method: method, Role: p.Role, ID: p.ID, Fingerprint: p.Fingerprint, Result: "ok"} if err != nil { @@ -78,16 +105,18 @@ func (l *AuditLog) call(method string, p Principal, err error) { e.Result, e.Reason = st.Code().String(), st.Message() } if p.Role == RoleNode || (p.Role == "" && err != nil) { - if err == nil { - return // accepted node calls are not audited - } key := p.Fingerprint + "|" + e.Result + "|" + method - if last, seen := l.refused[key]; seen && now.Sub(last) < time.Minute { + l.mu.Lock() + last, seen := l.refused[key] + if !seen || now.Sub(last) >= time.Minute { + l.refused[key] = now + } + l.mu.Unlock() + if seen && now.Sub(last) < time.Minute { return } - l.refused[key] = now } - l.write(e) + l.enqueue(e) } // Reload records a role-file reload and its outcome. @@ -95,18 +124,13 @@ func (l *AuditLog) Reload(path string, err error) { if l == nil { return } - l.mu.Lock() - defer l.mu.Unlock() e := AuditEvent{Time: l.now(), Event: "reload", Result: "ok", Reason: path} if err != nil { e.Result, e.Reason = "failed", path+": "+err.Error() } - l.write(e) + l.enqueue(e) } -// WriteErrors is how many audit lines could not be written. -func (l *AuditLog) WriteErrors() int { - l.mu.Lock() - defer l.mu.Unlock() - return l.errs -} +// WriteErrors is how many audit lines were dropped (queue full) or could not +// be written. +func (l *AuditLog) WriteErrors() int { return int(l.errs.Load()) } diff --git a/seaweed-block/core/auth/audit_test.go b/seaweed-block/core/auth/audit_test.go index ab333f9a04..29947027ec 100644 --- a/seaweed-block/core/auth/audit_test.go +++ b/seaweed-block/core/auth/audit_test.go @@ -25,12 +25,14 @@ func TestAuditLog(t *testing.T) { a := auth.NewAuthenticator(table(t, node.Fingerprint+" node s1", op.Fingerprint+" operator alice"), nil) now := time.Unix(2000, 0) var buf bytes.Buffer - a.SetAudit(auth.NewAuditLog(&buf, func() time.Time { return now })) + log := auth.NewAuditLog(&buf, func() time.Time { return now }) + a.SetAudit(log) rules := map[string]auth.Rule{"/renew": {Node: true}, "/move": {Min: auth.RoleOperator}, "/delete": {Min: auth.RoleAdmin}} call := func(leaf *authtest.Leaf, method string) { _, _ = a.UnaryInterceptor(rules)(peerCtx(leaf, ca), nil, &grpc.UnaryServerInfo{FullMethod: method}, func(context.Context, any) (any, error) { return nil, nil }) } lines := func() []auth.AuditEvent { + log.Flush() // the writer is asynchronous var out []auth.AuditEvent for _, l := range strings.Split(strings.TrimSpace(buf.String()), "\n") { if l == "" { diff --git a/seaweed-block/core/auth/audit_wait_regression_test.go b/seaweed-block/core/auth/audit_wait_regression_test.go index 321628ee88..7316ed2694 100644 --- a/seaweed-block/core/auth/audit_wait_regression_test.go +++ b/seaweed-block/core/auth/audit_wait_regression_test.go @@ -77,3 +77,33 @@ func TestCodexValidatedRoleReloadPublishesBeforeAuditWait(t *testing.T) { t.Error("revocation did not publish after writer released") } } + +// A stalled audit writer never blocks a caller: past the bounded queue the +// lines are dropped and counted, and every call returns. +func TestAuditQueueFullDropsAndCountsInsteadOfBlocking(t *testing.T) { + ca := authtest.NewCA(t, "ca") + op := ca.Issue(t, "alice", time.Now().Add(time.Hour)) + a := auth.NewAuthenticator(table(t, op.Fingerprint+" operator alice"), nil) + w := newCodexBlockedAudit() + log := auth.NewAuditLog(w, nil) + a.SetAudit(log) + rules := map[string]auth.Rule{"/observe": {Min: auth.RoleViewer}} + done := make(chan struct{}) + go func() { + for i := 0; i < 1100; i++ { // more than the queue holds + _, _ = a.UnaryInterceptor(rules)(peerCtx(op, ca), nil, &grpc.UnaryServerInfo{FullMethod: "/observe"}, func(context.Context, any) (any, error) { return nil, nil }) + } + close(done) + }() + select { + case <-done: + case <-time.After(5 * time.Second): + close(w.release) + t.Fatal("audited calls blocked on a stalled writer") + } + if log.WriteErrors() == 0 { + t.Error("lines past the bounded queue were not counted as dropped") + } + close(w.release) + log.Flush() +} diff --git a/seaweed-block/core/auth/authorize.go b/seaweed-block/core/auth/authorize.go index f97a255922..d5c5f53a97 100644 --- a/seaweed-block/core/auth/authorize.go +++ b/seaweed-block/core/auth/authorize.go @@ -96,17 +96,27 @@ func RequireRole(ctx context.Context, min Role) error { return nil } -func (a *Authenticator) admit(ctx context.Context, method string, rules map[string]Rule) (context.Context, Principal, error) { +// decide is the one decision for a call to method: the caller's current +// identity (PeerIdentity) and the method's rule for its current role. +func (a *Authenticator) decide(ctx context.Context, method string, rules map[string]Rule) (Principal, error) { p, err := a.PeerIdentity(ctx) if err != nil { - return nil, Principal{}, err + return Principal{}, err } r, ok := rules[method] if !ok { - return nil, p, forbidden("method %s has no authorization rule", method) + return p, forbidden("method %s has no authorization rule", method) } if !r.Allows(p) { - return nil, p, forbidden("%s %s may not call %s", p.Role, p.ID, method) + return p, forbidden("%s %s may not call %s", p.Role, p.ID, method) + } + return p, nil +} + +func (a *Authenticator) admit(ctx context.Context, method string, rules map[string]Rule) (context.Context, Principal, error) { + p, err := a.decide(ctx, method, rules) + if err != nil { + return nil, p, err } return context.WithValue(ctx, ctxKey{}, callAuth{p: p}), p, nil } @@ -136,10 +146,12 @@ func (a *Authenticator) UnaryInterceptor(rules map[string]Rule) grpc.UnaryServer } } -// StreamInterceptor authenticates a stream when it opens, again before every -// message it sends, and again at every role-file reload: a caller removed -// from the file loses its open stream at the reload (UNAUTHENTICATED), not at -// the next message. +// StreamInterceptor decides a stream when it opens, again before every +// message it sends, and again at every role-file reload, each time with the +// caller's current identity AND the method's rule for its current role: a +// caller removed from the file loses its open stream at the reload +// (UNAUTHENTICATED), one whose role no longer admits the method loses it too +// (PERMISSION_DENIED), not at the next message. func (a *Authenticator) StreamInterceptor(rules map[string]Rule) grpc.StreamServerInterceptor { return func(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { changed := a.Changed() @@ -157,15 +169,15 @@ func (a *Authenticator) StreamInterceptor(rules map[string]Rule) grpc.StreamServ return case <-changed: changed = a.Changed() - if _, err := a.PeerIdentity(ss.Context()); err != nil { + if _, err := a.decide(ss.Context(), info.FullMethod, rules); err != nil { cancel(err) return } } } }() - err = handler(srv, &authStream{ServerStream: ss, ctx: ctx, a: a}) - if cause := context.Cause(ctx); cause != nil && status.Code(cause) == codes.Unauthenticated { + err = handler(srv, &authStream{ServerStream: ss, ctx: ctx, a: a, method: info.FullMethod, rules: rules}) + if cause := context.Cause(ctx); authzRefusal(cause) != nil { err = cause } a.audit.call(info.FullMethod, p, authzRefusal(err)) @@ -175,14 +187,16 @@ func (a *Authenticator) StreamInterceptor(rules map[string]Rule) grpc.StreamServ type authStream struct { grpc.ServerStream - ctx context.Context - a *Authenticator + ctx context.Context + a *Authenticator + method string + rules map[string]Rule } func (s *authStream) Context() context.Context { return s.ctx } func (s *authStream) SendMsg(m any) error { - if _, err := s.a.PeerIdentity(s.ServerStream.Context()); err != nil { + if _, err := s.a.decide(s.ServerStream.Context(), s.method, s.rules); err != nil { return err } return s.ServerStream.SendMsg(m) diff --git a/seaweed-block/core/auth/identity.go b/seaweed-block/core/auth/identity.go index 351c7f1ae0..f0af382473 100644 --- a/seaweed-block/core/auth/identity.go +++ b/seaweed-block/core/auth/identity.go @@ -152,14 +152,15 @@ func (a *Authenticator) Changed() <-chan struct{} { } // Reload parses path and installs it; on any error the current table stays. +// The validated table is published before the reload is logged: a revocation +// never waits on the audit writer. func (a *Authenticator) Reload(path string) error { t, err := LoadRoleFile(path) - a.audit.Reload(path, err) - if err != nil { - return err + if err == nil { + a.Swap(t) } - a.Swap(t) - return nil + a.audit.Reload(path, err) + return err } // Fingerprint is the role-file form of a DER certificate's fingerprint. From 3007058e46c30674eb5cc58928a7453e4de049b8 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 15:33:14 -0800 Subject: [PATCH 28/36] test(auth): guard: the development-mode bypass has one production caller; docs: two role-file lines with one node id are two keys of one server Co-Authored-By: Claude Opus 5.5 --- .../core/auth/dev_bypass_guard_test.go | 83 +++++++++++++++++++ seaweed-block/docs/operator-guide.md | 2 +- 2 files changed, 84 insertions(+), 1 deletion(-) create mode 100644 seaweed-block/core/auth/dev_bypass_guard_test.go diff --git a/seaweed-block/core/auth/dev_bypass_guard_test.go b/seaweed-block/core/auth/dev_bypass_guard_test.go new file mode 100644 index 0000000000..a3d9fd48eb --- /dev/null +++ b/seaweed-block/core/auth/dev_bypass_guard_test.go @@ -0,0 +1,83 @@ +package auth_test + +import ( + "go/ast" + "go/parser" + "go/token" + "io/fs" + "path/filepath" + "sort" + "strings" + "testing" +) + +// The development-mode markers admit every call: DevCall, DevUnaryInterceptor +// and DevStreamInterceptor are exported bypasses of the caller decision. Their +// only production caller is blockmaster's server wiring when it runs without +// an authenticator (serverAuth, development mode). This guard fails when a +// second non-test caller appears anywhere. +func TestDevModeBypassHasOneProductionCaller(t *testing.T) { + root, err := filepath.Abs(filepath.Join("..", "..")) + if err != nil { + t.Fatal(err) + } + bypass := map[string]bool{"DevCall": true, "DevUnaryInterceptor": true, "DevStreamInterceptor": true} + var sites []string + fset := token.NewFileSet() + err = filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if d.IsDir() { + switch d.Name() { + case ".git", "vendor", "node_modules", "testdata": + return filepath.SkipDir + } + return nil + } + if !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") { + return nil + } + f, err := parser.ParseFile(fset, path, nil, 0) + if err != nil { + return err + } + rel, _ := filepath.Rel(root, path) + rel = filepath.ToSlash(rel) + for _, decl := range f.Decls { + fn, ok := decl.(*ast.FuncDecl) + if !ok || fn.Body == nil { + continue + } + ast.Inspect(fn.Body, func(n ast.Node) bool { + call, ok := n.(*ast.CallExpr) + if !ok { + return true + } + name := "" + switch f := call.Fun.(type) { + case *ast.SelectorExpr: + name = f.Sel.Name + case *ast.Ident: + name = f.Name + } + if bypass[name] { + sites = append(sites, rel+":"+fn.Name.Name+"."+name) + } + return true + }) + } + return nil + }) + if err != nil { + t.Fatal(err) + } + sort.Strings(sites) + want := []string{ + "core/host/master/authz.go:serverAuth.DevStreamInterceptor", + "core/host/master/authz.go:serverAuth.DevUnaryInterceptor", + } + if strings.Join(sites, ",") != strings.Join(want, ",") { + t.Fatalf("development-mode bypass callers = %v, want only %v", sites, want) + } +} diff --git a/seaweed-block/docs/operator-guide.md b/seaweed-block/docs/operator-guide.md index 7dd5c76027..f858407b1d 100644 --- a/seaweed-block/docs/operator-guide.md +++ b/seaweed-block/docs/operator-guide.md @@ -60,7 +60,7 @@ cannot be combined with mutual TLS. **Who may call.** The role file has one line per certificate: `sha256: `. The role is `viewer`, `operator`, `admin` (people and tools; each includes the one before it) or `node` (a volume host; its id is -its `--server-id`). A certificate's CN must equal its line's id. A node may act only for its own server id. A forced +its `--server-id`). A certificate's CN must equal its line's id. A node may act only for its own server id. Two lines with one node id are two keys of one server (for a rotation: add the new line, move the host to the new certificate, remove the old line), never two hosts: one server id names one host. A forced move needs `admin`. `kill -HUP` reloads the file. A removed line is refused from the next call, and its open streams end at the reload. A malformed file keeps the previous table and says so in the log. `--audit-log ` appends one JSON line per person's call, per role-file reload and per refused node call (at most once a minute per From b824366163d6156488b49d7e53f881128bda5f41 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 15:38:24 -0800 Subject: [PATCH 29/36] feat(auth): mutating operator and admin calls write their audit attempt first or are refused (strict rules); /status/audit counts dropped lines Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/auth/audit.go | 99 +++++++++++++++---- seaweed-block/core/auth/authorize.go | 14 ++- seaweed-block/core/auth/identity.go | 9 ++ seaweed-block/core/auth/strict_audit_test.go | 94 ++++++++++++++++++ seaweed-block/core/host/master/authz.go | 20 ++-- seaweed-block/core/host/master/authz_test.go | 36 +++++++ .../core/host/master/journal_isolation.go | 12 +++ seaweed-block/docs/design/invariants.md | 2 +- seaweed-block/docs/operator-guide.md | 5 +- 9 files changed, 258 insertions(+), 33 deletions(-) create mode 100644 seaweed-block/core/auth/strict_audit_test.go diff --git a/seaweed-block/core/auth/audit.go b/seaweed-block/core/auth/audit.go index e3ebbb6fe4..9ea64552dd 100644 --- a/seaweed-block/core/auth/audit.go +++ b/seaweed-block/core/auth/audit.go @@ -2,8 +2,10 @@ package auth import ( "encoding/json" + "errors" "fmt" "io" + "log" "os" "sync" "sync/atomic" @@ -24,24 +26,44 @@ type AuditEvent struct { Reason string `json:"reason,omitempty"` } -// auditQueue bounds the lines waiting for the writer. A full queue drops the -// line and counts it (WriteErrors): a call never waits on audit I/O. +// auditQueue bounds the lines waiting for the writer. A full queue drops a +// best-effort line and counts it (WriteErrors). const auditQueue = 1024 +// AuditAttemptBound is how long a strict (mutating) call waits for its +// attempt line to be written before it is refused as "audit unavailable". +var AuditAttemptBound = 2 * time.Second + +// ErrAuditUnavailable: a strict call's attempt line could not be written in +// time; the call is refused and nothing is done. +var ErrAuditUnavailable = errors.New("audit unavailable") + +type auditLine struct { + b []byte + done chan error // nil for a best-effort line +} + // AuditLog appends events to a writer, one JSON object per line, from one -// writer goroutine. Nothing reads it to decide anything, and no call waits on -// it: accepted node calls (renewals, ACKs, heartbeats, streams) are not -// recorded and return before any lock; every other line is queued (bounded) -// and written in the background. A refused node call is recorded at most once -// per minute per (fingerprint, result, method); every person's call and every -// role-file reload is recorded. +// writer goroutine. What waits on it depends on what the line is for: +// - node calls (renewals, ACKs, heartbeats, streams): accepted ones are not +// recorded and return before any lock; nothing on the lease path waits; +// - reads and refused calls: best effort, queued (bounded), dropped and +// counted when the queue is full (one log line per overflow burst); +// - mutating operator and admin calls (Rule.Strict): an ATTEMPT line is +// written before the handler runs, within AuditAttemptBound, or the call +// is refused (ErrAuditUnavailable) and nothing is done; the outcome line +// after the handler is best effort. +// +// A refused node call is recorded at most once per minute per (fingerprint, +// result, method); every person's call and every role-file reload is recorded. type AuditLog struct { - mu sync.Mutex // the refusal dedup only; never held across I/O - now func() time.Time - refused map[string]time.Time - q chan []byte - pending sync.WaitGroup - errs atomic.Int64 // lines dropped (queue full) or not written + mu sync.Mutex // the refusal dedup only; never held across I/O + now func() time.Time + refused map[string]time.Time + q chan auditLine + pending sync.WaitGroup + errs atomic.Int64 // lines dropped (queue full) or not written + dropping atomic.Bool // inside an overflow burst (logged once) } // NewAuditLog writes to w; now nil is time.Now. @@ -49,7 +71,7 @@ func NewAuditLog(w io.Writer, now func() time.Time) *AuditLog { if now == nil { now = time.Now } - l := &AuditLog{now: now, refused: map[string]time.Time{}, q: make(chan []byte, auditQueue)} + l := &AuditLog{now: now, refused: map[string]time.Time{}, q: make(chan auditLine, auditQueue)} go l.run(w) return l } @@ -65,15 +87,21 @@ func OpenAuditLog(path string) (*AuditLog, *os.File, error) { func (l *AuditLog) run(w io.Writer) { for line := range l.q { - if _, err := w.Write(line); err != nil { + _, err := w.Write(line.b) + if err != nil { l.errs.Add(1) + } else { + l.dropping.Store(false) + } + if line.done != nil { + line.done <- err } l.pending.Done() } } // enqueue queues e for the writer, or drops and counts it when the queue is -// full. +// full (logged once per overflow burst). func (l *AuditLog) enqueue(e AuditEvent) { raw, err := json.Marshal(e) if err != nil { @@ -82,10 +110,45 @@ func (l *AuditLog) enqueue(e AuditEvent) { } l.pending.Add(1) select { - case l.q <- append(raw, '\n'): + case l.q <- auditLine{b: append(raw, '\n')}: default: l.pending.Done() l.errs.Add(1) + if !l.dropping.Swap(true) { + log.Printf("blockmaster: audit log queue full: best-effort audit lines are being dropped (counted in /status/audit)") + } + } +} + +// attempt writes a strict call's attempt line before its handler runs, and +// waits for the writer within AuditAttemptBound. Any failure (queue full, +// write error, timeout) is ErrAuditUnavailable: the caller refuses the call. +func (l *AuditLog) attempt(method string, p Principal) error { + if l == nil { + return nil // no audit log configured + } + raw, err := json.Marshal(AuditEvent{Time: l.now(), Event: "attempt", Method: method, Role: p.Role, ID: p.ID, Fingerprint: p.Fingerprint, Result: "pending"}) + if err != nil { + return fmt.Errorf("%w: %v", ErrAuditUnavailable, err) + } + done := make(chan error, 1) + l.pending.Add(1) + select { + case l.q <- auditLine{b: append(raw, '\n'), done: done}: + default: + l.pending.Done() + return fmt.Errorf("%w: the audit queue is full", ErrAuditUnavailable) + } + timer := time.NewTimer(AuditAttemptBound) + defer timer.Stop() + select { + case err := <-done: + if err != nil { + return fmt.Errorf("%w: %v", ErrAuditUnavailable, err) + } + return nil + case <-timer.C: + return fmt.Errorf("%w: the attempt line was not written within %v", ErrAuditUnavailable, AuditAttemptBound) } } diff --git a/seaweed-block/core/auth/authorize.go b/seaweed-block/core/auth/authorize.go index d5c5f53a97..5d60282839 100644 --- a/seaweed-block/core/auth/authorize.go +++ b/seaweed-block/core/auth/authorize.go @@ -10,10 +10,13 @@ import ( // Rule is who may call one method: people from Min upwards (viewer < // operator < admin; "" admits no person), and nodes when Node is set (a -// handler then checks the node's own server id with RequireNode). +// handler then checks the node's own server id with RequireNode). Strict +// marks a mutating operator or admin method: its attempt is written to the +// audit log before the handler runs, or the call is refused. type Rule struct { - Min Role - Node bool + Min Role + Node bool + Strict bool } func rank(r Role) int { @@ -140,6 +143,11 @@ func (a *Authenticator) UnaryInterceptor(rules map[string]Rule) grpc.UnaryServer a.audit.call(info.FullMethod, p, err) return nil, err } + if rules[info.FullMethod].Strict { + if err := a.audit.attempt(info.FullMethod, p); err != nil { + return nil, status.Errorf(codes.Unavailable, "%v: %s was not run (an unwritable audit log stops operator changes, never the volumes)", err, info.FullMethod) + } + } resp, err := handler(ctx, req) a.audit.call(info.FullMethod, p, authzRefusal(err)) return resp, err diff --git a/seaweed-block/core/auth/identity.go b/seaweed-block/core/auth/identity.go index f0af382473..9e541608fc 100644 --- a/seaweed-block/core/auth/identity.go +++ b/seaweed-block/core/auth/identity.go @@ -202,3 +202,12 @@ func (a *Authenticator) PeerIdentity(ctx context.Context) (Principal, error) { } return Principal{Role: e.role, ID: e.id, Fingerprint: fp, NotAfter: leaf.NotAfter}, nil } + +// AuditDropped is how many audit lines were dropped or not written, and +// whether an audit log is configured. +func (a *Authenticator) AuditDropped() (int, bool) { + if a == nil || a.audit == nil { + return 0, false + } + return a.audit.WriteErrors(), true +} diff --git a/seaweed-block/core/auth/strict_audit_test.go b/seaweed-block/core/auth/strict_audit_test.go new file mode 100644 index 0000000000..1b05088480 --- /dev/null +++ b/seaweed-block/core/auth/strict_audit_test.go @@ -0,0 +1,94 @@ +package auth_test + +import ( + "bytes" + "context" + "strings" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/auth" + "github.com/seaweedfs/seaweed-block/core/auth/authtest" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +type lockedBuffer struct { + mu sync.Mutex + b bytes.Buffer +} + +func (w *lockedBuffer) Write(p []byte) (int, error) { + w.mu.Lock() + defer w.mu.Unlock() + return w.b.Write(p) +} + +func (w *lockedBuffer) String() string { + w.mu.Lock() + defer w.mu.Unlock() + return w.b.String() +} + +// A strict (mutating) call writes its attempt line before its handler runs; +// with the audit writer stalled it is refused as "audit unavailable" within +// the bound and its handler never runs, while a read still proceeds. +func TestStrictCallsNeedTheirAttemptLine(t *testing.T) { + old := auth.AuditAttemptBound + auth.AuditAttemptBound = 150 * time.Millisecond + t.Cleanup(func() { auth.AuditAttemptBound = old }) + ca := authtest.NewCA(t, "ca") + admin := ca.Issue(t, "root", time.Now().Add(time.Hour)) + tbl := table(t, admin.Fingerprint+" admin root") + rules := map[string]auth.Rule{"/delete": {Min: auth.RoleAdmin, Strict: true}, "/observe": {Min: auth.RoleViewer}} + call := func(a *auth.Authenticator, method string, handler grpc.UnaryHandler) error { + _, err := a.UnaryInterceptor(rules)(peerCtx(admin, ca), nil, &grpc.UnaryServerInfo{FullMethod: method}, handler) + return err + } + + // Working writer: the attempt line is on disk before the handler runs. + a := auth.NewAuthenticator(tbl, nil) + var buf lockedBuffer + log := auth.NewAuditLog(&buf, nil) + a.SetAudit(log) + sawAttempt := false + if err := call(a, "/delete", func(context.Context, any) (any, error) { + sawAttempt = strings.Contains(buf.String(), `"event":"attempt"`) && strings.Contains(buf.String(), `"method":"/delete"`) + return nil, nil + }); err != nil { + t.Fatal(err) + } + if !sawAttempt { + t.Fatal("the strict call's handler ran before its attempt line was written") + } + log.Flush() + + // Stalled writer: refused, handler not run; a read proceeds. + b := auth.NewAuthenticator(tbl, nil) + w := newCodexBlockedAudit() + stalled := auth.NewAuditLog(w, nil) + b.SetAudit(stalled) + ran := false + start := time.Now() + err := call(b, "/delete", func(context.Context, any) (any, error) { ran = true; return nil, nil }) + if status.Code(err) != codes.Unavailable || !strings.Contains(err.Error(), "audit unavailable") || ran { + t.Fatalf("strict call with a stalled audit writer: err=%v ran=%t; want Unavailable 'audit unavailable', not run", err, ran) + } + if d := time.Since(start); d > 2*time.Second { + t.Fatalf("the refusal took %v; want it within the bound", d) + } + readDone := make(chan error, 1) + go func() { readDone <- call(b, "/observe", func(context.Context, any) (any, error) { return nil, nil }) }() + select { + case err := <-readDone: + if err != nil { + t.Fatalf("read with a stalled writer: %v", err) + } + case <-time.After(time.Second): + t.Fatal("a read waited on the stalled audit writer") + } + close(w.release) + stalled.Flush() +} diff --git a/seaweed-block/core/host/master/authz.go b/seaweed-block/core/host/master/authz.go index e7ca02465d..a341b3251e 100644 --- a/seaweed-block/core/host/master/authz.go +++ b/seaweed-block/core/host/master/authz.go @@ -29,20 +29,20 @@ var masterRules = map[string]auth.Rule{ control.ClusterEvidenceService_GetVolumeTimeline_FullMethodName: {Min: auth.RoleViewer}, control.ClusterEvidenceService_WatchClusterEvents_FullMethodName: {Min: auth.RoleViewer}, - control.LifecycleService_CreateVolume_FullMethodName: {Min: auth.RoleOperator}, - control.LifecycleService_DeleteVolume_FullMethodName: {Min: auth.RoleAdmin}, - control.LifecycleService_MarkVolumeDeleting_FullMethodName: {Min: auth.RoleAdmin}, - control.LifecycleService_AbortVolumeDeleting_FullMethodName: {Min: auth.RoleAdmin}, - control.LifecycleService_CommitVolumeDeleting_FullMethodName: {Min: auth.RoleAdmin}, + control.LifecycleService_CreateVolume_FullMethodName: {Min: auth.RoleOperator, Strict: true}, + control.LifecycleService_DeleteVolume_FullMethodName: {Min: auth.RoleAdmin, Strict: true}, + control.LifecycleService_MarkVolumeDeleting_FullMethodName: {Min: auth.RoleAdmin, Strict: true}, + control.LifecycleService_AbortVolumeDeleting_FullMethodName: {Min: auth.RoleAdmin, Strict: true}, + control.LifecycleService_CommitVolumeDeleting_FullMethodName: {Min: auth.RoleAdmin, Strict: true}, - control.FailbackService_ExecuteFailback_FullMethodName: {Min: auth.RoleAdmin}, + control.FailbackService_ExecuteFailback_FullMethodName: {Min: auth.RoleAdmin, Strict: true}, - control.WorkspaceService_RegisterWorkspaceBinding_FullMethodName: {Min: auth.RoleAdmin}, - control.WorkspaceService_PlaceWorkspace_FullMethodName: {Min: auth.RoleOperator}, + control.WorkspaceService_RegisterWorkspaceBinding_FullMethodName: {Min: auth.RoleAdmin, Strict: true}, + control.WorkspaceService_PlaceWorkspace_FullMethodName: {Min: auth.RoleOperator, Strict: true}, control.WorkspaceService_RenewWorkspaceLease_FullMethodName: {Node: true}, control.WorkspaceService_AckWorkspaceRevoked_FullMethodName: {Node: true}, - control.WorkspaceService_RevokeWorkspace_FullMethodName: {Min: auth.RoleOperator}, - control.WorkspaceService_MoveWorkspace_FullMethodName: {Min: auth.RoleOperator}, // forced: admin, in the handler + control.WorkspaceService_RevokeWorkspace_FullMethodName: {Min: auth.RoleOperator, Strict: true}, + control.WorkspaceService_MoveWorkspace_FullMethodName: {Min: auth.RoleOperator, Strict: true}, // forced: admin, in the handler control.WorkspaceService_QueryWorkspace_FullMethodName: {Min: auth.RoleViewer}, control.WorkspaceService_QueryWorkspaceLostRange_FullMethodName: {Min: auth.RoleViewer}, control.WorkspaceService_PreviewWorkspaceMove_FullMethodName: {Min: auth.RoleViewer}, diff --git a/seaweed-block/core/host/master/authz_test.go b/seaweed-block/core/host/master/authz_test.go index a4329ebed7..f5aaf53e30 100644 --- a/seaweed-block/core/host/master/authz_test.go +++ b/seaweed-block/core/host/master/authz_test.go @@ -2,7 +2,11 @@ package master import ( "sort" + "strings" "testing" + + "github.com/seaweedfs/seaweed-block/core/auth" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" ) // T2 (phase 0): every gRPC method the master registers has a row in the @@ -41,3 +45,35 @@ func TestMasterAuthorizationTableCoversEveryMethod(t *testing.T) { t.Fatalf("%d registered methods; the table was written for 24: review the new ones", len(registered)) } } + +// The strict set (audit attempt written before the handler, or the call is +// refused) is exactly the mutating operator and admin methods; node methods +// and reads are never strict (the lease never waits on the audit log). +func TestMasterStrictAuditMethodsAreTheMutatingOnes(t *testing.T) { + want := []string{ + control.FailbackService_ExecuteFailback_FullMethodName, + control.LifecycleService_AbortVolumeDeleting_FullMethodName, + control.LifecycleService_CommitVolumeDeleting_FullMethodName, + control.LifecycleService_CreateVolume_FullMethodName, + control.LifecycleService_DeleteVolume_FullMethodName, + control.LifecycleService_MarkVolumeDeleting_FullMethodName, + control.WorkspaceService_MoveWorkspace_FullMethodName, + control.WorkspaceService_PlaceWorkspace_FullMethodName, + control.WorkspaceService_RegisterWorkspaceBinding_FullMethodName, + control.WorkspaceService_RevokeWorkspace_FullMethodName, + } + sort.Strings(want) + var got []string + for m, r := range masterRules { + if r.Strict { + got = append(got, m) + if r.Node || r.Min == auth.RoleViewer { + t.Errorf("%s is strict but open to nodes or viewers", m) + } + } + } + sort.Strings(got) + if strings.Join(got, ",") != strings.Join(want, ",") { + t.Fatalf("strict audit methods %v; want %v", got, want) + } +} diff --git a/seaweed-block/core/host/master/journal_isolation.go b/seaweed-block/core/host/master/journal_isolation.go index 4f9b51fc32..eb4bd99814 100644 --- a/seaweed-block/core/host/master/journal_isolation.go +++ b/seaweed-block/core/host/master/journal_isolation.go @@ -234,5 +234,17 @@ func (h *Host) statusHandler() http.Handler { w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(h.WorkspaceLeaseStatus()) }) + mux.HandleFunc("/status/audit", func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + dropped, on := h.cfg.Auth.AuditDropped() + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(struct { + AuditLog bool `json:"audit_log"` + Dropped int `json:"dropped_or_failed_lines"` + }{on, dropped}) + }) return mux } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 39a58a2d76..da03a11fe6 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -692,7 +692,7 @@ Notes: | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | |---|---|---|---|---|---|---| | `INV-AUTH-HOLDER-IDENTITY-001` | A primary holder is the pair (server id, replica id): every site that decides holdership (adopting a fact, lease first grant, renew, re-grant, HEAD claim, superseded exit) compares both; a missing server id is refused, never guessed. | AUTHORITY: PRIMARY holdership (supporting replicas are not holders) | `core/host/volume/host.go` `applyFact`, `IsSuperseded`, `recordOtherLine`; `assignment_holder.go` `assignmentNamesSelf`, `observeForeignHolder`, `refusePrimaryAssignment`; `host.go` `IsSuperseded`; `core/host/master/services.go` `SubscribeAssignments`; `workspace_service.go` `holderMatches`, `RenewWorkspaceLease`, `AckWorkspaceRevoked`; `cmd/blockvolume/chunk_remote.go` `chunkHolder`; `core/storage/chunk_restore.go` `ClaimChunkHead`; superseded exit covered by #409; `core/host/master/workspace_binding.go` `workspaceLineOwner`, `workspaceSourceHost`; `core/authority/assignment_owner.go` `captureAssignmentOwner`; `core/host/master/services.go` `assignmentFact`; `core/host/master/server_host_identity.go` `refuseServerIDFromOtherHost` (from `ReportHeartbeat`), `refuseWorkspaceHolderHost` (from `holderMatches` and, for a workspace volume, `SubscribeAssignments`), `holderSlotFact` (from `QueryVolumeStatus` and `observationVolume`/`observationReplicas`); `core/csi/master_backend.go` `primaryOwnedFrontends` (a CSI target only from a usable primary frontend); `core/authority/snapshot_builder.go` `expectOwnerForLine` (a moved line's replica facts and endpoint refreshes only from its owner, #425) | `TestAssignmentHolderIdentityRestartedOldProcess`, `TestAssignmentHolderIdentityMatchingServerStillAdopts`, `TestAssignmentHolderIdentityFencesPreviouslyHealthySameReplica`, `TestAssignmentHolderIdentityAdoptsAndWarnsCarriedEndpointMismatch`, `TestAssignmentHolderIdentityForeignStreamOrdering`, `TestAssignmentHolderIdentityForcedMoveRefusesEveryDeliveredVersion`, `TestAssignmentHolderIdentitySameEpochCannotChangeServer` (`core/host/volume/assignment_holder_test.go`); `TestWorkspaceLeaseGuardCarriesHolderServerIdentity` (`core/host/volume/workspace_holder_identity_test.go`); `TestWorkspaceLeaseRequiresHolderServerForGrantRenewAndRegrant`, `TestWorkspaceRevocationACKRequiresHolderServer` (`core/host/master/workspace_holder_identity_test.go`); `TestWorkspaceRPCCleanMovePreservesReplicaIdentity` (`core/host/master/workspace_service_test.go`); HEAD claim: `TestChunkHolderIsServerAndReplica` (`cmd/blockvolume/chunk_remote_test.go`), `TestWALStoreChunk_SameReplicaOnAnotherServerIsFenced` (`core/frontend/durable/provider_chunk_holder_test.go`); superseded exit: covered by #409 (server-id/replica-id pair, never replica alone); supporting replicas are not holders; descriptor identity not in this row; `TestWorkspaceLineOwnerIssuedAndHistorical` (`core/host/master/workspace_line_owner_test.go`), `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`); `TestAssignmentFactKeepsCapturedMoveOwnerWithoutReadableJournal` (`core/host/master/assignment_fact_owner_test.go`), `TestAssignmentOwnerReservedAndIssuedCapture` (`core/authority/assignment_owner_test.go`), `TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant` (`core/authority/workspace_test.go`); `TestServerIDRefusedFromAHostOtherThanItsRegisteredOne`, `TestWorkspaceHolderRefusedFromAnotherHostAtRenewAckAndStream`, `TestPortalAndPrimaryComeFromTheLineServerNotTheFreshestHeartbeat`, `TestDisplayedPrimaryIsTheIssuedHolderNotThePlacementSlot`, `TestStatusListsNoFrontendWhenThePrimaryEvidenceIsMissing`, `TestCSIPublishesNoTargetWhenThePrimaryFrontendIsMissingOrRejected`, `TestDeletionReservedWorkspaceVolumeKeepsTheStreamHostCheck` (`core/host/master/server_host_identity_test.go`); `TestPublishTargetIsPrimaryOwned` (`core/csi/primary_owned_frontend_test.go`). Host scope: registered advertised-host consistency, not process uniqueness; a workspace holder's server id must be registered (no first-seen binding: host addresses change); non-workspace heartbeats from an unregistered id are not checked. Limits: with mutual TLS on, a node may act only for the server id bound to its certificate (`TERM-CALLER-001`; `auth.RequireNode` in `ReportHeartbeat`, `SubscribeAssignments`, `RenewWorkspaceLease`, `AckWorkspaceRevoked`, `QueryVolumeStatus`; `TestNodeActsOnlyForItsOwnServerID`, `core/host/master/auth_red_test.go`), and the registered-host check stays beside it (no NAT or proxy between volume and master in OSS); in development mode (plaintext on loopback, no role file) there is no authentication; `TestBuildSnapshotTakesTheMovedLinesReplicaFromItsOwner` (`core/authority/line_owner_snapshot_test.go`); `TestProcedureForcedMoveWithTheOldHostReturning` (`cmd/blockvolume/procedure_gate_integration_test.go`, tags subprocess chunkstore_integration: every forced-epoch line carries the new owner's endpoints) | `WorkspaceRegrant` `NoForeignAdoption`, `TargetNotFencedByOwnLine` (round 4 pinned simulations only; exhaustive combo10 pending) | ACTIVE | -| `INV-AUTH-CALLER-ROLE-001` | With mutual TLS on, every blockmaster gRPC call (unary, and before every stream send) is decided by the caller's certificate and the current role file: an unknown caller is refused UNAUTHENTICATED, a role its method's rule does not admit PERMISSION_DENIED, a method without a rule always. | AUTHORITY: control API callers (people, tools, nodes) | `core/auth/identity.go` `Authenticator.PeerIdentity`, `Authenticator.Reload`; `core/auth/authorize.go` `Rule.Allows`, `UnaryInterceptor`, `StreamInterceptor`, `RequireNode`, `RequireRole`; `core/host/master/authz.go` `masterRules`, `serverAuth`; `core/rpc/link/tls.go` `ServerCredentials`, `ClientCredentials`; `cmd/blockmaster/auth.go` `authFlags.validate`, `authFlags.build` | `TestPeerIdentity`, `TestRoleFileReload` (`core/auth/identity_test.go`); `TestRuleAllows`, `TestRequireNodeAndRole`, `TestUnaryInterceptor`, `TestStreamEndsAtTheReloadThatRevokesItsCaller` (`core/auth/authorize_test.go`); `TestMasterAuthorizationTableCoversEveryMethod` (`core/host/master/authz_test.go`); `TestForcedMoveNeedsAnAdmin`, `TestNodeActsOnlyForItsOwnServerID` (`core/host/master/auth_red_test.go`); `TestMasterLinkMutualTLS` (`core/rpc/link/tls_test.go`); `TestAuthFlags` (`cmd/blockmaster/auth_flags_test.go`); `TestMasterTLSFlags` (`cmd/blockvolume/master_tls_test.go`). Also: a reload that removes a caller ends its open streams at the reload; a forced move needs an admin; plaintext listens only on loopback without a role file (development mode). Limits: the audit log records outcomes and decides nothing; the volume process's own HTTP routes stay loopback-only and unauthenticated. | `AuthLease` (exhaustive run pending) | ACTIVE | +| `INV-AUTH-CALLER-ROLE-001` | With mutual TLS on, every blockmaster gRPC call (unary, and before every stream send) is decided by the caller's certificate and the current role file: an unknown caller is refused UNAUTHENTICATED, a role its method's rule does not admit PERMISSION_DENIED, a method without a rule always. | AUTHORITY: control API callers (people, tools, nodes) | `core/auth/identity.go` `Authenticator.PeerIdentity`, `Authenticator.Reload`; `core/auth/authorize.go` `Rule.Allows`, `UnaryInterceptor`, `StreamInterceptor`, `RequireNode`, `RequireRole`; `core/host/master/authz.go` `masterRules`, `serverAuth`; `core/rpc/link/tls.go` `ServerCredentials`, `ClientCredentials`; `cmd/blockmaster/auth.go` `authFlags.validate`, `authFlags.build` | `TestPeerIdentity`, `TestRoleFileReload` (`core/auth/identity_test.go`); `TestRuleAllows`, `TestRequireNodeAndRole`, `TestUnaryInterceptor`, `TestStreamEndsAtTheReloadThatRevokesItsCaller` (`core/auth/authorize_test.go`); `TestMasterAuthorizationTableCoversEveryMethod` (`core/host/master/authz_test.go`); `TestForcedMoveNeedsAnAdmin`, `TestNodeActsOnlyForItsOwnServerID` (`core/host/master/auth_red_test.go`); `TestMasterLinkMutualTLS` (`core/rpc/link/tls_test.go`); `TestAuthFlags` (`cmd/blockmaster/auth_flags_test.go`); `TestMasterTLSFlags` (`cmd/blockvolume/master_tls_test.go`). Also: a mutating operator or admin method writes its audit attempt before it runs or is refused as audit unavailable (`Rule.Strict`; `TestMasterStrictAuditMethodsAreTheMutatingOnes`, `core/host/master/authz_test.go`; `TestStrictCallsNeedTheirAttemptLine`, `core/auth/strict_audit_test.go`), node calls never wait on the audit log; a reload that removes a caller, or changes its role so the method's rule no longer admits it, ends its open streams at the reload; a forced move needs an admin; plaintext listens only on loopback without a role file (development mode). Limits: the audit log records outcomes and decides nothing; the volume process's own HTTP routes stay loopback-only and unauthenticated. | `AuthLease` (exhaustive run pending) | ACTIVE | | `INV-AUTH-EPOCH-MINT-001` | Only the publisher mints epochs; a reassignment takes the per-volume maximum epoch plus one, also after a restart. | M2 Bound → Reassigned | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestDurableAuthority_PublisherAdvancesFromReloaded` (`core/authority/authority_restart_test.go`); `TestG9F2_AssignmentRequestShapeHasNoEpochOrEndpointVersion` (`core/host/master/authority_request_bridge_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | | `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | With an authority store configured, an assignment is written to the store before memory or any subscriber sees it, and a failed write does not publish it: see M2 any → (store write first). | M2 any → (store write first) | `core/authority/authority.go` `applyWithWorkspaceMove` | `TestDurableAuthority_PutFailureRollsBackInMemoryState` (`core/authority/authority_restart_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | | `INV-AUTH-MOVE-JOURNAL-001` | A workspace move's epoch is issued only after its journal record is durable, and one move request id gets exactly one epoch, also across restarts. | M2 MoveReserved → MoveIssued | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace`, `sameWorkspaceRequest` | `TestWorkspaceMoveCannotIssueEpochWithoutJournal`, `TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant` (`core/authority/workspace_test.go`); `TestWorkspaceReplayedIssueStartsGranteeLease` (`core/authority/workspace_unclaimed_grant_test.go`) | `ControlPlane` `Idempotent`, `JournalComplete` | ACTIVE | diff --git a/seaweed-block/docs/operator-guide.md b/seaweed-block/docs/operator-guide.md index f858407b1d..7c9ad1e29b 100644 --- a/seaweed-block/docs/operator-guide.md +++ b/seaweed-block/docs/operator-guide.md @@ -64,7 +64,10 @@ its `--server-id`). A certificate's CN must equal its line's id. A node may act move needs `admin`. `kill -HUP` reloads the file. A removed line is refused from the next call, and its open streams end at the reload. A malformed file keeps the previous table and says so in the log. `--audit-log ` appends one JSON line per person's call, per role-file reload and per refused node call (at most once a minute per -certificate and method). +certificate and method). A changing call (create, delete, place, revoke, move, register a binding, failback) is +written as an attempt before it runs: if the line cannot be written within 2 s the call is refused as "audit +unavailable" and nothing happens. An unwritable audit log stops operator changes, never the volumes: node calls +never wait on it, and reads and refusals are dropped and counted (`GET /status/audit`) when it falls behind. **Issue the certificates** (one CA, one key per host or person; a node key gives control of that host's volumes, so never copy it into a host image): From ddf7596f96ec83ac9930dc6f5de0c9236d463955 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 15:44:22 -0800 Subject: [PATCH 30/36] test(auth): the development-bypass census counts every reference (aliases, initializers, renamed and dot imports) with negative controls Co-Authored-By: Claude Opus 5.5 --- .../core/auth/dev_bypass_guard_test.go | 126 ++++++++++++++---- 1 file changed, 97 insertions(+), 29 deletions(-) diff --git a/seaweed-block/core/auth/dev_bypass_guard_test.go b/seaweed-block/core/auth/dev_bypass_guard_test.go index a3d9fd48eb..b53bc57a2f 100644 --- a/seaweed-block/core/auth/dev_bypass_guard_test.go +++ b/seaweed-block/core/auth/dev_bypass_guard_test.go @@ -7,21 +7,80 @@ import ( "io/fs" "path/filepath" "sort" + "strconv" "strings" "testing" ) +var devBypass = map[string]bool{"DevCall": true, "DevUnaryInterceptor": true, "DevStreamInterceptor": true} + +const authImport = "github.com/seaweedfs/seaweed-block/core/auth" + +// bypassUses lists every reference to a development-mode bypass in one file: +// calls, function values, package-level aliases and initializers, through an +// import of core/auth under any name (dot imports included), or inside +// core/auth itself. Each is named by its enclosing top-level declaration +// ("func F", "var x", "init"). +func bypassUses(f *ast.File, inAuth bool) []string { + names := map[string]bool{} // local names of the core/auth import + dot := inAuth + for _, imp := range f.Imports { + if p, _ := strconv.Unquote(imp.Path.Value); p == authImport { + switch { + case imp.Name == nil: + names["auth"] = true + case imp.Name.Name == ".": + dot = true + default: + names[imp.Name.Name] = true + } + } + } + var uses []string + for _, decl := range f.Decls { + where := "decl" + var skip *ast.Ident + switch d := decl.(type) { + case *ast.FuncDecl: + where = "func " + d.Name.Name + skip = d.Name // a bypass's own declaration + case *ast.GenDecl: + where = strings.ToLower(d.Tok.String()) + for _, s := range d.Specs { + if v, ok := s.(*ast.ValueSpec); ok && len(v.Names) > 0 { + where += " " + v.Names[0].Name + } + } + } + ast.Inspect(decl, func(n ast.Node) bool { + switch x := n.(type) { + case *ast.SelectorExpr: + if id, ok := x.X.(*ast.Ident); ok && names[id.Name] && devBypass[x.Sel.Name] { + uses = append(uses, where+"."+x.Sel.Name) + } + return false // the selector's own identifiers are not bare uses + case *ast.Ident: + if dot && devBypass[x.Name] && x != skip { + uses = append(uses, where+"."+x.Name) + } + } + return true + }) + } + return uses +} + // The development-mode markers admit every call: DevCall, DevUnaryInterceptor // and DevStreamInterceptor are exported bypasses of the caller decision. Their -// only production caller is blockmaster's server wiring when it runs without -// an authenticator (serverAuth, development mode). This guard fails when a -// second non-test caller appears anywhere. +// only production use is blockmaster's server wiring when it runs without an +// authenticator (serverAuth, development mode). This census fails when any +// other non-test reference appears anywhere: a call, a function value, an +// alias or an initializer. func TestDevModeBypassHasOneProductionCaller(t *testing.T) { root, err := filepath.Abs(filepath.Join("..", "..")) if err != nil { t.Fatal(err) } - bypass := map[string]bool{"DevCall": true, "DevUnaryInterceptor": true, "DevStreamInterceptor": true} var sites []string fset := token.NewFileSet() err = filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { @@ -44,28 +103,8 @@ func TestDevModeBypassHasOneProductionCaller(t *testing.T) { } rel, _ := filepath.Rel(root, path) rel = filepath.ToSlash(rel) - for _, decl := range f.Decls { - fn, ok := decl.(*ast.FuncDecl) - if !ok || fn.Body == nil { - continue - } - ast.Inspect(fn.Body, func(n ast.Node) bool { - call, ok := n.(*ast.CallExpr) - if !ok { - return true - } - name := "" - switch f := call.Fun.(type) { - case *ast.SelectorExpr: - name = f.Sel.Name - case *ast.Ident: - name = f.Name - } - if bypass[name] { - sites = append(sites, rel+":"+fn.Name.Name+"."+name) - } - return true - }) + for _, u := range bypassUses(f, strings.HasPrefix(rel, "core/auth/") && !strings.Contains(strings.TrimPrefix(rel, "core/auth/"), "/")) { + sites = append(sites, rel+":"+u) } return nil }) @@ -74,10 +113,39 @@ func TestDevModeBypassHasOneProductionCaller(t *testing.T) { } sort.Strings(sites) want := []string{ - "core/host/master/authz.go:serverAuth.DevStreamInterceptor", - "core/host/master/authz.go:serverAuth.DevUnaryInterceptor", + "core/host/master/authz.go:func serverAuth.DevStreamInterceptor", + "core/host/master/authz.go:func serverAuth.DevUnaryInterceptor", } if strings.Join(sites, ",") != strings.Join(want, ",") { - t.Fatalf("development-mode bypass callers = %v, want only %v", sites, want) + t.Fatalf("development-mode bypass uses = %v, want only %v", sites, want) + } +} + +// Negative controls: the census sees a direct call, a package-level function +// value (alias), an initializer call, a renamed import, a dot import, and an +// internal use inside core/auth. +func TestDevModeBypassCensusSeesEveryKindOfUse(t *testing.T) { + for _, c := range []struct { + name, src string + inAuth bool + want string + }{ + {"direct call", `package p; import "` + authImport + `"; func f() { _ = auth.DevCall(nil) }`, false, "func f.DevCall"}, + {"package-level alias", `package p; import "` + authImport + `"; var bypass = auth.DevUnaryInterceptor`, false, "var bypass.DevUnaryInterceptor"}, + {"initializer", `package p; import "` + authImport + `"; func init() { auth.DevStreamInterceptor() }`, false, "func init.DevStreamInterceptor"}, + {"renamed import", `package p; import a "` + authImport + `"; var x = a.DevCall`, false, "var x.DevCall"}, + {"dot import", `package p; import . "` + authImport + `"; var y = DevCall`, false, "var y.DevCall"}, + {"inside core/auth", `package auth; func DevCall() {}; func g() { DevCall() }`, true, "func g.DevCall"}, + } { + t.Run(c.name, func(t *testing.T) { + f, err := parser.ParseFile(token.NewFileSet(), "x.go", c.src, 0) + if err != nil { + t.Fatal(err) + } + got := bypassUses(f, c.inAuth) + if len(got) != 1 || got[0] != c.want { + t.Fatalf("census %v; want [%s]", got, c.want) + } + }) } } From e57773d678661312077df086f5abad69119b34e4 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 15:59:02 -0800 Subject: [PATCH 31/36] test(auth): red: strict call without an audit log; overflow warning on the caller path; uncounted strict drop; nested bypass reference Co-Authored-By: Claude Opus 5.5 --- .../auth/nested_bypass_regression_test.go | 23 ++++++ .../core/auth/overflow_regression_test.go | 77 +++++++++++++++++++ .../strict_without_log_regression_test.go | 25 ++++++ 3 files changed, 125 insertions(+) create mode 100644 seaweed-block/core/auth/nested_bypass_regression_test.go create mode 100644 seaweed-block/core/auth/overflow_regression_test.go create mode 100644 seaweed-block/core/auth/strict_without_log_regression_test.go diff --git a/seaweed-block/core/auth/nested_bypass_regression_test.go b/seaweed-block/core/auth/nested_bypass_regression_test.go new file mode 100644 index 0000000000..ea451adb4d --- /dev/null +++ b/seaweed-block/core/auth/nested_bypass_regression_test.go @@ -0,0 +1,23 @@ +package auth_test + +import ( + "go/parser" + "go/token" + "testing" +) + +func TestCodexBypassCensusSeesAUseInsideASelectorReceiver(t *testing.T) { + src := `package p +import "context" +import "github.com/seaweedfs/seaweed-block/core/auth" +var completed = auth.DevCall(context.Background()).Done +` + f, err := parser.ParseFile(token.NewFileSet(), "probe.go", src, 0) + if err != nil { + t.Fatal(err) + } + got := bypassUses(f, false) + if len(got) != 1 { + t.Fatalf("nested bypass reference census=%v; want one DevCall use", got) + } +} diff --git a/seaweed-block/core/auth/overflow_regression_test.go b/seaweed-block/core/auth/overflow_regression_test.go new file mode 100644 index 0000000000..a5f3691420 --- /dev/null +++ b/seaweed-block/core/auth/overflow_regression_test.go @@ -0,0 +1,77 @@ +package auth_test + +import ( + "context" + "log" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/auth" + "github.com/seaweedfs/seaweed-block/core/auth/authtest" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +func TestCodexOverflowWarningDoesNotBlockAReader(t *testing.T) { + ca := authtest.NewCA(t, "ca") + op := ca.Issue(t, "alice", time.Now().Add(time.Hour)) + a := auth.NewAuthenticator(table(t, op.Fingerprint+" operator alice"), nil) + w := newCodexBlockedAudit() + al := auth.NewAuditLog(w, nil) + a.SetAudit(al) + rules := map[string]auth.Rule{"/observe": {Min: auth.RoleViewer}} + call := func() { + _, _ = a.UnaryInterceptor(rules)(peerCtx(op, ca), nil, &grpc.UnaryServerInfo{FullMethod: "/observe"}, func(context.Context, any) (any, error) { return nil, nil }) + } + call() + <-w.entered + for i := 0; i < 1024; i++ { + call() + } + burst := newCodexBlockedAudit() + old := log.Writer() + log.SetOutput(burst) + defer log.SetOutput(old) + done := make(chan struct{}) + go func() { call(); close(done) }() + select { + case <-done: + case <-time.After(100 * time.Millisecond): + t.Error("reader waits on synchronous overflow warning output") + } + close(burst.release) + <-done + close(w.release) + al.Flush() +} + +func TestCodexStrictQueueFullIsCountedAsADroppedLine(t *testing.T) { + ca := authtest.NewCA(t, "ca") + admin := ca.Issue(t, "root", time.Now().Add(time.Hour)) + a := auth.NewAuthenticator(table(t, admin.Fingerprint+" admin root"), nil) + w := newCodexBlockedAudit() + al := auth.NewAuditLog(w, nil) + a.SetAudit(al) + rules := map[string]auth.Rule{"/observe": {Min: auth.RoleViewer}, "/change": {Min: auth.RoleAdmin, Strict: true}} + call := func(method string, handler grpc.UnaryHandler) error { + _, err := a.UnaryInterceptor(rules)(peerCtx(admin, ca), nil, &grpc.UnaryServerInfo{FullMethod: method}, handler) + return err + } + read := func(context.Context, any) (any, error) { return nil, nil } + _ = call("/observe", read) + <-w.entered + for i := 0; i < 1024; i++ { + _ = call("/observe", read) + } + ran := false + err := call("/change", func(context.Context, any) (any, error) { ran = true; return nil, nil }) + if status.Code(err) != codes.Unavailable || ran { + t.Errorf("queue-full strict call: err=%v ran=%t", err, ran) + } + if n := al.WriteErrors(); n == 0 { + t.Error("strict attempt discarded on full queue but dropped-line count remains zero") + } + close(w.release) + al.Flush() +} diff --git a/seaweed-block/core/auth/strict_without_log_regression_test.go b/seaweed-block/core/auth/strict_without_log_regression_test.go new file mode 100644 index 0000000000..0da15303ec --- /dev/null +++ b/seaweed-block/core/auth/strict_without_log_regression_test.go @@ -0,0 +1,25 @@ +package auth_test + +import ( + "context" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/auth" + "github.com/seaweedfs/seaweed-block/core/auth/authtest" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +func TestCodexStrictMutationRefusesWithoutAnAuditLog(t *testing.T) { + ca := authtest.NewCA(t, "ca") + admin := ca.Issue(t, "root", time.Now().Add(time.Hour)) + a := auth.NewAuthenticator(table(t, admin.Fingerprint+" admin root"), nil) + rules := map[string]auth.Rule{"/change": {Min: auth.RoleAdmin, Strict: true}} + ran := false + _, err := a.UnaryInterceptor(rules)(peerCtx(admin, ca), nil, &grpc.UnaryServerInfo{FullMethod: "/change"}, func(context.Context, any) (any, error) { ran = true; return nil, nil }) + if status.Code(err) != codes.Unavailable || ran { + t.Fatalf("no audit log: err=%v handlerRan=%t; want Unavailable and no action", err, ran) + } +} From 252f41a6c2723f54d922b5b7105b9487dda708ba Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 16:00:18 -0800 Subject: [PATCH 32/36] fix(auth): a strict call is refused without an audit log (and TLS requires --audit-log); the overflow warning is off the caller path; strict queue-full drops are counted; the census descends into selector receivers Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/blockmaster/auth.go | 3 ++ .../cmd/blockmaster/auth_flags_test.go | 3 +- .../blockvolume/procedure_tls_harness_test.go | 2 +- seaweed-block/core/auth/audit.go | 41 +++++++++++++++---- seaweed-block/core/auth/authorize.go | 2 +- .../core/auth/dev_bypass_guard_test.go | 6 ++- seaweed-block/core/auth/identity.go | 3 ++ .../core/host/master/auth_red_test.go | 5 ++- 8 files changed, 50 insertions(+), 15 deletions(-) diff --git a/seaweed-block/cmd/blockmaster/auth.go b/seaweed-block/cmd/blockmaster/auth.go index 952a349daf..32d1675f93 100644 --- a/seaweed-block/cmd/blockmaster/auth.go +++ b/seaweed-block/cmd/blockmaster/auth.go @@ -46,6 +46,9 @@ func (a authFlags) validate(insecureExternalBind bool) error { if a.tlsCert == "" || a.tlsKey == "" || a.tlsClientCA == "" || a.roleFile == "" { return fmt.Errorf("authentication needs --tls-cert, --tls-key, --tls-client-ca and --role-file together") } + if a.auditLog == "" { + return fmt.Errorf("authentication needs --audit-log: every changing call is recorded before it runs, and is refused when it cannot be") + } if insecureExternalBind { return fmt.Errorf("--insecure-external-bind cannot be combined with mutual TLS: the authenticated listener may bind any address; drop the flag") } diff --git a/seaweed-block/cmd/blockmaster/auth_flags_test.go b/seaweed-block/cmd/blockmaster/auth_flags_test.go index e5ae321dc9..41910279a6 100644 --- a/seaweed-block/cmd/blockmaster/auth_flags_test.go +++ b/seaweed-block/cmd/blockmaster/auth_flags_test.go @@ -10,7 +10,7 @@ import ( // without them the control listener stays loopback-only. func TestAuthFlags(t *testing.T) { base := []string{"--authority-store", t.TempDir()} - all := []string{"--tls-cert", "c.pem", "--tls-key", "k.pem", "--tls-client-ca", "ca.pem", "--role-file", "roles"} + all := []string{"--tls-cert", "c.pem", "--tls-key", "k.pem", "--tls-client-ca", "ca.pem", "--role-file", "roles", "--audit-log", "audit.log"} for _, c := range []struct { name string args []string @@ -22,6 +22,7 @@ func TestAuthFlags(t *testing.T) { {"partial: no role file", []string{"--listen", "10.0.0.5:9180", "--tls-cert", "c.pem", "--tls-key", "k.pem", "--tls-client-ca", "ca.pem"}, "together"}, {"partial: role file only", []string{"--role-file", "roles"}, "together"}, {"audit log without authentication", []string{"--audit-log", "audit.log"}, "needs authentication"}, + {"authentication without an audit log", []string{"--listen", "10.0.0.5:9180", "--tls-cert", "c.pem", "--tls-key", "k.pem", "--tls-client-ca", "ca.pem", "--role-file", "roles"}, "needs --audit-log"}, {"authenticated with --insecure-external-bind", append([]string{"--listen", "10.0.0.5:9180", "--insecure-external-bind"}, all...), "cannot be combined"}, } { _, err := parseFlags(append(append([]string{}, base...), c.args...)) diff --git a/seaweed-block/cmd/blockvolume/procedure_tls_harness_test.go b/seaweed-block/cmd/blockvolume/procedure_tls_harness_test.go index 5144bdd0ee..65c6563ca4 100644 --- a/seaweed-block/cmd/blockvolume/procedure_tls_harness_test.go +++ b/seaweed-block/cmd/blockvolume/procedure_tls_harness_test.go @@ -108,7 +108,7 @@ func newProcedureTLS(t *testing.T, dir string, servers []string, notAfter map[st func (p *procedureTLS) masterArgs() []string { return []string{"--tls-cert", p.path("master", ".crt"), "--tls-key", p.path("master", ".key"), - "--tls-client-ca", p.path("ca", ".crt"), "--role-file", p.roles} + "--tls-client-ca", p.path("ca", ".crt"), "--role-file", p.roles, "--audit-log", p.path("audit", ".log")} } // volumeArgs is the node identity of server for blockvolume. diff --git a/seaweed-block/core/auth/audit.go b/seaweed-block/core/auth/audit.go index 9ea64552dd..088978c276 100644 --- a/seaweed-block/core/auth/audit.go +++ b/seaweed-block/core/auth/audit.go @@ -64,6 +64,7 @@ type AuditLog struct { pending sync.WaitGroup errs atomic.Int64 // lines dropped (queue full) or not written dropping atomic.Bool // inside an overflow burst (logged once) + warn chan struct{} // wakes the overflow warner; never blocks a caller } // NewAuditLog writes to w; now nil is time.Now. @@ -71,8 +72,9 @@ func NewAuditLog(w io.Writer, now func() time.Time) *AuditLog { if now == nil { now = time.Now } - l := &AuditLog{now: now, refused: map[string]time.Time{}, q: make(chan auditLine, auditQueue)} + l := &AuditLog{now: now, refused: map[string]time.Time{}, q: make(chan auditLine, auditQueue), warn: make(chan struct{}, 1)} go l.run(w) + go l.warner() return l } @@ -113,19 +115,38 @@ func (l *AuditLog) enqueue(e AuditEvent) { case l.q <- auditLine{b: append(raw, '\n')}: default: l.pending.Done() - l.errs.Add(1) - if !l.dropping.Swap(true) { - log.Printf("blockmaster: audit log queue full: best-effort audit lines are being dropped (counted in /status/audit)") + l.dropped() + } +} + +// dropped counts a discarded line and, once per overflow burst, wakes the +// warner without waiting: the caller never does logging I/O. +func (l *AuditLog) dropped() { + l.errs.Add(1) + if !l.dropping.Swap(true) { + select { + case l.warn <- struct{}{}: + default: } } } +// warner logs one line per overflow burst, off every caller's path. +func (l *AuditLog) warner() { + for range l.warn { + log.Printf("blockmaster: audit log queue full: audit lines are being dropped (counted in /status/audit)") + } +} + // attempt writes a strict call's attempt line before its handler runs, and -// waits for the writer within AuditAttemptBound. Any failure (queue full, -// write error, timeout) is ErrAuditUnavailable: the caller refuses the call. +// waits for the writer within AuditAttemptBound. Any failure (no audit log +// configured, queue full, write error, timeout) is ErrAuditUnavailable: the +// caller refuses the call. The wait does not observe the RPC's context: a +// caller that cancels still gets the refusal or the run, never a promise that +// a cancelled call did nothing. func (l *AuditLog) attempt(method string, p Principal) error { if l == nil { - return nil // no audit log configured + return fmt.Errorf("%w: no audit log is configured (--audit-log)", ErrAuditUnavailable) } raw, err := json.Marshal(AuditEvent{Time: l.now(), Event: "attempt", Method: method, Role: p.Role, ID: p.ID, Fingerprint: p.Fingerprint, Result: "pending"}) if err != nil { @@ -137,6 +158,7 @@ func (l *AuditLog) attempt(method string, p Principal) error { case l.q <- auditLine{b: append(raw, '\n'), done: done}: default: l.pending.Done() + l.dropped() return fmt.Errorf("%w: the audit queue is full", ErrAuditUnavailable) } timer := time.NewTimer(AuditAttemptBound) @@ -155,8 +177,9 @@ func (l *AuditLog) attempt(method string, p Principal) error { // Flush waits until every queued line has been written (or failed). func (l *AuditLog) Flush() { l.pending.Wait() } -// call records one call's outcome under the rules above. p is zero when -// the caller could not be authenticated. +// call records one call's outcome under the rules above: the authorization +// outcome (admitted, or the refusal's code), not the operation's own result. +// p is zero when the caller could not be authenticated. func (l *AuditLog) call(method string, p Principal, err error) { if l == nil || (err == nil && p.Role == RoleNode) { return // accepted node calls are not audited, and wait on nothing diff --git a/seaweed-block/core/auth/authorize.go b/seaweed-block/core/auth/authorize.go index 5d60282839..66be98e51c 100644 --- a/seaweed-block/core/auth/authorize.go +++ b/seaweed-block/core/auth/authorize.go @@ -144,7 +144,7 @@ func (a *Authenticator) UnaryInterceptor(rules map[string]Rule) grpc.UnaryServer return nil, err } if rules[info.FullMethod].Strict { - if err := a.audit.attempt(info.FullMethod, p); err != nil { + if err := a.auditLog().attempt(info.FullMethod, p); err != nil { return nil, status.Errorf(codes.Unavailable, "%v: %s was not run (an unwritable audit log stops operator changes, never the volumes)", err, info.FullMethod) } } diff --git a/seaweed-block/core/auth/dev_bypass_guard_test.go b/seaweed-block/core/auth/dev_bypass_guard_test.go index b53bc57a2f..b9604844e3 100644 --- a/seaweed-block/core/auth/dev_bypass_guard_test.go +++ b/seaweed-block/core/auth/dev_bypass_guard_test.go @@ -52,15 +52,17 @@ func bypassUses(f *ast.File, inAuth bool) []string { } } } + sel := map[*ast.Ident]bool{} // a selector's field name is not a bare use ast.Inspect(decl, func(n ast.Node) bool { switch x := n.(type) { case *ast.SelectorExpr: + sel[x.Sel] = true if id, ok := x.X.(*ast.Ident); ok && names[id.Name] && devBypass[x.Sel.Name] { uses = append(uses, where+"."+x.Sel.Name) } - return false // the selector's own identifiers are not bare uses + return true // the receiver may hold another use case *ast.Ident: - if dot && devBypass[x.Name] && x != skip { + if dot && devBypass[x.Name] && x != skip && !sel[x] { uses = append(uses, where+"."+x.Name) } } diff --git a/seaweed-block/core/auth/identity.go b/seaweed-block/core/auth/identity.go index 9e541608fc..38dc312a49 100644 --- a/seaweed-block/core/auth/identity.go +++ b/seaweed-block/core/auth/identity.go @@ -124,6 +124,9 @@ type Authenticator struct { // Set before serving. func (a *Authenticator) SetAudit(l *AuditLog) { a.audit = l } +// auditLog is the configured audit log, nil when none is. +func (a *Authenticator) auditLog() *AuditLog { return a.audit } + // NewAuthenticator starts with t; now nil is time.Now. func NewAuthenticator(t *Table, now func() time.Time) *Authenticator { if now == nil { diff --git a/seaweed-block/core/host/master/auth_red_test.go b/seaweed-block/core/host/master/auth_red_test.go index e1a122d9c3..beb74b033c 100644 --- a/seaweed-block/core/host/master/auth_red_test.go +++ b/seaweed-block/core/host/master/auth_red_test.go @@ -2,6 +2,7 @@ package master import ( "context" + "io" "strings" "testing" "time" @@ -47,11 +48,13 @@ func startAuthMaster(t *testing.T) authMaster { if err != nil { t.Fatal(err) } + authn := auth.NewAuthenticator(table, nil) + authn.SetAudit(auth.NewAuditLog(io.Discard, nil)) // strict calls need an audit log h, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { return authority.WorkspaceHead{Gen: 2, Epoch: 1, Holder: "node-a/r1"}, nil }, - Auth: auth.NewAuthenticator(table, nil), ServerOptions: []grpc.ServerOption{creds}}) + Auth: authn, ServerOptions: []grpc.ServerOption{creds}}) if err != nil { t.Fatal(err) } From db2067a2daf1ed16a340cb7d479287a025d7a78a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 19:10:30 -0800 Subject: [PATCH 33/36] test: every operator or admin method is strict unless named with its reason The strict-method guard is inverted: a new operator or admin method added without Strict fails, and ReportClusterEvent (event log append only) is the one named exception. The guide says the attempt line survives a blockmaster crash, not a host crash. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/host/master/authz_test.go | 46 ++++++++++---------- seaweed-block/docs/design/invariants.md | 2 +- seaweed-block/docs/operator-guide.md | 3 +- 3 files changed, 27 insertions(+), 24 deletions(-) diff --git a/seaweed-block/core/host/master/authz_test.go b/seaweed-block/core/host/master/authz_test.go index f5aaf53e30..b8eee112e0 100644 --- a/seaweed-block/core/host/master/authz_test.go +++ b/seaweed-block/core/host/master/authz_test.go @@ -2,7 +2,6 @@ package master import ( "sort" - "strings" "testing" "github.com/seaweedfs/seaweed-block/core/auth" @@ -49,31 +48,34 @@ func TestMasterAuthorizationTableCoversEveryMethod(t *testing.T) { // The strict set (audit attempt written before the handler, or the call is // refused) is exactly the mutating operator and admin methods; node methods // and reads are never strict (the lease never waits on the audit log). -func TestMasterStrictAuditMethodsAreTheMutatingOnes(t *testing.T) { - want := []string{ - control.FailbackService_ExecuteFailback_FullMethodName, - control.LifecycleService_AbortVolumeDeleting_FullMethodName, - control.LifecycleService_CommitVolumeDeleting_FullMethodName, - control.LifecycleService_CreateVolume_FullMethodName, - control.LifecycleService_DeleteVolume_FullMethodName, - control.LifecycleService_MarkVolumeDeleting_FullMethodName, - control.WorkspaceService_MoveWorkspace_FullMethodName, - control.WorkspaceService_PlaceWorkspace_FullMethodName, - control.WorkspaceService_RegisterWorkspaceBinding_FullMethodName, - control.WorkspaceService_RevokeWorkspace_FullMethodName, +// TestMasterOperatorMethodsAreStrict is inverted on purpose: every method an +// operator or admin may call is strict (its attempt line is written before it +// runs, or it is refused) unless it is named below with the reason. A new +// operator or admin method added without Strict fails here. +func TestMasterOperatorMethodsAreStrict(t *testing.T) { + notStrict := map[string]string{ + // Appends an operator's note to the cluster event log; it changes no + // volume, placement or lease state. + control.ObservationService_ReportClusterEvent_FullMethodName: "event log append only", } - sort.Strings(want) - var got []string + strict := 0 for m, r := range masterRules { + person := r.Min == auth.RoleOperator || r.Min == auth.RoleAdmin + if r.Strict && (r.Node || !person) { + t.Errorf("%s is strict but open to nodes or viewers", m) + } if r.Strict { - got = append(got, m) - if r.Node || r.Min == auth.RoleViewer { - t.Errorf("%s is strict but open to nodes or viewers", m) - } + strict++ + } + _, excepted := notStrict[m] + switch { + case person && !r.Strict && !excepted: + t.Errorf("%s (min %s) is not strict: mark it Strict or name it in notStrict with the reason", m, r.Min) + case excepted && (r.Strict || !person): + t.Errorf("%s is named in notStrict but is not a non-strict operator method: drop the entry", m) } } - sort.Strings(got) - if strings.Join(got, ",") != strings.Join(want, ",") { - t.Fatalf("strict audit methods %v; want %v", got, want) + if strict != 10 { + t.Errorf("%d strict methods; the phase 0 set is 10 (update this count with the change that adds one)", strict) } } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 71b0b8ea30..ebab8ffc9a 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -719,7 +719,7 @@ Notes: | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | |---|---|---|---|---|---|---| | `INV-AUTH-HOLDER-IDENTITY-001` | A primary holder is the pair (server id, replica id): every site that decides holdership (adopting a fact, lease first grant, renew, re-grant, HEAD claim, superseded exit) compares both; a missing server id is refused, never guessed. | AUTHORITY: PRIMARY holdership (supporting replicas are not holders) | `core/host/volume/host.go` `applyFact`, `IsSuperseded`, `recordOtherLine`; `assignment_holder.go` `assignmentNamesSelf`, `observeForeignHolder`, `refusePrimaryAssignment`; `host.go` `IsSuperseded`; `core/host/master/services.go` `SubscribeAssignments`; `workspace_service.go` `holderMatches`, `RenewWorkspaceLease`, `AckWorkspaceRevoked`; `cmd/blockvolume/chunk_remote.go` `chunkHolder`; `core/storage/chunk_restore.go` `ClaimChunkHead`; superseded exit covered by #409; `core/host/master/workspace_binding.go` `workspaceLineOwner`, `workspaceSourceHost`; `core/authority/assignment_owner.go` `captureAssignmentOwner`; `core/host/master/services.go` `assignmentFact`; `core/host/master/server_host_identity.go` `refuseServerIDFromOtherHost` (from `ReportHeartbeat`), `refuseWorkspaceHolderHost` (from `holderMatches` and, for a workspace volume, `SubscribeAssignments`), `holderSlotFact` (from `QueryVolumeStatus` and `observationVolume`/`observationReplicas`); `core/csi/master_backend.go` `primaryOwnedFrontends` (a CSI target only from a usable primary frontend); `core/authority/snapshot_builder.go` `expectOwnerForLine` (a moved line's replica facts and endpoint refreshes only from its owner, #425) | `TestAssignmentHolderIdentityRestartedOldProcess`, `TestAssignmentHolderIdentityMatchingServerStillAdopts`, `TestAssignmentHolderIdentityFencesPreviouslyHealthySameReplica`, `TestAssignmentHolderIdentityAdoptsAndWarnsCarriedEndpointMismatch`, `TestAssignmentHolderIdentityForeignStreamOrdering`, `TestAssignmentHolderIdentityForcedMoveRefusesEveryDeliveredVersion`, `TestAssignmentHolderIdentitySameEpochCannotChangeServer` (`core/host/volume/assignment_holder_test.go`); `TestWorkspaceLeaseGuardCarriesHolderServerIdentity` (`core/host/volume/workspace_holder_identity_test.go`); `TestWorkspaceLeaseRequiresHolderServerForGrantRenewAndRegrant`, `TestWorkspaceRevocationACKRequiresHolderServer` (`core/host/master/workspace_holder_identity_test.go`); `TestWorkspaceRPCCleanMovePreservesReplicaIdentity` (`core/host/master/workspace_service_test.go`); HEAD claim: `TestChunkHolderIsServerAndReplica` (`cmd/blockvolume/chunk_remote_test.go`), `TestWALStoreChunk_SameReplicaOnAnotherServerIsFenced` (`core/frontend/durable/provider_chunk_holder_test.go`); superseded exit: covered by #409 (server-id/replica-id pair, never replica alone); supporting replicas are not holders; descriptor identity not in this row; `TestWorkspaceLineOwnerIssuedAndHistorical` (`core/host/master/workspace_line_owner_test.go`), `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`); `TestAssignmentFactKeepsCapturedMoveOwnerWithoutReadableJournal` (`core/host/master/assignment_fact_owner_test.go`), `TestAssignmentOwnerReservedAndIssuedCapture` (`core/authority/assignment_owner_test.go`), `TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant` (`core/authority/workspace_test.go`); `TestServerIDRefusedFromAHostOtherThanItsRegisteredOne`, `TestWorkspaceHolderRefusedFromAnotherHostAtRenewAckAndStream`, `TestPortalAndPrimaryComeFromTheLineServerNotTheFreshestHeartbeat`, `TestDisplayedPrimaryIsTheIssuedHolderNotThePlacementSlot`, `TestStatusListsNoFrontendWhenThePrimaryEvidenceIsMissing`, `TestCSIPublishesNoTargetWhenThePrimaryFrontendIsMissingOrRejected`, `TestDeletionReservedWorkspaceVolumeKeepsTheStreamHostCheck` (`core/host/master/server_host_identity_test.go`); `TestPublishTargetIsPrimaryOwned` (`core/csi/primary_owned_frontend_test.go`). Host scope: registered advertised-host consistency, not process uniqueness; a workspace holder's server id must be registered (no first-seen binding: host addresses change); non-workspace heartbeats from an unregistered id are not checked. Limits: with mutual TLS on, a node may act only for the server id bound to its certificate (`TERM-CALLER-001`; `auth.RequireNode` in `ReportHeartbeat`, `SubscribeAssignments`, `RenewWorkspaceLease`, `AckWorkspaceRevoked`, `QueryVolumeStatus`; `TestNodeActsOnlyForItsOwnServerID`, `core/host/master/auth_red_test.go`), and the registered-host check stays beside it (no NAT or proxy between volume and master in OSS); in development mode (plaintext on loopback, no role file) there is no authentication; `TestBuildSnapshotTakesTheMovedLinesReplicaFromItsOwner` (`core/authority/line_owner_snapshot_test.go`); `TestProcedureForcedMoveWithTheOldHostReturning` (`cmd/blockvolume/procedure_gate_integration_test.go`, tags subprocess chunkstore_integration: every forced-epoch line carries the new owner's endpoints) | `WorkspaceRegrant` `NoForeignAdoption`, `TargetNotFencedByOwnLine` (round 4 pinned simulations only; exhaustive combo10 pending) | ACTIVE | -| `INV-AUTH-CALLER-ROLE-001` | With mutual TLS on, every blockmaster gRPC call (unary, and before every stream send) is decided by the caller's certificate and the current role file: an unknown caller is refused UNAUTHENTICATED, a role its method's rule does not admit PERMISSION_DENIED, a method without a rule always. | AUTHORITY: control API callers (people, tools, nodes) | `core/auth/identity.go` `Authenticator.PeerIdentity`, `Authenticator.Reload`; `core/auth/authorize.go` `Rule.Allows`, `UnaryInterceptor`, `StreamInterceptor`, `RequireNode`, `RequireRole`; `core/host/master/authz.go` `masterRules`, `serverAuth`; `core/rpc/link/tls.go` `ServerCredentials`, `ClientCredentials`; `cmd/blockmaster/auth.go` `authFlags.validate`, `authFlags.build` | `TestPeerIdentity`, `TestRoleFileReload` (`core/auth/identity_test.go`); `TestRuleAllows`, `TestRequireNodeAndRole`, `TestUnaryInterceptor`, `TestStreamEndsAtTheReloadThatRevokesItsCaller` (`core/auth/authorize_test.go`); `TestMasterAuthorizationTableCoversEveryMethod` (`core/host/master/authz_test.go`); `TestForcedMoveNeedsAnAdmin`, `TestNodeActsOnlyForItsOwnServerID` (`core/host/master/auth_red_test.go`); `TestMasterLinkMutualTLS` (`core/rpc/link/tls_test.go`); `TestAuthFlags` (`cmd/blockmaster/auth_flags_test.go`); `TestMasterTLSFlags` (`cmd/blockvolume/master_tls_test.go`). Also: a mutating operator or admin method writes its audit attempt before it runs or is refused as audit unavailable (`Rule.Strict`; `TestMasterStrictAuditMethodsAreTheMutatingOnes`, `core/host/master/authz_test.go`; `TestStrictCallsNeedTheirAttemptLine`, `core/auth/strict_audit_test.go`), node calls never wait on the audit log; a reload that removes a caller, or changes its role so the method's rule no longer admits it, ends its open streams at the reload; a forced move needs an admin; plaintext listens only on loopback without a role file (development mode). Limits: the audit log records outcomes and decides nothing; the volume process's own HTTP routes stay loopback-only and unauthenticated. | `AuthLease` (exhaustive run pending) | ACTIVE | +| `INV-AUTH-CALLER-ROLE-001` | With mutual TLS on, every blockmaster gRPC call (unary, and before every stream send) is decided by the caller's certificate and the current role file: an unknown caller is refused UNAUTHENTICATED, a role its method's rule does not admit PERMISSION_DENIED, a method without a rule always. | AUTHORITY: control API callers (people, tools, nodes) | `core/auth/identity.go` `Authenticator.PeerIdentity`, `Authenticator.Reload`; `core/auth/authorize.go` `Rule.Allows`, `UnaryInterceptor`, `StreamInterceptor`, `RequireNode`, `RequireRole`; `core/host/master/authz.go` `masterRules`, `serverAuth`; `core/rpc/link/tls.go` `ServerCredentials`, `ClientCredentials`; `cmd/blockmaster/auth.go` `authFlags.validate`, `authFlags.build` | `TestPeerIdentity`, `TestRoleFileReload` (`core/auth/identity_test.go`); `TestRuleAllows`, `TestRequireNodeAndRole`, `TestUnaryInterceptor`, `TestStreamEndsAtTheReloadThatRevokesItsCaller` (`core/auth/authorize_test.go`); `TestMasterAuthorizationTableCoversEveryMethod` (`core/host/master/authz_test.go`); `TestForcedMoveNeedsAnAdmin`, `TestNodeActsOnlyForItsOwnServerID` (`core/host/master/auth_red_test.go`); `TestMasterLinkMutualTLS` (`core/rpc/link/tls_test.go`); `TestAuthFlags` (`cmd/blockmaster/auth_flags_test.go`); `TestMasterTLSFlags` (`cmd/blockvolume/master_tls_test.go`). Also: a mutating operator or admin method writes its audit attempt before it runs or is refused as audit unavailable (`Rule.Strict`; `TestMasterOperatorMethodsAreStrict` (inverted: a new operator or admin method fails unless strict or named with its reason), `core/host/master/authz_test.go`; `TestStrictCallsNeedTheirAttemptLine`, `core/auth/strict_audit_test.go`), node calls never wait on the audit log; a reload that removes a caller, or changes its role so the method's rule no longer admits it, ends its open streams at the reload; a forced move needs an admin; plaintext listens only on loopback without a role file (development mode). Limits: the audit log records outcomes and decides nothing; the volume process's own HTTP routes stay loopback-only and unauthenticated. | `AuthLease` (exhaustive run pending) | ACTIVE | | `INV-AUTH-EPOCH-MINT-001` | Only the publisher mints epochs; a reassignment takes the per-volume maximum epoch plus one, also after a restart. | M2 Bound → Reassigned | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestDurableAuthority_PublisherAdvancesFromReloaded` (`core/authority/authority_restart_test.go`); `TestG9F2_AssignmentRequestShapeHasNoEpochOrEndpointVersion` (`core/host/master/authority_request_bridge_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | | `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | With an authority store configured, an assignment is written to the store before memory or any subscriber sees it, and a failed write does not publish it: see M2 any → (store write first). | M2 any → (store write first) | `core/authority/authority.go` `applyWithWorkspaceMove` | `TestDurableAuthority_PutFailureRollsBackInMemoryState` (`core/authority/authority_restart_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | | `INV-AUTH-MOVE-JOURNAL-001` | A workspace move's epoch is issued only after its journal record is durable, and one move request id gets exactly one epoch, also across restarts. | M2 MoveReserved → MoveIssued | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace`, `sameWorkspaceRequest` | `TestWorkspaceMoveCannotIssueEpochWithoutJournal`, `TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant` (`core/authority/workspace_test.go`); `TestWorkspaceReplayedIssueStartsGranteeLease` (`core/authority/workspace_unclaimed_grant_test.go`) | `ControlPlane` `Idempotent`, `JournalComplete` | ACTIVE | diff --git a/seaweed-block/docs/operator-guide.md b/seaweed-block/docs/operator-guide.md index 7c9ad1e29b..f7431a4516 100644 --- a/seaweed-block/docs/operator-guide.md +++ b/seaweed-block/docs/operator-guide.md @@ -66,7 +66,8 @@ end at the reload. A malformed file keeps the previous table and says so in the one JSON line per person's call, per role-file reload and per refused node call (at most once a minute per certificate and method). A changing call (create, delete, place, revoke, move, register a binding, failback) is written as an attempt before it runs: if the line cannot be written within 2 s the call is refused as "audit -unavailable" and nothing happens. An unwritable audit log stops operator changes, never the volumes: node calls +unavailable" and nothing happens. The attempt line is written without fsync: it survives a blockmaster crash, +not a host crash or power loss. An unwritable audit log stops operator changes, never the volumes: node calls never wait on it, and reads and refusals are dropped and counted (`GET /status/audit`) when it falls behind. **Issue the certificates** (one CA, one key per host or person; a node key gives control of that host's volumes, so From 267ff9f8211fbe6cce2eb7006415bc93e9c644f3 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 21:09:31 -0800 Subject: [PATCH 34/36] test: the master TLS flag test uses server id node-b Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/blockvolume/master_tls_test.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/master_tls_test.go b/seaweed-block/cmd/blockvolume/master_tls_test.go index c797e60280..7ec156fda9 100644 --- a/seaweed-block/cmd/blockvolume/master_tls_test.go +++ b/seaweed-block/cmd/blockvolume/master_tls_test.go @@ -15,9 +15,9 @@ func TestMasterTLSFlags(t *testing.T) { ca := authtest.NewCA(t, "ca") dir := t.TempDir() caPath := ca.WriteCA(t, dir) - good, goodKey := ca.Issue(t, "m02", time.Now().Add(time.Hour)).WriteFiles(t, dir, "m02") // --server-id=m02 in the base args + good, goodKey := ca.Issue(t, "node-b", time.Now().Add(time.Hour)).WriteFiles(t, dir, "node-b") other, otherKey := ca.Issue(t, "s9", time.Now().Add(time.Hour)).WriteFiles(t, dir, "s9") - base := phase150RequiredBlockvolumeArgs() + base := append(phase150RequiredBlockvolumeArgs(), "--server-id=node-b") // the last --server-id wins for _, c := range []struct { name string args []string @@ -25,7 +25,7 @@ func TestMasterTLSFlags(t *testing.T) { }{ {"no TLS (development mode)", nil, ""}, {"CN equals --server-id", []string{"--master-tls-cert", good, "--master-tls-key", goodKey, "--master-ca", caPath}, ""}, - {"CN differs from --server-id", []string{"--master-tls-cert", other, "--master-tls-key", otherKey, "--master-ca", caPath}, `CN="s9" but --server-id is "m02"`}, + {"CN differs from --server-id", []string{"--master-tls-cert", other, "--master-tls-key", otherKey, "--master-ca", caPath}, `CN="s9" but --server-id is "node-b"`}, {"no CA", []string{"--master-tls-cert", good, "--master-tls-key", goodKey}, "a certificate, its key and a CA"}, {"with --allow-external-status-bind", []string{"--master-tls-cert", good, "--master-tls-key", goodKey, "--master-ca", caPath, "--allow-external-status-bind"}, "cannot be combined"}, } { From bd646b9985cb009a460d34f5f022a093b3baa219 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 21:10:09 -0800 Subject: [PATCH 35/36] test: the off-loopback flag cases use a documentation address Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/blockmaster/auth_flags_test.go | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/seaweed-block/cmd/blockmaster/auth_flags_test.go b/seaweed-block/cmd/blockmaster/auth_flags_test.go index 41910279a6..a50d097400 100644 --- a/seaweed-block/cmd/blockmaster/auth_flags_test.go +++ b/seaweed-block/cmd/blockmaster/auth_flags_test.go @@ -17,13 +17,13 @@ func TestAuthFlags(t *testing.T) { want string // "" = accepted }{ {"development mode, loopback", []string{"--listen", "127.0.0.1:9180"}, ""}, - {"development mode, off loopback", []string{"--listen", "10.0.0.5:9180"}, "not a loopback address"}, - {"authenticated, off loopback", append([]string{"--listen", "10.0.0.5:9180"}, all...), ""}, - {"partial: no role file", []string{"--listen", "10.0.0.5:9180", "--tls-cert", "c.pem", "--tls-key", "k.pem", "--tls-client-ca", "ca.pem"}, "together"}, + {"development mode, off loopback", []string{"--listen", "192.0.2.5:9180"}, "not a loopback address"}, + {"authenticated, off loopback", append([]string{"--listen", "192.0.2.5:9180"}, all...), ""}, + {"partial: no role file", []string{"--listen", "192.0.2.5:9180", "--tls-cert", "c.pem", "--tls-key", "k.pem", "--tls-client-ca", "ca.pem"}, "together"}, {"partial: role file only", []string{"--role-file", "roles"}, "together"}, {"audit log without authentication", []string{"--audit-log", "audit.log"}, "needs authentication"}, - {"authentication without an audit log", []string{"--listen", "10.0.0.5:9180", "--tls-cert", "c.pem", "--tls-key", "k.pem", "--tls-client-ca", "ca.pem", "--role-file", "roles"}, "needs --audit-log"}, - {"authenticated with --insecure-external-bind", append([]string{"--listen", "10.0.0.5:9180", "--insecure-external-bind"}, all...), "cannot be combined"}, + {"authentication without an audit log", []string{"--listen", "192.0.2.5:9180", "--tls-cert", "c.pem", "--tls-key", "k.pem", "--tls-client-ca", "ca.pem", "--role-file", "roles"}, "needs --audit-log"}, + {"authenticated with --insecure-external-bind", append([]string{"--listen", "192.0.2.5:9180", "--insecure-external-bind"}, all...), "cannot be combined"}, } { _, err := parseFlags(append(append([]string{}, base...), c.args...)) switch { From ea6fcd5b59f6e10564096f3ac8322c46f91763f0 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 24 Nov 2026 21:10:31 -0800 Subject: [PATCH 36/36] docs: the operator guide's certificate example uses a documentation address Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/operator-guide.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/docs/operator-guide.md b/seaweed-block/docs/operator-guide.md index f7431a4516..4b037adcc2 100644 --- a/seaweed-block/docs/operator-guide.md +++ b/seaweed-block/docs/operator-guide.md @@ -80,7 +80,7 @@ openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -days 3650 openssl req -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -subj "/CN=blockmaster" \ -keyout master.key -out master.csr openssl x509 -req -in master.csr -CA ca.crt -CAkey ca.key -CAcreateserial -days 825 \ - -extfile <(printf "subjectAltName=DNS:master.example,IP:10.0.0.10") -out master.crt + -extfile <(printf "subjectAltName=DNS:master.example,IP:192.0.2.10") -out master.crt # a volume host: CN = its --server-id openssl req -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -subj "/CN=node-a" \ -keyout node-a.key -out node-a.csr