Files
seaweedfs/weed/command/filer_backup_offset_test.go
T
a9fda6b50f filer clients: authenticate filer gRPC calls with per-call admin tokens (#13039)
* Add per-call filer authentication sources and pooled client wrappers

* Authenticate gateway filer calls with per-call admin tokens

* Authenticate shell admin and synchronization filer calls

* Authenticate workers MQ and remaining filer client paths

* Cache filer client signing keys and sign subscriptions with the shared key

Re-reading security.toml on every filer RPC cost about 125us against 8us for
signing. Keep the keys for up to a second, re-reading at once when a WEED_
override or the configuration directory changes. When the file exists but
cannot be read, keep the last keys read, else the startup keys, as
FilerAdminKeys does, so a process without a key stays tokenless. Metadata
subscriptions prefer the shared key, as filer peers do, because older filers
verify subscription admin tokens only with it.

* Authenticate admin-script, maintenance and filer.conf shell paths

Plugin worker admin scripts and master maintenance scripts build their own
shell options and carried no filer token source; fs.configure and
s3.bucket.quota.check read filer.conf without it.

* filer.cat: report a failed read; isolate key overrides in the admin-script test

filer.cat ignored the error from its filer call and exited successfully,
leaving a truncated -output file. Report the error and exit with failure.
The admin-script token test now clears the WEED_ signing-key overrides,
which take precedence over security.toml.

* security: refuse gRPC keys too short to sign; query engine uses client TLS

Under GODEBUG=fips140=only, hmac.New panics on keys under 14 bytes. The
startup check now covers jwt.filer_signing.grpc_key and grpc_previous_key,
and filer client token sources check the keys they read, so a reloaded or
per-endpoint security file with a short key is refused instead of
panicking when the next RPC signs.

The query engine's broker client dialed every master, filer and broker in
plaintext, so the admin token it now sends could cross the network in the
clear. It dials with the grpc.client TLS settings instead, and weed-sql
loads security.toml as weed-db does.

* security: per-endpoint admin tokens ignore WEED_ key overrides

FilerAdminTokenFromFile honored WEED_JWT_FILER_SIGNING_GRPC_KEY and
WEED_JWT_FILER_SIGNING_KEY. Those are process-wide, so filer.sync with
-a.security and -b.security signed both clusters' admin tokens with the
one key, handing each cluster a token valid on the other. A per-endpoint
file now supplies its own keys only.

* weed-sql, weed-db: refuse to start on an unreadable security.toml

Both only warned when security.toml was present but could not be read or
parsed. They then dialed without the grpc.client TLS settings while the
filer token source could still sign admin tokens from WEED_ environment
keys, so the tokens could travel in plaintext. They now exit with an
error that does not quote the file; a missing file is still fine.

* pb: take the filer token source in WithGrpcFilerClient and WithOneOfGrpcFilerClients

Fold WithGrpcFilerClientAuth and WithOneOfGrpcFilerClientsAuth into the
existing helpers instead of keeping two names for each. Callers without a
token source pass nil.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util: return the read error from ReadConfiguration

Fold ReadConfigurationWithError into ReadConfiguration. The error is
returned and not logged, since parser errors can quote values; the
existing reload callers already warn when no file was read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* security: keep the test-only filerAdminToken helper in the test

It had no production caller. The test helper now resolves keys through
filerClientKeysFrom, as the token sources do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util: read security.toml once in LoadSecurityConfigurationOrError

It validated the file, then merged it with a second read whose failure
was ignored and whose parser error was logged. It now merges with one
read and logs nothing from the parser. Viper's search also treats a
directory the process cannot search as holding no file; a candidate
that cannot be checked for lack of permission is now refused too.

* security: verify admin subscription tokens with the gRPC clock leeway

CheckGrpcMetadataSubscription checked admin tokens strictly, while unary
filer calls allow jwt.filer_signing.clock_leeway_seconds. With ten-second
client admin tokens, a subscriber whose clock trailed the filer's by more
than ten seconds was refused with a matching key. It now takes the leeway,
and the filer passes its configured one. The leeway check moves from the
server package to security.IsFilerAdminTokenWithLeeway so both use it.

* util: start without security.toml only when every candidate is confirmed absent

A candidate whose check fails for any reason other than not existing,
such as a symlink loop, is refused like one the process cannot search.

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:53:59 -08:00

172 lines
6.6 KiB
Go

package command
import (
"context"
"net"
"strings"
"sync"
"sync/atomic"
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
// kvFilerServer implements just the KV calls of the filer gRPC API over an
// in-memory map, mirroring the real server's behavior of returning an empty
// response, not an error, for a missing key.
type kvFilerServer struct {
filer_pb.UnimplementedSeaweedFilerServer
mu sync.Mutex
kv map[string][]byte
}
func (s *kvFilerServer) KvGet(_ context.Context, req *filer_pb.KvGetRequest) (*filer_pb.KvGetResponse, error) {
s.mu.Lock()
defer s.mu.Unlock()
return &filer_pb.KvGetResponse{Value: s.kv[string(req.Key)]}, nil
}
func (s *kvFilerServer) KvPut(_ context.Context, req *filer_pb.KvPutRequest) (*filer_pb.KvPutResponse, error) {
s.mu.Lock()
defer s.mu.Unlock()
s.kv[string(req.Key)] = req.Value
return &filer_pb.KvPutResponse{}, nil
}
type failingKvFilerServer struct {
filer_pb.UnimplementedSeaweedFilerServer
calls atomic.Int32
}
func (s *failingKvFilerServer) KvGet(context.Context, *filer_pb.KvGetRequest) (*filer_pb.KvGetResponse, error) {
if s.calls.Add(1) == 1 {
return &filer_pb.KvGetResponse{Error: "kv store unavailable"}, nil
}
return &filer_pb.KvGetResponse{}, nil
}
// a miss reads as ErrNotFound so the retried attempt skips the KEK retry loop
func (s *failingKvFilerServer) LookupDirectoryEntry(context.Context, *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) {
return &filer_pb.LookupDirectoryEntryResponse{}, nil
}
func startKvFiler(t *testing.T) (pb.ServerAddress, grpc.DialOption) {
return startFiler(t, &kvFilerServer{kv: map[string][]byte{}})
}
func startFiler(t *testing.T, server filer_pb.SeaweedFilerServer) (pb.ServerAddress, grpc.DialOption) {
t.Helper()
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen: %v", err)
}
grpcServer := grpc.NewServer()
filer_pb.RegisterSeaweedFilerServer(grpcServer, server)
go func() { _ = grpcServer.Serve(listener) }()
t.Cleanup(func() { grpcServer.Stop() })
grpcPort := listener.Addr().(*net.TCPAddr).Port
return pb.NewServerAddressWithGrpcPort("127.0.0.1:8888", grpcPort),
grpc.WithTransportCredentials(insecure.NewCredentials())
}
// An upgraded backup finds no destination-scoped checkpoint yet and must
// resume from the historical name+directory key; once its own key holds a
// value, the historical key — possibly still advanced by another backup that
// shared it — must no longer influence it.
func TestBackupOffset_HistoricalFallbackThenIndependence(t *testing.T) {
filerAddr, dial := startKvFiler(t)
s := &stubSink{name: "s3", dir: "/", destination: "endpoint-a|bucket-a|/"}
sinkId, legacySinkId := backupCheckpointIds("/", s, false)
// pre-upgrade state: only the shared historical checkpoint exists
if err := setOffset(dial, filerAddr, nil, BackupKeyPrefix, legacySinkId, 111); err != nil {
t.Fatalf("seed historical offset: %v", err)
}
got, err := getOffsetWithFallback(dial, filerAddr, nil, BackupKeyPrefix, sinkId, BackupKeyPrefix, legacySinkId)
if err != nil || got != 111 {
t.Fatalf("fallback read = (%d, %v), want (111, nil)", got, err)
}
// the backup checkpoints under its own key and prefers it from then on
if err := setOffset(dial, filerAddr, nil, BackupKeyPrefix, sinkId, 222); err != nil {
t.Fatalf("write destination-scoped offset: %v", err)
}
got, err = getOffsetWithFallback(dial, filerAddr, nil, BackupKeyPrefix, sinkId, BackupKeyPrefix, legacySinkId)
if err != nil || got != 222 {
t.Fatalf("destination-scoped read = (%d, %v), want (222, nil)", got, err)
}
// another backup advancing the historical key no longer moves this one
if err := setOffset(dial, filerAddr, nil, BackupKeyPrefix, legacySinkId, 333); err != nil {
t.Fatalf("advance historical offset: %v", err)
}
got, err = getOffsetWithFallback(dial, filerAddr, nil, BackupKeyPrefix, sinkId, BackupKeyPrefix, legacySinkId)
if err != nil || got != 222 {
t.Fatalf("read after historical advance = (%d, %v), want (222, nil)", got, err)
}
}
// The collision scenario from the report, over the real KV wire path: two
// backups whose configurations differ only in endpoint and bucket write
// their checkpoints without disturbing each other's.
func TestBackupOffset_DistinctDestinationsDoNotShare(t *testing.T) {
filerAddr, dial := startKvFiler(t)
idA, legacyA := backupCheckpointIds("/", &stubSink{name: "s3", dir: "/", destination: "s3.us-west-004.backblazeb2.com|seaweed-backup-a|/"}, false)
idB, legacyB := backupCheckpointIds("/", &stubSink{name: "s3", dir: "/", destination: "s3.us-east-005.backblazeb2.com|seaweed-backup-b|/"}, false)
if err := setOffset(dial, filerAddr, nil, BackupKeyPrefix, idA, 1000); err != nil {
t.Fatalf("write A: %v", err)
}
if err := setOffset(dial, filerAddr, nil, BackupKeyPrefix, idB, 2000); err != nil {
t.Fatalf("write B: %v", err)
}
if got, err := getOffsetWithFallback(dial, filerAddr, nil, BackupKeyPrefix, idA, BackupKeyPrefix, legacyA); err != nil || got != 1000 {
t.Fatalf("A reads (%d, %v), want (1000, nil)", got, err)
}
if got, err := getOffsetWithFallback(dial, filerAddr, nil, BackupKeyPrefix, idB, BackupKeyPrefix, legacyB); err != nil || got != 2000 {
t.Fatalf("B reads (%d, %v), want (2000, nil)", got, err)
}
}
func TestFilerBackup_OffsetReadFailureFailsAttempt(t *testing.T) {
server := &failingKvFilerServer{}
filerAddr, dial := startFiler(t, server)
config := util.GetViper()
config.Set("sink.local.enabled", true)
config.Set("sink.local.directory", t.TempDir())
t.Cleanup(func() {
config.Set("sink.local.enabled", false)
config.Set("sink.local.directory", "")
})
options := filerBackupOptions
address := string(filerAddr)
options.filer = &address
resumeTsNs, err := doFilerBackup(dial, &options, nil, nil, nil, 1, 1, 0)
if err == nil || !strings.Contains(err.Error(), "kv store unavailable") {
t.Fatalf("doFilerBackup error = %v, want the offset read failure", err)
}
if resumeTsNs != 0 {
t.Fatalf("resume position = %d, want 0", resumeTsNs)
}
// the next attempt re-reads the checkpoint and gets past it once the KV
// recovers, so it must fail later, not on the offset read
_, err = doFilerBackup(dial, &options, nil, nil, nil, 1, 2, resumeTsNs)
if err == nil || strings.Contains(err.Error(), "kv store unavailable") {
t.Fatalf("retried doFilerBackup error = %v, want a later-stage failure", err)
}
if got := server.calls.Load(); got < 2 {
t.Fatalf("checkpoint reads across attempts = %d, want a re-read", got)
}
}