From a9fda6b50f01e418c6db2eb9d77fc70ac850a85e Mon Sep 17 00:00:00 2001 From: Carlos Leyva <66577002+carlos-leyva-guerrero@users.noreply.github.com> Date: Sat, 28 Nov 2026 03:53:59 +0100 Subject: [PATCH] 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 * 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 * 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 * 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 Co-authored-by: Claude Opus 5.5 --- cmd/weed-db/dbcmd.go | 5 +- cmd/weed-sql/sqlcmd.go | 6 + weed/admin/dash/admin_server.go | 18 +- weed/admin/dash/client_management.go | 2 +- weed/admin/dash/filer_client_auth_test.go | 170 +++++ weed/admin/dash/mount_clients.go | 2 +- weed/cluster/lock_client.go | 10 +- weed/cluster/lock_client_test.go | 167 +++++ weed/command/filer_backup.go | 23 +- weed/command/filer_backup_auth_test.go | 113 +++ weed/command/filer_backup_offset_test.go | 20 +- weed/command/filer_cat.go | 6 +- weed/command/filer_copy.go | 15 +- weed/command/filer_meta_backup.go | 3 +- weed/command/filer_meta_scan.go | 19 +- weed/command/filer_meta_tail.go | 1 + weed/command/filer_remote_gateway.go | 17 +- weed/command/filer_remote_gateway_buckets.go | 9 +- weed/command/filer_remote_sync.go | 9 +- weed/command/filer_remote_sync_all.go | 2 +- weed/command/filer_remote_sync_dir.go | 22 +- weed/command/filer_sync.go | 50 +- weed/command/filer_sync_offset_test.go | 20 +- weed/command/filer_sync_verify.go | 17 +- weed/command/iam.go | 2 +- weed/command/mini.go | 4 +- weed/command/mount_common.go | 2 +- weed/command/s3.go | 2 +- weed/command/sftp.go | 2 +- weed/command/shell.go | 1 + weed/command/webdav.go | 2 +- .../filer_etc/filer_etc_policy_test.go | 65 ++ weed/credential/filer_etc/filer_etc_store.go | 3 +- weed/filer/filer_conf.go | 17 +- weed/filer/remote_mapping.go | 12 +- weed/filer/remote_mapping_auth_test.go | 87 +++ weed/filer/remote_storage.go | 11 +- weed/filer_client/filer_client_accessor.go | 8 +- weed/iam/integration/oidc_provider_audit.go | 3 +- weed/iam/integration/oidc_provider_store.go | 3 +- weed/iam/integration/role_store.go | 3 +- weed/iam/integration/session_revocation.go | 3 +- weed/iam/policy/policy_store.go | 3 +- weed/iamapi/iamapi_filer_auth_test.go | 121 ++++ weed/iamapi/iamapi_server.go | 13 +- weed/mount/sse_s3_reader.go | 2 +- weed/mount/weedfs.go | 2 +- weed/mq/broker/broker_filer_auth_test.go | 96 +++ weed/mq/broker/broker_server.go | 6 +- weed/mq/kafka/gateway/coordinator_registry.go | 3 + .../integration/seaweedmq_handler_utils.go | 1 + weed/pb/filer_client_auth_test.go | 315 +++++++++ weed/pb/filer_clients_auth_retry_test.go | 88 +++ weed/pb/filer_pb_tail.go | 20 +- weed/pb/grpc_client_server.go | 17 +- weed/plugin/worker/admin_script_handler.go | 10 +- .../worker/admin_script_handler_test.go | 36 + weed/query/engine/broker_client.go | 13 +- weed/query/engine/broker_client_auth_test.go | 86 +++ weed/remote_storage/track_sync_offset.go | 16 +- weed/replication/replicator.go | 11 +- .../replication/sink/filersink/fetch_write.go | 6 +- .../sink/filersink/filer_auth_test.go | 196 ++++++ weed/replication/sink/filersink/filer_sink.go | 7 + weed/replication/source/filer_source.go | 28 +- weed/s3api/bucket_size_metrics.go | 4 +- weed/s3api/s3_sse_s3.go | 3 +- weed/s3api/s3api_bucket_handlers.go | 3 +- weed/s3api/s3api_circuit_breaker.go | 3 +- weed/s3api/s3api_directory_marker.go | 3 +- weed/s3api/s3api_filer_auth_test.go | 321 +++++++++ weed/s3api/s3api_handlers.go | 6 +- weed/s3api/s3api_object_handlers.go | 2 +- weed/s3api/s3api_object_handlers_put.go | 2 +- weed/s3api/s3api_object_routed_read.go | 3 +- weed/s3api/s3api_object_routed_upload.go | 3 +- weed/s3api/s3api_object_routed_write.go | 7 +- weed/s3api/s3api_server.go | 8 +- weed/security/filer_client_auth.go | 246 +++++++ weed/security/filer_client_auth_test.go | 654 ++++++++++++++++++ weed/security/grpc_peer.go | 18 +- weed/security/guard.go | 2 +- weed/security/jwt_previous_key_test.go | 4 +- weed/security/metadata_subscribe.go | 7 +- weed/security/metadata_subscribe_test.go | 30 +- weed/server/filer_client_auth_test.go | 186 +++++ weed/server/filer_grpc_scope.go | 21 +- ...ler_grpc_scope_subscription_compat_test.go | 2 + .../filer_grpc_server_sub_meta_scope.go | 11 +- weed/server/filer_server.go | 4 +- weed/server/master_server.go | 1 + weed/server/webdav_client_auth_test.go | 58 ++ weed/server/webdav_server.go | 6 +- weed/sftpd/sftp_filer.go | 2 +- weed/sftpd/sftp_filer_test.go | 66 +- weed/shell/command_cluster_check.go | 6 +- weed/shell/command_cluster_ps.go | 4 +- weed/shell/command_fs_configure.go | 2 +- weed/shell/command_fs_meta_token_test.go | 2 +- weed/shell/command_fs_verify.go | 1 + weed/shell/command_mq_topic_compact.go | 1 + weed/shell/command_remote_meta_sync.go | 2 +- weed/shell/command_remote_mount.go | 8 +- weed/shell/command_remote_mount_buckets.go | 2 +- weed/shell/command_remote_uncache.go | 2 +- weed/shell/command_remote_unmount.go | 4 +- weed/shell/command_s3_bucket_quota_check.go | 2 +- weed/shell/command_s3_clean_uploads.go | 1 + weed/shell/commands.go | 25 +- weed/shell/filer_client_auth_test.go | 181 +++++ weed/shell/s3tables_helpers.go | 7 +- weed/util/config.go | 68 +- weed/util/config_test.go | 96 ++- weed/util/fips140_keys.go | 2 + weed/wdclient/filer_client.go | 12 +- weed/worker/tasks/iceberg/handler.go | 7 +- .../tasks/iceberg/handler_filer_auth_test.go | 94 +++ weed/worker/tasks/s3_lifecycle/handler.go | 18 +- .../s3_lifecycle/handler_filer_auth_test.go | 92 +++ 119 files changed, 4087 insertions(+), 290 deletions(-) create mode 100644 weed/admin/dash/filer_client_auth_test.go create mode 100644 weed/command/filer_backup_auth_test.go create mode 100644 weed/filer/remote_mapping_auth_test.go create mode 100644 weed/iamapi/iamapi_filer_auth_test.go create mode 100644 weed/mq/broker/broker_filer_auth_test.go create mode 100644 weed/pb/filer_client_auth_test.go create mode 100644 weed/pb/filer_clients_auth_retry_test.go create mode 100644 weed/query/engine/broker_client_auth_test.go create mode 100644 weed/replication/sink/filersink/filer_auth_test.go create mode 100644 weed/s3api/s3api_filer_auth_test.go create mode 100644 weed/security/filer_client_auth.go create mode 100644 weed/security/filer_client_auth_test.go create mode 100644 weed/server/filer_client_auth_test.go create mode 100644 weed/server/webdav_client_auth_test.go create mode 100644 weed/shell/filer_client_auth_test.go create mode 100644 weed/worker/tasks/iceberg/handler_filer_auth_test.go create mode 100644 weed/worker/tasks/s3_lifecycle/handler_filer_auth_test.go diff --git a/cmd/weed-db/dbcmd.go b/cmd/weed-db/dbcmd.go index 05fa18c5b9..86fb4198d0 100644 --- a/cmd/weed-db/dbcmd.go +++ b/cmd/weed-db/dbcmd.go @@ -169,7 +169,10 @@ func Run(args []string) int { } func runWithOptions(opts *Options) bool { - util.LoadConfiguration("security", false) + if err := util.LoadSecurityConfigurationOrError(); err != nil { + fmt.Fprintf(os.Stderr, "Error: %v\n", err) + return false + } // Validate options. if opts.MasterAddr == "" { diff --git a/cmd/weed-sql/sqlcmd.go b/cmd/weed-sql/sqlcmd.go index c25b6501f7..e5e2e5969f 100644 --- a/cmd/weed-sql/sqlcmd.go +++ b/cmd/weed-sql/sqlcmd.go @@ -13,6 +13,7 @@ import ( "github.com/peterh/liner" "github.com/seaweedfs/seaweedfs/weed/query/engine" + "github.com/seaweedfs/seaweedfs/weed/util" flag "github.com/seaweedfs/seaweedfs/weed/util/fla9" "github.com/seaweedfs/seaweedfs/weed/util/grace" "github.com/seaweedfs/seaweedfs/weed/util/sqlutil" @@ -106,6 +107,11 @@ func Run(args []string) int { } func runWithOptions(opts *Options) bool { + if err := util.LoadSecurityConfigurationOrError(); err != nil { + fmt.Fprintf(os.Stderr, "Error: %v\n", err) + return false + } + // Initialize SQL engine with master address for service discovery. sqlEngine := engine.NewSQLEngine(opts.Master) diff --git a/weed/admin/dash/admin_server.go b/weed/admin/dash/admin_server.go index d6ea2d63d9..47bab1d3d1 100644 --- a/weed/admin/dash/admin_server.go +++ b/weed/admin/dash/admin_server.go @@ -113,14 +113,15 @@ func getCollectionName(filerGroup, bucketName string) string { } type AdminServer struct { - masterClient *wdclient.MasterClient - templateFS http.FileSystem - dataDir string - filerGroup string - grpcDialOption grpc.DialOption - cacheExpiration time.Duration - lastCacheUpdate time.Time - cachedTopology *ClusterTopology + masterClient *wdclient.MasterClient + templateFS http.FileSystem + dataDir string + filerGroup string + grpcDialOption grpc.DialOption + filerTokenSource security.FilerTokenSource + cacheExpiration time.Duration + lastCacheUpdate time.Time + cachedTopology *ClusterTopology // dashSamples is a bounded in-memory ring of recent cluster snapshots that // powers the dashboard's at-a-glance sparklines (see dashboard_metrics.go), @@ -215,6 +216,7 @@ func NewAdminServer(masters string, filerGroup string, templateFS http.FileSyste dataDir: dataDir, filerGroup: filerGroup, grpcDialOption: grpcDialOption, + filerTokenSource: security.FilerAdminToken, cacheExpiration: defaultCacheTimeout, filerCacheExpiration: defaultFilerCacheTimeout, configPersistence: NewConfigPersistence(dataDir), diff --git a/weed/admin/dash/client_management.go b/weed/admin/dash/client_management.go index 6de7d1901b..24645668c4 100644 --- a/weed/admin/dash/client_management.go +++ b/weed/admin/dash/client_management.go @@ -30,7 +30,7 @@ func (s *AdminServer) WithFilerClient(f func(client filer_pb.SeaweedFilerClient) return fmt.Errorf("no filer available") } - return pb.WithGrpcFilerClient(false, 0, pb.ServerAddress(filerAddr), s.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + return pb.WithGrpcFilerClient(false, 0, pb.ServerAddress(filerAddr), s.grpcDialOption, s.filerTokenSource, func(client filer_pb.SeaweedFilerClient) error { return f(client) }) } diff --git a/weed/admin/dash/filer_client_auth_test.go b/weed/admin/dash/filer_client_auth_test.go new file mode 100644 index 0000000000..4ce9efa40e --- /dev/null +++ b/weed/admin/dash/filer_client_auth_test.go @@ -0,0 +1,170 @@ +package dash + +import ( + "context" + "crypto/rand" + "encoding/hex" + "net" + "strconv" + "testing" + "time" + + "github.com/seaweedfs/seaweedfs/weed/pb" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/security" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" +) + +type dashAuthFiler struct { + filer_pb.UnimplementedSeaweedFilerServer +} + +func (dashAuthFiler) GetFilerConfiguration(context.Context, *filer_pb.GetFilerConfigurationRequest) (*filer_pb.GetFilerConfigurationResponse, error) { + return &filer_pb.GetFilerConfigurationResponse{DirBuckets: "/buckets", FilerGroup: "test"}, nil +} + +func (dashAuthFiler) LookupDirectoryEntry(context.Context, *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) { + return &filer_pb.LookupDirectoryEntryResponse{Entry: &filer_pb.Entry{}}, nil +} + +func dashAuthCheck(ctx context.Context, key security.SigningKey, require bool) error { + md, _ := metadata.FromIncomingContext(ctx) + values := md.Get("authorization") + if len(key) == 0 { + if require && len(values) == 0 { + return status.Error(codes.Unauthenticated, "authentication required") + } + if len(values) == 0 { + return nil + } + } + if len(values) != 1 { + return status.Error(codes.Unauthenticated, "authentication required") + } + const prefix = "Bearer " + if len(values[0]) <= len(prefix) || values[0][:len(prefix)] != prefix || !security.IsFilerAdminToken(key, security.EncodedJwt(values[0][len(prefix):])) { + return status.Error(codes.Unauthenticated, "invalid authentication") + } + return nil +} + +func dashAuthAddress(address string) pb.ServerAddress { + _, portText, err := net.SplitHostPort(address) + if err != nil { + return pb.ServerAddress(address) + } + port, err := strconv.Atoi(portText) + if err != nil { + return pb.ServerAddress(address) + } + return pb.NewServerAddressWithGrpcPort(address, port) +} + +func startDashAuthFiler(t *testing.T, key security.SigningKey, require bool) pb.ServerAddress { + t.Helper() + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal("listen") + } + server := grpc.NewServer( + grpc.UnaryInterceptor(func(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { + if err := dashAuthCheck(ctx, key, require); err != nil { + return nil, err + } + return handler(ctx, req) + }), + grpc.StreamInterceptor(func(srv any, stream grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) error { + if err := dashAuthCheck(stream.Context(), key, require); err != nil { + return err + } + return handler(srv, stream) + }), + ) + filer_pb.RegisterSeaweedFilerServer(server, dashAuthFiler{}) + go func() { _ = server.Serve(listener) }() + address := dashAuthAddress(listener.Addr().String()) + t.Cleanup(func() { + server.Stop() + _ = listener.Close() + pb.InvalidateGrpcConnection(address.ToGrpcAddress()) + }) + return address +} + +func dashTestKey(t *testing.T) security.SigningKey { + t.Helper() + bytes := make([]byte, 32) + if _, err := rand.Read(bytes); err != nil { + t.Fatal("generate disposable signing key") + } + return security.SigningKey(hex.EncodeToString(bytes)) +} + +func TestAdminFilerReadsUsePerCallAdminToken(t *testing.T) { + key := dashTestKey(t) + otherKey := dashTestKey(t) + for _, tc := range []struct { + name string + require bool + source security.FilerTokenSource + want codes.Code + }{ + { + name: "valid token", + require: true, + source: func(context.Context) (security.EncodedJwt, error) { + return security.GenJwtForFilerAdmin(key, 10), nil + }, + want: codes.OK, + }, + { + name: "wrong key", + require: true, + source: func(context.Context) (security.EncodedJwt, error) { + return security.GenJwtForFilerAdmin(otherKey, 10), nil + }, + want: codes.Unauthenticated, + }, + { + name: "missing token", + require: true, + want: codes.Unauthenticated, + }, + { + name: "optional no key", + require: false, + want: codes.OK, + }, + } { + t.Run(tc.name, func(t *testing.T) { + serverKey := key + if tc.name == "optional no key" { + serverKey = nil + } + address := startDashAuthFiler(t, serverKey, tc.require) + server := &AdminServer{ + grpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()), + filerTokenSource: tc.source, + cachedFilers: []string{string(address)}, + lastFilerUpdate: time.Now(), + filerCacheExpiration: time.Hour, + } + config, err := server.getFilerConfig() + if status.Code(err) != tc.want { + t.Fatalf("admin filer configuration read code=%v, want %v", status.Code(err), tc.want) + } + if tc.want == codes.OK { + if config.BucketsPath != "/buckets" || config.FilerGroup != "test" { + t.Fatal("admin filer configuration response was not preserved") + } + if _, err := server.getFilerConf(); err != nil { + t.Fatal("admin filer.conf read was refused") + } + } + }) + } +} diff --git a/weed/admin/dash/mount_clients.go b/weed/admin/dash/mount_clients.go index a5f965f6ab..c688a8a6ed 100644 --- a/weed/admin/dash/mount_clients.go +++ b/weed/admin/dash/mount_clients.go @@ -36,7 +36,7 @@ func (s *AdminServer) GetMountClients() (*MountClientsData, error) { defer wg.Done() ctx, cancel := context.WithTimeout(context.Background(), mountClientsFilerTimeout) defer cancel() - err := pb.WithGrpcFilerClient(false, 0, pb.ServerAddress(filerAddr), s.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + err := pb.WithGrpcFilerClient(false, 0, pb.ServerAddress(filerAddr), s.grpcDialOption, s.filerTokenSource, func(client filer_pb.SeaweedFilerClient) error { resp, err := client.ListMetadataSubscribers(ctx, &filer_pb.ListMetadataSubscribersRequest{ ClientTypes: mountClientTypes, }) diff --git a/weed/cluster/lock_client.go b/weed/cluster/lock_client.go index 26926c731d..339ef9ef9d 100644 --- a/weed/cluster/lock_client.go +++ b/weed/cluster/lock_client.go @@ -13,6 +13,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/glog" "github.com/seaweedfs/seaweedfs/weed/pb" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/security" "google.golang.org/grpc" ) @@ -21,7 +22,10 @@ type LockClient struct { // RequestContext, when set before using the client, supplies per-attempt // metadata for lock, renewal and unlock RPCs. Generic clients retain their // existing authority when it is nil. - RequestContext func(context.Context) context.Context + RequestContext func(context.Context) context.Context + // TokenSource supplies per-call filer authorization. A nil source preserves + // the existing anonymous behavior. + TokenSource security.FilerTokenSource maxLockDuration time.Duration sleepDuration time.Duration seedFiler pb.ServerAddress @@ -436,7 +440,7 @@ func (lock *LiveLock) StopShortLivedLock() error { defer func() { atomic.StoreInt32(&lock.isLocked, 0) }() - return pb.WithFilerClient(false, 0, lock.hostFiler, lock.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + return pb.WithGrpcFilerClient(false, 0, lock.hostFiler, lock.grpcDialOption, lock.lc.TokenSource, func(client filer_pb.SeaweedFilerClient) error { ctx, cancel := context.WithTimeout(context.Background(), lock.lc.lockRpcTimeout) defer cancel() if lock.lc.RequestContext != nil { @@ -495,7 +499,7 @@ func (lock *LiveLock) doLock(lockDuration, attemptTimeout time.Duration) (errorM previousHostFiler := lock.hostFiler previousOwner := lock.owner - err = pb.WithFilerClient(false, 0, lock.hostFiler, lock.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + err = pb.WithGrpcFilerClient(false, 0, lock.hostFiler, lock.grpcDialOption, lock.lc.TokenSource, func(client filer_pb.SeaweedFilerClient) error { // Bound each attempt: a ring member that is reachable from the masters // but not from this filer would otherwise block on the connect timeout. ctx, cancel := context.WithTimeout(context.Background(), attemptTimeout) diff --git a/weed/cluster/lock_client_test.go b/weed/cluster/lock_client_test.go index 1ee6617c76..3a04af6ea4 100644 --- a/weed/cluster/lock_client_test.go +++ b/weed/cluster/lock_client_test.go @@ -2,8 +2,11 @@ package cluster import ( "context" + "crypto/rand" + "encoding/hex" "fmt" "net" + "strings" "sync/atomic" "testing" "time" @@ -11,8 +14,12 @@ import ( "github.com/seaweedfs/seaweedfs/weed/cluster/lock_manager" "github.com/seaweedfs/seaweedfs/weed/pb" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/security" "google.golang.org/grpc" + "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" ) // The gateway must resolve a lock key to the same primary the filers do, @@ -323,6 +330,166 @@ func (s *grantingLockFiler) DistributedLock(ctx context.Context, req *filer_pb.L return &filer_pb.LockResponse{RenewToken: "tok"}, nil } +type rotatingAuthLockFiler struct { + filer_pb.UnimplementedSeaweedFilerServer + keys []security.SigningKey + authorizations chan int +} + +type identityLockFiler struct { + filer_pb.UnimplementedSeaweedFilerServer + seen chan bool +} + +func (s *identityLockFiler) DistributedLock(ctx context.Context, req *filer_pb.LockRequest) (*filer_pb.LockResponse, error) { + md, _ := metadata.FromIncomingContext(ctx) + values := md.Get("authorization") + valid := len(values) == 1 && values[0] == "Bearer caller-identity" + s.seen <- valid + if !valid { + return nil, status.Error(codes.Unauthenticated, "missing caller identity") + } + return &filer_pb.LockResponse{RenewToken: "tok"}, nil +} + +func (s *rotatingAuthLockFiler) DistributedLock(ctx context.Context, req *filer_pb.LockRequest) (*filer_pb.LockResponse, error) { + md, _ := metadata.FromIncomingContext(ctx) + values := md.Get("authorization") + authenticatedBy := -1 + if len(values) == 1 && strings.HasPrefix(values[0], security.BearerPrefix) { + for i, key := range s.keys { + if security.IsFilerAdminToken(key, security.EncodedJwt(strings.TrimPrefix(values[0], security.BearerPrefix))) { + authenticatedBy = i + break + } + } + } + + s.authorizations <- authenticatedBy + if authenticatedBy < 0 { + return nil, status.Error(codes.Unauthenticated, "missing or invalid filer authorization") + } + return &filer_pb.LockResponse{RenewToken: "tok"}, nil +} + +func lockTestSigningKey(t *testing.T) security.SigningKey { + t.Helper() + bytes := make([]byte, 32) + if _, err := rand.Read(bytes); err != nil { + t.Fatal(err) + } + return security.SigningKey(hex.EncodeToString(bytes)) +} + +func TestLockClientResolvesFilerTokenForEachAttempt(t *testing.T) { + keys := []security.SigningKey{lockTestSigningKey(t), lockTestSigningKey(t)} + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + filer := &rotatingAuthLockFiler{keys: keys, authorizations: make(chan int, 2)} + grpcServer := grpc.NewServer() + filer_pb.RegisterSeaweedFilerServer(grpcServer, filer) + go grpcServer.Serve(listener) + defer grpcServer.Stop() + + host, port, err := net.SplitHostPort(listener.Addr().String()) + if err != nil { + t.Fatalf("split host port: %v", err) + } + lc := NewLockClient(grpc.WithTransportCredentials(insecure.NewCredentials()), pb.ServerAddress(fmt.Sprintf("%s:0.%s", host, port))) + var tokenNumber uint64 + lc.TokenSource = func(context.Context) (security.EncodedJwt, error) { + n := atomic.AddUint64(&tokenNumber, 1) + return security.GenJwtForFilerAdmin(keys[(n-1)%uint64(len(keys))], 60), nil + } + + lock := lc.NewShortLivedLock("test-key", "test-owner") + if lock == nil { + t.Fatal("expected the lock to be acquired") + } + if err := lock.AttemptToLock(time.Second); err != nil { + t.Fatalf("renew lock: %v", err) + } + + first := <-filer.authorizations + second := <-filer.authorizations + if first < 0 || second < 0 { + t.Fatal("expected authorization on both attempts") + } + if first == second { + t.Fatal("expected a freshly resolved token on renewal") + } +} + +func TestLockClientTokenSourceErrorDoesNotDispatch(t *testing.T) { + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + filer := &rotatingAuthLockFiler{authorizations: make(chan int, 1)} + grpcServer := grpc.NewServer() + filer_pb.RegisterSeaweedFilerServer(grpcServer, filer) + go grpcServer.Serve(listener) + defer grpcServer.Stop() + + host, port, err := net.SplitHostPort(listener.Addr().String()) + if err != nil { + t.Fatalf("split host port: %v", err) + } + lc := NewLockClient(grpc.WithTransportCredentials(insecure.NewCredentials()), pb.ServerAddress(fmt.Sprintf("%s:0.%s", host, port))) + lc.TokenSource = func(context.Context) (security.EncodedJwt, error) { + return "", fmt.Errorf("token source unavailable") + } + lock := &LiveLock{ + key: "test-key", + hostFiler: lc.seedFiler, + grpcDialOption: lc.grpcDialOption, + lc: lc, + } + if _, _, err := lock.doLock(time.Second, time.Second); err == nil { + t.Fatal("expected token-source error") + } + select { + case <-filer.authorizations: + t.Fatal("token-source error dispatched a filer RPC") + case <-time.After(100 * time.Millisecond): + } +} + +func TestLockClientNilTokenSourcePreservesRequestContext(t *testing.T) { + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + filer := &identityLockFiler{seen: make(chan bool, 1)} + grpcServer := grpc.NewServer() + filer_pb.RegisterSeaweedFilerServer(grpcServer, filer) + go grpcServer.Serve(listener) + defer grpcServer.Stop() + + host, port, err := net.SplitHostPort(listener.Addr().String()) + if err != nil { + t.Fatalf("split host port: %v", err) + } + lc := NewLockClient(grpc.WithTransportCredentials(insecure.NewCredentials()), pb.ServerAddress(fmt.Sprintf("%s:0.%s", host, port))) + lc.RequestContext = func(ctx context.Context) context.Context { + return metadata.AppendToOutgoingContext(ctx, "authorization", "Bearer caller-identity") + } + lock := lc.NewShortLivedLock("test-key", "test-owner") + if lock == nil { + t.Fatal("expected the existing caller identity to acquire the lock") + } + select { + case valid := <-filer.seen: + if !valid { + t.Fatal("existing caller identity was not preserved") + } + case <-time.After(time.Second): + t.Fatal("filer did not receive the request") + } +} + // A ring member that accepts connections but never answers must not swallow // the retry window: when its budget is spent the seed route still gets an // attempt before acquisition gives up. diff --git a/weed/command/filer_backup.go b/weed/command/filer_backup.go index 4991a32163..b166f9e3fd 100644 --- a/weed/command/filer_backup.go +++ b/weed/command/filer_backup.go @@ -157,7 +157,7 @@ func doFilerBackup(grpcDialOption grpc.DialOption, backupOption *FilerBackupOpti // snapshot below sets the start point; no checkpoint read needed glog.V(0).Infof("initialSnapshot requested — walking live tree before subscribing") } else { - lastOffsetTsNs, err := getOffsetWithFallback(grpcDialOption, sourceFiler, BackupKeyPrefix, sinkId, BackupKeyPrefix, legacySinkId) + lastOffsetTsNs, err := getOffsetWithFallback(grpcDialOption, sourceFiler, security.FilerAdminToken, BackupKeyPrefix, sinkId, BackupKeyPrefix, legacySinkId) if err != nil { return 0, fmt.Errorf("read backup offset: %w", err) } else if lastOffsetTsNs > 0 { @@ -181,11 +181,17 @@ func doFilerBackup(grpcDialOption grpc.DialOption, backupOption *FilerBackupOpti *backupOption.proxyByFiler); err != nil { return resumeTsNs, fmt.Errorf("filersource initialization failed: %v", err) } + filerSource.SetFilerTokenSource(security.FilerAdminToken) + dataSink.SetSourceFiler(filerSource) + if tokenSink, ok := dataSink.(interface { + SetFilerTokenSource(security.FilerTokenSource) + }); ok { + tokenSink.SetFilerTokenSource(security.FilerAdminToken) + } if err := repl_util.InitializeSSEForReplication(filerSource); err != nil { return resumeTsNs, fmt.Errorf("SSE initialization failed: %v", err) } - dataSink.SetSourceFiler(filerSource) if err := replication.CheckSinkDigest(filerSource.GrpcAddress(), filerSource.Digest, dataSink); err != nil { if replication.IsDigestMismatch(err) { glog.Exitf("%v", err) @@ -220,7 +226,7 @@ func doFilerBackup(grpcDialOption grpc.DialOption, backupOption *FilerBackupOpti // The walk can take hours on large trees; retry the tiny KV write a // handful of times before giving up so a flaky filer KV doesn't force // the whole walk to repeat on the next retry loop iteration. - if err := persistSnapshotOffset(grpcDialOption, sourceFiler, sinkId, snapshotTsNs); err != nil { + if err := persistSnapshotOffset(grpcDialOption, sourceFiler, sinkId, snapshotTsNs, security.FilerAdminToken); err != nil { glog.Errorf("initialSnapshot: FAILED to persist offset %d for sinkId %d after retries: %v — the next retry will redo the full walk", snapshotTsNs, sinkId, err) return 0, fmt.Errorf("persist initial snapshot offset: %w", err) } @@ -300,7 +306,7 @@ func doFilerBackup(grpcDialOption grpc.DialOption, backupOption *FilerBackupOpti defer ticker.Stop() persist := func() { if ts := resumeTsNsFor(processor); ts != lastPersistedTsNs.Load() { - if err := setOffset(grpcDialOption, sourceFiler, BackupKeyPrefix, sinkId, ts); err == nil { + if err := setOffset(grpcDialOption, sourceFiler, security.FilerAdminToken, BackupKeyPrefix, sinkId, ts); err == nil { lastPersistedTsNs.Store(ts) } else { glog.Warningf("persist backup offset: %v", err) @@ -366,6 +372,7 @@ func doFilerBackup(grpcDialOption grpc.DialOption, backupOption *FilerBackupOpti StartTsNs: startFrom.UnixNano(), StopTsNs: 0, EventErrorType: eventErrorType, + FilerTokenSource: security.FilerAdminToken, GetResumeTsNs: func() int64 { return resumeTsNsFor(processor) }, @@ -487,12 +494,16 @@ func eventSupersessionProbe(resp *filer_pb.SubscribeMetadataResponse) (util.Full // errors. Losing this write forces a full re-walk on the next retry loop // iteration, so a small retry budget here is far cheaper than paying the // walk cost again on a large tree. -func persistSnapshotOffset(grpcDialOption grpc.DialOption, sourceFiler pb.ServerAddress, sinkId int32, tsNs int64) error { +func persistSnapshotOffset(grpcDialOption grpc.DialOption, sourceFiler pb.ServerAddress, sinkId int32, tsNs int64, tokenSource ...security.FilerTokenSource) error { const attempts = 4 backoff := 500 * time.Millisecond + var source security.FilerTokenSource + if len(tokenSource) > 0 { + source = tokenSource[0] + } var lastErr error for i := 1; i <= attempts; i++ { - if err := setOffset(grpcDialOption, sourceFiler, BackupKeyPrefix, sinkId, tsNs); err == nil { + if err := setOffset(grpcDialOption, sourceFiler, source, BackupKeyPrefix, sinkId, tsNs); err == nil { return nil } else { lastErr = err diff --git a/weed/command/filer_backup_auth_test.go b/weed/command/filer_backup_auth_test.go new file mode 100644 index 0000000000..60e9b5601e --- /dev/null +++ b/weed/command/filer_backup_auth_test.go @@ -0,0 +1,113 @@ +package command + +import ( + "context" + "crypto/rand" + "encoding/hex" + "net" + "strings" + "sync" + "testing" + + "github.com/seaweedfs/seaweedfs/weed/pb" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/security" + "github.com/seaweedfs/seaweedfs/weed/util" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" +) + +type backupAuthKVFiler struct { + filer_pb.UnimplementedSeaweedFilerServer + key security.SigningKey + mu sync.Mutex + kv map[string][]byte +} + +func (s *backupAuthKVFiler) authenticate(ctx context.Context) error { + md, _ := metadata.FromIncomingContext(ctx) + values := md.Get("authorization") + if len(values) != 1 || !strings.HasPrefix(values[0], security.BearerPrefix) || + !security.IsFilerAdminToken(s.key, security.EncodedJwt(strings.TrimPrefix(values[0], security.BearerPrefix))) { + return status.Error(codes.Unauthenticated, "missing or invalid filer authorization") + } + return nil +} + +func (s *backupAuthKVFiler) KvGet(_ context.Context, request *filer_pb.KvGetRequest) (*filer_pb.KvGetResponse, error) { + s.mu.Lock() + defer s.mu.Unlock() + return &filer_pb.KvGetResponse{Value: append([]byte(nil), s.kv[string(request.Key)]...)}, nil +} + +func (s *backupAuthKVFiler) KvPut(_ context.Context, request *filer_pb.KvPutRequest) (*filer_pb.KvPutResponse, error) { + s.mu.Lock() + defer s.mu.Unlock() + s.kv[string(request.Key)] = append([]byte(nil), request.Value...) + return &filer_pb.KvPutResponse{}, nil +} + +func backupAuthKey(t *testing.T) security.SigningKey { + t.Helper() + buf := make([]byte, 32) + if _, err := rand.Read(buf); err != nil { + t.Fatal(err) + } + return security.SigningKey(hex.EncodeToString(buf)) +} + +func startBackupAuthKVFiler(t *testing.T, filer *backupAuthKVFiler) (pb.ServerAddress, grpc.DialOption) { + t.Helper() + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + server := grpc.NewServer(grpc.UnaryInterceptor(func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { + if err := filer.authenticate(ctx); err != nil { + return nil, err + } + return handler(ctx, req) + })) + filer_pb.RegisterSeaweedFilerServer(server, filer) + go func() { _ = server.Serve(listener) }() + t.Cleanup(func() { + server.Stop() + _ = listener.Close() + }) + port := listener.Addr().(*net.TCPAddr).Port + return pb.NewServerAddressWithGrpcPort("127.0.0.1:8888", port), grpc.WithTransportCredentials(insecure.NewCredentials()) +} + +func TestBackupOffsetUsesProtectedPerCallOperation(t *testing.T) { + key := backupAuthKey(t) + filer := &backupAuthKVFiler{key: key, kv: make(map[string][]byte)} + address, dial := startBackupAuthKVFiler(t, filer) + tokenSource := security.FilerTokenSource(func(context.Context) (security.EncodedJwt, error) { + return security.GenJwtForFilerAdmin(key, 60), nil + }) + prefix := BackupKeyPrefix + const signature = int32(43) + if err := setOffset(dial, address, tokenSource, prefix, signature, 1234); err != nil { + t.Fatalf("protected backup offset write: %v", err) + } + got, err := getOffset(dial, address, tokenSource, prefix, signature) + if err != nil { + t.Fatalf("protected backup offset read: %v", err) + } + if got != 1234 { + t.Fatalf("backup offset = %d, want 1234", got) + } + + // Keep this assertion at the stored-value boundary: it proves the real KV + // calls completed through the protected adapter, while avoiding token output. + keyBytes := []byte(prefix + "____") + util.Uint32toBytes(keyBytes[len(prefix):], uint32(signature)) + filer.mu.Lock() + defer filer.mu.Unlock() + if _, ok := filer.kv[string(keyBytes)]; !ok { + t.Fatal("protected backup offset was not persisted") + } +} diff --git a/weed/command/filer_backup_offset_test.go b/weed/command/filer_backup_offset_test.go index 385612c719..4eefd8d19a 100644 --- a/weed/command/filer_backup_offset_test.go +++ b/weed/command/filer_backup_offset_test.go @@ -84,28 +84,28 @@ func TestBackupOffset_HistoricalFallbackThenIndependence(t *testing.T) { sinkId, legacySinkId := backupCheckpointIds("/", s, false) // pre-upgrade state: only the shared historical checkpoint exists - if err := setOffset(dial, filerAddr, BackupKeyPrefix, legacySinkId, 111); err != nil { + if err := setOffset(dial, filerAddr, nil, BackupKeyPrefix, legacySinkId, 111); err != nil { t.Fatalf("seed historical offset: %v", err) } - got, err := getOffsetWithFallback(dial, filerAddr, BackupKeyPrefix, sinkId, BackupKeyPrefix, legacySinkId) + 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, BackupKeyPrefix, sinkId, 222); err != nil { + if err := setOffset(dial, filerAddr, nil, BackupKeyPrefix, sinkId, 222); err != nil { t.Fatalf("write destination-scoped offset: %v", err) } - got, err = getOffsetWithFallback(dial, filerAddr, BackupKeyPrefix, sinkId, BackupKeyPrefix, legacySinkId) + 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, BackupKeyPrefix, legacySinkId, 333); err != nil { + if err := setOffset(dial, filerAddr, nil, BackupKeyPrefix, legacySinkId, 333); err != nil { t.Fatalf("advance historical offset: %v", err) } - got, err = getOffsetWithFallback(dial, filerAddr, BackupKeyPrefix, sinkId, BackupKeyPrefix, legacySinkId) + 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) } @@ -120,17 +120,17 @@ func TestBackupOffset_DistinctDestinationsDoNotShare(t *testing.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, BackupKeyPrefix, idA, 1000); err != nil { + if err := setOffset(dial, filerAddr, nil, BackupKeyPrefix, idA, 1000); err != nil { t.Fatalf("write A: %v", err) } - if err := setOffset(dial, filerAddr, BackupKeyPrefix, idB, 2000); err != nil { + if err := setOffset(dial, filerAddr, nil, BackupKeyPrefix, idB, 2000); err != nil { t.Fatalf("write B: %v", err) } - if got, err := getOffsetWithFallback(dial, filerAddr, BackupKeyPrefix, idA, BackupKeyPrefix, legacyA); err != nil || got != 1000 { + 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, BackupKeyPrefix, idB, BackupKeyPrefix, legacyB); err != nil || got != 2000 { + 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) } } diff --git a/weed/command/filer_cat.go b/weed/command/filer_cat.go index 73ae320d20..dbaadc362e 100644 --- a/weed/command/filer_cat.go +++ b/weed/command/filer_cat.go @@ -98,7 +98,7 @@ func runFilerCat(cmd *Command, args []string) bool { writer = f } - pb.WithFilerClient(false, util.RandomInt32(), filerCat.filerAddress, filerCat.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + err = pb.WithGrpcFilerClient(false, util.RandomInt32(), filerCat.filerAddress, filerCat.grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error { request := &filer_pb.LookupDirectoryEntryRequest{ Name: name, @@ -119,6 +119,10 @@ func runFilerCat(cmd *Command, args []string) bool { return filer.StreamContent(&filerCat, writer, respLookupEntry.Entry.GetChunks(), 0, int64(filer.FileSize(respLookupEntry.Entry))) }) + if err != nil { + fmt.Fprintf(os.Stderr, "read %s: %v\n", filerSource, err) + return false + } return true } diff --git a/weed/command/filer_copy.go b/weed/command/filer_copy.go index e0df946786..2f4ba592cb 100644 --- a/weed/command/filer_copy.go +++ b/weed/command/filer_copy.go @@ -186,7 +186,7 @@ func runCopy(cmd *Command, args []string) bool { } func readFilerConfiguration(grpcDialOption grpc.DialOption, filerGrpcAddress pb.ServerAddress) (masters []string, collection, replication string, dirBuckets string, maxMB uint32, cipher bool, digest string, err error) { - err = pb.WithGrpcFilerClient(false, 0, filerGrpcAddress, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + err = pb.WithGrpcFilerClient(false, 0, filerGrpcAddress, grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error { resp, err := client.GetFilerConfiguration(context.Background(), &filer_pb.GetFilerConfigurationRequest{}) if err != nil { return fmt.Errorf("get filer %s configuration: %v", filerGrpcAddress, err) @@ -318,7 +318,7 @@ func (worker *FileCopyWorker) checkExistingFileFirst(task FileCopyTask, f *os.Fi return } - err = pb.WithGrpcFilerClient(false, worker.signature, worker.filerAddress, worker.options.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + err = pb.WithGrpcFilerClient(false, worker.signature, worker.filerAddress, worker.options.grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error { request := &filer_pb.LookupDirectoryEntryRequest{ Directory: task.destinationUrlPath, @@ -387,7 +387,7 @@ func (worker *FileCopyWorker) uploadFileAsOne(task FileCopyTask, f *os.File) err chunks = append(chunks, uploadResult.ToPbFileChunk(finalFileId, 0, time.Now().UnixNano())) } - if err := pb.WithGrpcFilerClient(false, worker.signature, worker.filerAddress, worker.options.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + if err := pb.WithGrpcFilerClient(false, worker.signature, worker.filerAddress, worker.options.grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error { request := &filer_pb.CreateEntryRequest{ Directory: task.destinationUrlPath, Entry: &filer_pb.Entry{ @@ -524,7 +524,7 @@ func (worker *FileCopyWorker) uploadFileInChunks(task FileCopyTask, f *os.File, return fmt.Errorf("create manifest: %w", manifestErr) } - if err := pb.WithGrpcFilerClient(false, worker.signature, worker.filerAddress, worker.options.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + if err := pb.WithGrpcFilerClient(false, worker.signature, worker.filerAddress, worker.options.grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error { request := &filer_pb.CreateEntryRequest{ Directory: task.destinationUrlPath, Entry: &filer_pb.Entry{ @@ -614,12 +614,9 @@ func (worker *FileCopyWorker) saveDataAsChunk(reader io.Reader, name string, off var _ = filer_pb.FilerClient(&FileCopyWorker{}) func (worker *FileCopyWorker) WithFilerClient(streamingMode bool, fn func(filer_pb.SeaweedFilerClient) error) (err error) { - - filerGrpcAddress := worker.filerAddress.ToGrpcAddress() - err = pb.WithGrpcClient(context.Background(), streamingMode, worker.signature, func(grpcConnection *grpc.ClientConn) error { - client := filer_pb.NewSeaweedFilerClient(grpcConnection) + err = pb.WithGrpcFilerClient(streamingMode, worker.signature, worker.filerAddress, worker.options.grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error { return fn(client) - }, filerGrpcAddress, false, worker.options.grpcDialOption) + }) return } diff --git a/weed/command/filer_meta_backup.go b/weed/command/filer_meta_backup.go index 1ef2b6747a..4739564d11 100644 --- a/weed/command/filer_meta_backup.go +++ b/weed/command/filer_meta_backup.go @@ -388,6 +388,7 @@ func (metaBackup *FilerMetaBackupOptions) streamMetadataBackup(startTime time.Ti StartTsNs: startTime.UnixNano(), StopTsNs: 0, EventErrorType: pb.RetryForeverOnError, + FilerTokenSource: security.FilerAdminToken, } return pb.FollowMetadata(pb.ServerAddress(*metaBackup.filerAddress), metaBackup.grpcDialOption, metadataFollowOption, processEventFnWithOffset) @@ -422,7 +423,7 @@ var _ = filer_pb.FilerClient(&FilerMetaBackupOptions{}) func (metaBackup *FilerMetaBackupOptions) WithFilerClient(streamingMode bool, fn func(filer_pb.SeaweedFilerClient) error) error { - return pb.WithFilerClient(streamingMode, metaBackup.clientId, pb.ServerAddress(*metaBackup.filerAddress), metaBackup.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + return pb.WithGrpcFilerClient(streamingMode, metaBackup.clientId, pb.ServerAddress(*metaBackup.filerAddress), metaBackup.grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error { return fn(client) }) diff --git a/weed/command/filer_meta_scan.go b/weed/command/filer_meta_scan.go index 45305ee84f..b2154a3452 100644 --- a/weed/command/filer_meta_scan.go +++ b/weed/command/filer_meta_scan.go @@ -90,7 +90,7 @@ type scanFilerClient struct { } func (c *scanFilerClient) WithFilerClient(streamingMode bool, fn func(filer_pb.SeaweedFilerClient) error) error { - return pb.WithFilerClient(streamingMode, c.signature, c.address, c.grpcDialOption, fn) + return pb.WithGrpcFilerClient(streamingMode, c.signature, c.address, c.grpcDialOption, security.FilerAdminToken, fn) } func (c *scanFilerClient) AdjustedUrl(location *filer_pb.Location) string { return location.Url } @@ -298,14 +298,15 @@ func runFilerMetaScan(cmd *Command, args []string) bool { scan := func(directRead bool) error { option := &pb.MetadataFollowOption{ - ClientName: "scan", - ClientId: util.RandomInt32(), - ClientEpoch: 0, - SelfSignature: 0, - PathPrefix: *scanPathPrefix, - StartTsNs: startTs.UnixNano(), - StopTsNs: stopTsNs, - EventErrorType: pb.TrivialOnError, + ClientName: "scan", + ClientId: util.RandomInt32(), + ClientEpoch: 0, + SelfSignature: 0, + FilerTokenSource: security.FilerAdminToken, + PathPrefix: *scanPathPrefix, + StartTsNs: startTs.UnixNano(), + StopTsNs: stopTsNs, + EventErrorType: pb.TrivialOnError, } if directRead { // The server hands out log chunk fids and this reads them straight diff --git a/weed/command/filer_meta_tail.go b/weed/command/filer_meta_tail.go index 94481c28dc..267d900745 100644 --- a/weed/command/filer_meta_tail.go +++ b/weed/command/filer_meta_tail.go @@ -118,6 +118,7 @@ func runFilerMetaTail(cmd *Command, args []string) bool { StartTsNs: time.Now().Add(-*tailStart).UnixNano(), StopTsNs: untilTsNs, EventErrorType: pb.TrivialOnError, + FilerTokenSource: security.FilerAdminToken, } tailErr := pb.FollowMetadata(pb.ServerAddress(*tailFiler), grpcDialOption, metadataFollowOption, func(resp *filer_pb.SubscribeMetadataResponse) error { diff --git a/weed/command/filer_remote_gateway.go b/weed/command/filer_remote_gateway.go index 828248ac91..521c22ec43 100644 --- a/weed/command/filer_remote_gateway.go +++ b/weed/command/filer_remote_gateway.go @@ -26,18 +26,19 @@ type RemoteGatewayOptions struct { include *string exclude *string - mappings *remote_pb.RemoteStorageMapping - remoteConfs map[string]*remote_pb.RemoteConf - bucketsDir string - clientId int32 - clientEpoch int32 - resumeTsNs int64 + mappings *remote_pb.RemoteStorageMapping + remoteConfs map[string]*remote_pb.RemoteConf + bucketsDir string + clientId int32 + clientEpoch int32 + resumeTsNs int64 + filerTokenSource security.FilerTokenSource } var _ = filer_pb.FilerClient(&RemoteGatewayOptions{}) func (option *RemoteGatewayOptions) WithFilerClient(streamingMode bool, fn func(filer_pb.SeaweedFilerClient) error) error { - return pb.WithFilerClient(streamingMode, option.clientId, pb.ServerAddress(*option.filerAddress), option.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + return pb.WithGrpcFilerClient(streamingMode, option.clientId, pb.ServerAddress(*option.filerAddress), option.grpcDialOption, option.filerTokenSource, func(client filer_pb.SeaweedFilerClient) error { return fn(client) }) } @@ -88,6 +89,7 @@ func runFilerRemoteGateway(cmd *Command, args []string) bool { util.LoadSecurityConfiguration() grpcDialOption := security.LoadClientTLS(util.GetViper(), "grpc.client") remoteGatewayOptions.grpcDialOption = grpcDialOption + remoteGatewayOptions.filerTokenSource = security.FilerAdminToken filerAddress := pb.ServerAddress(*remoteGatewayOptions.filerAddress) @@ -98,6 +100,7 @@ func runFilerRemoteGateway(cmd *Command, args []string) bool { "/", // does not matter *remoteGatewayOptions.readChunkFromFiler, ) + filerSource.SetFilerTokenSource(remoteGatewayOptions.filerTokenSource) remoteGatewayOptions.bucketsDir = "/buckets" // check buckets again diff --git a/weed/command/filer_remote_gateway_buckets.go b/weed/command/filer_remote_gateway_buckets.go index a7369848ce..720510a9e7 100644 --- a/weed/command/filer_remote_gateway_buckets.go +++ b/weed/command/filer_remote_gateway_buckets.go @@ -33,7 +33,7 @@ func (option *RemoteGatewayOptions) followBucketUpdatesAndUploadToRemote(filerSo return err } - lastOffsetTs, err := collectLastSyncOffset(option, option.grpcDialOption, pb.ServerAddress(*option.filerAddress), option.bucketsDir, *option.timeAgo, option.resumeTsNs) + lastOffsetTs, err := collectLastSyncOffset(option, option.grpcDialOption, pb.ServerAddress(*option.filerAddress), option.bucketsDir, *option.timeAgo, option.resumeTsNs, option.filerTokenSource) if err != nil { return err } @@ -51,7 +51,7 @@ func (option *RemoteGatewayOptions) followBucketUpdatesAndUploadToRemote(filerSo now := time.Now().UnixNano() glog.V(0).Infof("remote sync %s progressed to %v %0.2f/sec", *option.filerAddress, time.Unix(0, offsetTsNs), float64(counter)/(float64(now-lastLogTsNs)/1e9)) lastLogTsNs = now - return remote_storage.SetSyncOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), option.bucketsDir, resumeTsNsFor(processor)) + return remote_storage.SetSyncOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), option.bucketsDir, resumeTsNsFor(processor), option.filerTokenSource) }) option.clientEpoch++ @@ -67,6 +67,7 @@ func (option *RemoteGatewayOptions) followBucketUpdatesAndUploadToRemote(filerSo StartTsNs: lastOffsetTs.UnixNano(), StopTsNs: 0, EventErrorType: pb.RetryForeverOnError, + FilerTokenSource: option.filerTokenSource, GetResumeTsNs: func() int64 { return resumeTsNsFor(processor) }, @@ -74,7 +75,7 @@ func (option *RemoteGatewayOptions) followBucketUpdatesAndUploadToRemote(filerSo } err = pb.FollowMetadata(pb.ServerAddress(*option.filerAddress), option.grpcDialOption, metadataFollowOption, processEventFnWithOffset) - option.resumeTsNs = saveResumeOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), option.bucketsDir, processor) + option.resumeTsNs = saveResumeOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), option.bucketsDir, processor, option.filerTokenSource) return err } @@ -709,7 +710,7 @@ func extractBucketPath(bucketsDir, dir string) (util.FullPath, bool) { func (option *RemoteGatewayOptions) collectRemoteStorageConf() (err error) { - if mappings, err := filer.ReadMountMappings(option.grpcDialOption, pb.ServerAddress(*option.filerAddress)); err != nil { + if mappings, err := filer.ReadMountMappings(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), option.filerTokenSource); err != nil { if err == filer_pb.ErrNotFound { return fmt.Errorf("remote storage is not configured in filer server") } diff --git a/weed/command/filer_remote_sync.go b/weed/command/filer_remote_sync.go index 43a5da3d2e..91229b55ef 100644 --- a/weed/command/filer_remote_sync.go +++ b/weed/command/filer_remote_sync.go @@ -28,14 +28,15 @@ type RemoteSyncOptions struct { resumeTsNs int64 // what resumeTsNs was earned under: the directory's remote location, and // the offset stored when it was kept (resumeFor) - resumeLoc *remote_pb.RemoteStorageLocation - resumeStoredNs int64 + resumeLoc *remote_pb.RemoteStorageLocation + resumeStoredNs int64 + filerTokenSource security.FilerTokenSource } var _ = filer_pb.FilerClient(&RemoteSyncOptions{}) func (option *RemoteSyncOptions) WithFilerClient(streamingMode bool, fn func(filer_pb.SeaweedFilerClient) error) error { - return pb.WithFilerClient(streamingMode, option.clientId, pb.ServerAddress(*option.filerAddress), option.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + return pb.WithGrpcFilerClient(streamingMode, option.clientId, pb.ServerAddress(*option.filerAddress), option.grpcDialOption, option.filerTokenSource, func(client filer_pb.SeaweedFilerClient) error { return fn(client) }) } @@ -98,6 +99,7 @@ func runFilerRemoteSynchronize(cmd *Command, args []string) bool { util.LoadSecurityConfiguration() grpcDialOption := security.LoadClientTLS(util.GetViper(), "grpc.client") remoteSyncOptions.grpcDialOption = grpcDialOption + remoteSyncOptions.filerTokenSource = security.FilerAdminToken dir := *remoteSyncOptions.dir filerAddress := pb.ServerAddress(*remoteSyncOptions.filerAddress) @@ -109,6 +111,7 @@ func runFilerRemoteSynchronize(cmd *Command, args []string) bool { "/", // does not matter *remoteSyncOptions.readChunkFromFiler, ) + filerSource.SetFilerTokenSource(remoteSyncOptions.filerTokenSource) if *remoteSyncOptions.allMounts { if dir != "" { diff --git a/weed/command/filer_remote_sync_all.go b/weed/command/filer_remote_sync_all.go index 05b918f390..ba1ea15f46 100644 --- a/weed/command/filer_remote_sync_all.go +++ b/weed/command/filer_remote_sync_all.go @@ -110,7 +110,7 @@ func newMountSupervisor(option *RemoteSyncOptions, filerSource *source.FilerSour return followMountedDir(o, filerSource, dir, watch) } m.readOffset = func(dir string) (int64, error) { - return remote_storage.GetSyncOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), dir) + return remote_storage.GetSyncOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), dir, option.filerTokenSource) } return m } diff --git a/weed/command/filer_remote_sync_dir.go b/weed/command/filer_remote_sync_dir.go index fca603a84f..4ff80f8b4b 100644 --- a/weed/command/filer_remote_sync_dir.go +++ b/weed/command/filer_remote_sync_dir.go @@ -23,6 +23,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/pb/remote_pb" "github.com/seaweedfs/seaweedfs/weed/remote_storage" "github.com/seaweedfs/seaweedfs/weed/replication/source" + "github.com/seaweedfs/seaweedfs/weed/security" "github.com/seaweedfs/seaweedfs/weed/util" "github.com/seaweedfs/seaweedfs/weed/util/chunk_cache" "google.golang.org/grpc" @@ -75,23 +76,23 @@ func followMountedDir(option *RemoteSyncOptions, filerSource *source.FilerSource // remote.unmount completing in between (its mapping write, its purge, // then its offset) would start a follow that saw the directory mounted // past the unmount's table, into its purge. - storedOffsetNs, err := remote_storage.GetSyncOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), mountedDir) + storedOffsetNs, err := remote_storage.GetSyncOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), mountedDir, option.filerTokenSource) if err != nil { return fmt.Errorf("read sync offset of %s: %w", mountedDir, err) } // read filer remote storage mount mappings - _, mountKey, remoteStorageMountLocation, remoteStorage, detectErr := filer.DetectMountInfo(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), mountedDir) + _, mountKey, remoteStorageMountLocation, remoteStorage, detectErr := filer.DetectMountInfo(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), mountedDir, option.filerTokenSource) if err := option.resumeFor(mountedDir, mountKey, remoteStorageMountLocation, detectErr, storedOffsetNs); err != nil { return err } dirLoc := dirRemoteLocation(mountKey, mountedDir, remoteStorageMountLocation) guard := &offsetGuard{dir: mountedDir, last: storedOffsetNs, read: func() (int64, error) { - return remote_storage.GetSyncOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), mountedDir) + return remote_storage.GetSyncOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), mountedDir, option.filerTokenSource) }, write: func(ts int64) error { - return remote_storage.SetSyncOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), mountedDir, ts) + return remote_storage.SetSyncOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), mountedDir, ts, option.filerTokenSource) }, } @@ -105,7 +106,7 @@ func followMountedDir(option *RemoteSyncOptions, filerSource *source.FilerSource return err } lastOffsetTs, err = startAfterMountOffset(lastOffsetTs, mountKey, mountedDir, *option.timeAgo, option.resumeTsNs, func() (int64, error) { - return remote_storage.GetSyncOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), mountKey) + return remote_storage.GetSyncOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), mountKey, option.filerTokenSource) }) if err != nil { return err @@ -164,6 +165,7 @@ func followMountedDir(option *RemoteSyncOptions, filerSource *source.FilerSource StartTsNs: lastOffsetTs.UnixNano(), StopTsNs: 0, EventErrorType: pb.RetryForeverOnError, + FilerTokenSource: option.filerTokenSource, GetResumeTsNs: func() int64 { return resumeTsNsFor(processor) }, @@ -233,9 +235,9 @@ func startAfterMountOffset(start time.Time, mountKey, dir string, timeAgo time.D // recomputes -timeAgo from now, so a failure before the first checkpoint // would otherwise start the retry after the event it failed on. The offset is // returned for the retry in this process, which must not depend on the write. -func saveResumeOffset(grpcDialOption grpc.DialOption, filerAddress pb.ServerAddress, dir string, processor *MetadataProcessor) int64 { +func saveResumeOffset(grpcDialOption grpc.DialOption, filerAddress pb.ServerAddress, dir string, processor *MetadataProcessor, tokenSource ...security.FilerTokenSource) int64 { return saveResumeOffsetWith(func(ts int64) error { - return remote_storage.SetSyncOffset(grpcDialOption, filerAddress, dir, ts) + return remote_storage.SetSyncOffset(grpcDialOption, filerAddress, dir, ts, tokenSource...) }, dir, processor) } @@ -1490,7 +1492,7 @@ func retriedWriteFile(client remote_storage.RemoteStorageClient, filerSource fil return } -func collectLastSyncOffset(filerClient filer_pb.FilerClient, grpcDialOption grpc.DialOption, filerAddress pb.ServerAddress, mountedDir string, timeAgo time.Duration, resumeTsNs int64) (time.Time, error) { +func collectLastSyncOffset(filerClient filer_pb.FilerClient, grpcDialOption grpc.DialOption, filerAddress pb.ServerAddress, mountedDir string, timeAgo time.Duration, resumeTsNs int64, tokenSource ...security.FilerTokenSource) (time.Time, error) { if resumeTsNs > 0 { // the previous attempt pinned where it stopped, which can sit behind // both the saved offset and a recomputed -timeAgo window @@ -1504,7 +1506,9 @@ func collectLastSyncOffset(filerClient filer_pb.FilerClient, grpcDialOption grpc entry, _, _, err := filer_pb.GetEntry(ctx, filerClient, util.FullPath(mountedDir)) return entry, err }, - func() (int64, error) { return remote_storage.GetSyncOffset(grpcDialOption, filerAddress, mountedDir) }) + func() (int64, error) { + return remote_storage.GetSyncOffset(grpcDialOption, filerAddress, mountedDir, tokenSource...) + }) } // collectLastSyncOffsetFrom is collectLastSyncOffset with the saved offset diff --git a/weed/command/filer_sync.go b/weed/command/filer_sync.go index 2f10c1eb88..7e6ca26843 100644 --- a/weed/command/filer_sync.go +++ b/weed/command/filer_sync.go @@ -78,6 +78,7 @@ type syncState struct { sourcePath string targetPath string sourceFilerSignature int32 + tokenSource security.FilerTokenSource } var ( @@ -177,6 +178,8 @@ func runFilerSynchronize(cmd *Command, args []string) bool { // per-cluster HTTPS clients for volume server connections var httpClientA, httpClientB *util_http_client.HTTPClient var jwtForFilerA, jwtForFilerB security.FilerJwtProvider + tokenSourceA := security.FilerAdminTokenFromFile(*syncOptions.aSecurity) + tokenSourceB := security.FilerAdminTokenFromFile(*syncOptions.bSecurity) if *syncOptions.aSecurity != "" { var err error if httpClientA, err = security.LoadHTTPClientFromFile(*syncOptions.aSecurity); err != nil { @@ -205,13 +208,13 @@ func runFilerSynchronize(cmd *Command, args []string) bool { go statsCollect.StartMetricsServer(*syncOptions.metricsHttpIp, *syncOptions.metricsHttpPort) // read a filer signature - aFilerSignature, aFilerDigest, aFilerErr := replication.ReadFilerSignature(grpcDialOptionA, filerA) + aFilerSignature, aFilerDigest, aFilerErr := replication.ReadFilerSignature(grpcDialOptionA, filerA, tokenSourceA) if aFilerErr != nil { glog.Errorf("get filer 'a' signature %d error from %s to %s: %v", aFilerSignature, *syncOptions.filerA, *syncOptions.filerB, aFilerErr) return true } // read b filer signature - bFilerSignature, bFilerDigest, bFilerErr := replication.ReadFilerSignature(grpcDialOptionB, filerB) + bFilerSignature, bFilerDigest, bFilerErr := replication.ReadFilerSignature(grpcDialOptionB, filerB, tokenSourceB) if bFilerErr != nil { glog.Errorf("get filer 'b' signature %d error from %s to %s: %v", bFilerSignature, *syncOptions.filerA, *syncOptions.filerB, bFilerErr) return true @@ -230,7 +233,7 @@ func runFilerSynchronize(cmd *Command, args []string) bool { if offsetTsNs == 0 { return } - if err := setOffset(state.grpcDialOption, state.targetFiler, getSignaturePrefixByPath(state.sourcePath, state.targetPath), state.sourceFilerSignature, offsetTsNs); err != nil { + if err := setOffset(state.grpcDialOption, state.targetFiler, state.tokenSource, getSignaturePrefixByPath(state.sourcePath, state.targetPath), state.sourceFilerSignature, offsetTsNs); err != nil { glog.Errorf("failed to save checkpoint for %s on shutdown: %v", name, err) } else { glog.V(0).Infof("saved checkpoint for %s on shutdown: %v", name, time.Unix(0, offsetTsNs)) @@ -244,7 +247,7 @@ func runFilerSynchronize(cmd *Command, args []string) bool { go func() { // a->b // set synchronization start timestamp to offset - initOffsetError := initOffsetFromTsMs(grpcDialOptionB, filerB, aFilerSignature, *syncOptions.aFromTsMs, getSignaturePrefixByPath(*syncOptions.aPath, *syncOptions.bPath)) + initOffsetError := initOffsetFromTsMs(grpcDialOptionB, filerB, tokenSourceB, aFilerSignature, *syncOptions.aFromTsMs, getSignaturePrefixByPath(*syncOptions.aPath, *syncOptions.bPath)) if initOffsetError != nil { glog.Errorf("init offset from timestamp %d error from %s to %s: %v", *syncOptions.aFromTsMs, *syncOptions.filerA, *syncOptions.filerB, initOffsetError) os.Exit(2) @@ -277,7 +280,9 @@ func runFilerSynchronize(cmd *Command, args []string) bool { httpClientA, httpClientB, jwtForFilerA, - jwtForFilerB) + jwtForFilerB, + tokenSourceA, + tokenSourceB) if err != nil { glog.Errorf("sync from %s to %s: %v", *syncOptions.filerA, *syncOptions.filerB, err) time.Sleep(1747 * time.Millisecond) @@ -288,7 +293,7 @@ func runFilerSynchronize(cmd *Command, args []string) bool { if !*syncOptions.isActivePassive { // b->a // set synchronization start timestamp to offset - initOffsetError := initOffsetFromTsMs(grpcDialOptionA, filerA, bFilerSignature, *syncOptions.bFromTsMs, getSignaturePrefixByPath(*syncOptions.bPath, *syncOptions.aPath)) + initOffsetError := initOffsetFromTsMs(grpcDialOptionA, filerA, tokenSourceA, bFilerSignature, *syncOptions.bFromTsMs, getSignaturePrefixByPath(*syncOptions.bPath, *syncOptions.aPath)) if initOffsetError != nil { glog.Errorf("init offset from timestamp %d error from %s to %s: %v", *syncOptions.bFromTsMs, *syncOptions.filerB, *syncOptions.filerA, initOffsetError) os.Exit(2) @@ -322,7 +327,9 @@ func runFilerSynchronize(cmd *Command, args []string) bool { httpClientB, httpClientA, jwtForFilerB, - jwtForFilerA) + jwtForFilerA, + tokenSourceB, + tokenSourceA) if err != nil { glog.Errorf("sync from %s to %s: %v", *syncOptions.filerB, *syncOptions.filerA, err) time.Sleep(2147 * time.Millisecond) @@ -335,14 +342,14 @@ func runFilerSynchronize(cmd *Command, args []string) bool { } // initOffsetFromTsMs Initialize offset -func initOffsetFromTsMs(grpcDialOption grpc.DialOption, targetFiler pb.ServerAddress, sourceFilerSignature int32, fromTsMs int64, signaturePrefix string) error { +func initOffsetFromTsMs(grpcDialOption grpc.DialOption, targetFiler pb.ServerAddress, tokenSource security.FilerTokenSource, sourceFilerSignature int32, fromTsMs int64, signaturePrefix string) error { if fromTsMs <= 0 { return nil } // convert to nanosecond fromTsNs := fromTsMs * 1000_000 // If not successful, exit the program. - setOffsetErr := setOffset(grpcDialOption, targetFiler, signaturePrefix, sourceFilerSignature, fromTsNs) + setOffsetErr := setOffset(grpcDialOption, targetFiler, tokenSource, signaturePrefix, sourceFilerSignature, fromTsNs) if setOffsetErr != nil { return setOffsetErr } @@ -353,14 +360,15 @@ func initOffsetFromTsMs(grpcDialOption grpc.DialOption, targetFiler pb.ServerAdd func doSubscribeFilerMetaChanges(clientId int32, clientEpoch int32, sourceGrpcDialOption grpc.DialOption, sourceFiler pb.ServerAddress, sourcePath string, sourceExcludePaths []string, sourceReadChunkFromFiler bool, targetGrpcDialOption grpc.DialOption, targetFiler pb.ServerAddress, targetPath string, replicationStr, collection string, ttlSec int, sinkWriteChunkByFiler bool, diskType string, debug bool, concurrency int, chunkConcurrency int, doDeleteFiles bool, sourceFilerSignature int32, targetFilerSignature int32, statePtr *atomic.Pointer[syncState], sourceHttpClient *util_http_client.HTTPClient, sinkHttpClient *util_http_client.HTTPClient, - sourceJwtProvider security.FilerJwtProvider, sinkJwtProvider security.FilerJwtProvider) error { + sourceJwtProvider security.FilerJwtProvider, sinkJwtProvider security.FilerJwtProvider, + sourceTokenSource security.FilerTokenSource, sinkTokenSource security.FilerTokenSource) error { // if first time, start from now // if has previously synced, resume from that point of time // the historical key ignored the target path; falling back to it lets a // sync that predates target-scoped keys survive the upgrade signaturePrefix := getSignaturePrefixByPath(sourcePath, targetPath) - sourceFilerOffsetTsNs, err := getOffsetWithFallback(targetGrpcDialOption, targetFiler, signaturePrefix, sourceFilerSignature, getSignaturePrefixByPath(sourcePath, "/"), sourceFilerSignature) + sourceFilerOffsetTsNs, err := getOffsetWithFallback(targetGrpcDialOption, targetFiler, sinkTokenSource, signaturePrefix, sourceFilerSignature, getSignaturePrefixByPath(sourcePath, "/"), sourceFilerSignature) if err != nil { return err } @@ -377,6 +385,7 @@ func doSubscribeFilerMetaChanges(clientId int32, clientEpoch int32, sourceGrpcDi if sourceJwtProvider != nil { filerSource.SetFilerJwtProvider(sourceJwtProvider) } + filerSource.SetFilerTokenSource(sourceTokenSource) filerSink := &filersink.FilerSink{} filerSink.DoInitialize(targetFiler.ToHttpAddress(), targetFiler.ToGrpcAddress(), targetPath, replicationStr, collection, ttlSec, diskType, targetGrpcDialOption, sinkWriteChunkByFiler) filerSink.SetChunkConcurrency(chunkConcurrency) @@ -386,6 +395,7 @@ func doSubscribeFilerMetaChanges(clientId int32, clientEpoch int32, sourceGrpcDi if sinkJwtProvider != nil { filerSink.SetFilerJwtProvider(sinkJwtProvider) } + filerSink.SetFilerTokenSource(sinkTokenSource) filerSink.SetSourceFiler(filerSource) persistEventFn := genProcessFunction(sourcePath, targetPath, sourceExcludePaths, nil, nil, nil, filerSink, doDeleteFiles, debug) @@ -418,6 +428,7 @@ func doSubscribeFilerMetaChanges(clientId int32, clientEpoch int32, sourceGrpcDi sourcePath: sourcePath, targetPath: targetPath, sourceFilerSignature: sourceFilerSignature, + tokenSource: sinkTokenSource, }) } @@ -479,7 +490,7 @@ func doSubscribeFilerMetaChanges(clientId int32, clientEpoch int32, sourceGrpcDi lastProgressedTsNs = offsetTsNs // collect synchronous offset statsCollect.FilerSyncOffsetGauge.WithLabelValues(sourceFiler.String(), targetFiler.String(), clientName, sourcePath).Set(float64(offsetTsNs)) - return setOffset(targetGrpcDialOption, targetFiler, signaturePrefix, sourceFilerSignature, resumeTsNsFor(processor)) + return setOffset(targetGrpcDialOption, targetFiler, sinkTokenSource, signaturePrefix, sourceFilerSignature, resumeTsNsFor(processor)) }) prefix := sourcePath @@ -499,6 +510,7 @@ func doSubscribeFilerMetaChanges(clientId int32, clientEpoch int32, sourceGrpcDi StopTsNs: 0, EventErrorType: pb.RetryForeverOnError, FilerJwtProvider: sourceJwtProvider, + FilerTokenSource: sourceTokenSource, GetResumeTsNs: func() int64 { return resumeTsNsFor(processor) }, @@ -540,9 +552,9 @@ func getSignaturePrefixByPath(sourcePath, targetPath string) string { return prefix } -func getOffset(grpcDialOption grpc.DialOption, filer pb.ServerAddress, signaturePrefix string, signature int32) (lastOffsetTsNs int64, readErr error) { +func getOffset(grpcDialOption grpc.DialOption, filer pb.ServerAddress, tokenSource security.FilerTokenSource, signaturePrefix string, signature int32) (lastOffsetTsNs int64, readErr error) { - readErr = pb.WithFilerClient(false, signature, filer, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + readErr = pb.WithGrpcFilerClient(false, signature, filer, grpcDialOption, tokenSource, func(client filer_pb.SeaweedFilerClient) error { syncKey := []byte(signaturePrefix + "____") util.Uint32toBytes(syncKey[len(signaturePrefix):len(signaturePrefix)+4], uint32(signature)) @@ -573,10 +585,10 @@ func getOffset(grpcDialOption grpc.DialOption, filer pb.ServerAddress, signature // instead of replaying from zero. Writes must go only to the current key: // keeping the historical key warm would re-create the very sharing between // streams that a key-scheme change separates. -func getOffsetWithFallback(grpcDialOption grpc.DialOption, filer pb.ServerAddress, signaturePrefix string, signature int32, legacySignaturePrefix string, legacySignature int32) (int64, error) { - lastOffsetTsNs, err := getOffset(grpcDialOption, filer, signaturePrefix, signature) +func getOffsetWithFallback(grpcDialOption grpc.DialOption, filer pb.ServerAddress, tokenSource security.FilerTokenSource, signaturePrefix string, signature int32, legacySignaturePrefix string, legacySignature int32) (int64, error) { + lastOffsetTsNs, err := getOffset(grpcDialOption, filer, tokenSource, signaturePrefix, signature) if err == nil && lastOffsetTsNs == 0 { - lastOffsetTsNs, err = getOffset(grpcDialOption, filer, legacySignaturePrefix, legacySignature) + lastOffsetTsNs, err = getOffset(grpcDialOption, filer, tokenSource, legacySignaturePrefix, legacySignature) } return lastOffsetTsNs, err } @@ -622,7 +634,7 @@ func resumeTsNsFor(p *MetadataProcessor) int64 { // lands late can be told apart from the fresher write it would shadow. var offsetWriteSeq atomic.Int64 -func setOffset(grpcDialOption grpc.DialOption, filer pb.ServerAddress, signaturePrefix string, signature int32, offsetTsNs int64) error { +func setOffset(grpcDialOption grpc.DialOption, filer pb.ServerAddress, tokenSource security.FilerTokenSource, signaturePrefix string, signature int32, offsetTsNs int64) error { syncKey := []byte(signaturePrefix + "____") util.Uint32toBytes(syncKey[len(signaturePrefix):len(signaturePrefix)+4], uint32(signature)) key := string(filer) + "\x00" + string(syncKey) @@ -643,7 +655,7 @@ func setOffset(grpcDialOption grpc.DialOption, filer pb.ServerAddress, signature } checkpoint.lastSeq = seq - return pb.WithFilerClient(false, signature, filer, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + return pb.WithGrpcFilerClient(false, signature, filer, grpcDialOption, tokenSource, func(client filer_pb.SeaweedFilerClient) error { valueBuf := make([]byte, 8) util.Uint64toBytes(valueBuf, uint64(offsetTsNs)) diff --git a/weed/command/filer_sync_offset_test.go b/weed/command/filer_sync_offset_test.go index 93caf23e5c..812cc5d1c2 100644 --- a/weed/command/filer_sync_offset_test.go +++ b/weed/command/filer_sync_offset_test.go @@ -60,21 +60,21 @@ func TestSyncOffset_HistoricalFallbackThenIndependence(t *testing.T) { prefixB := getSignaturePrefixByPath("/data", "/backup-b") // pre-upgrade state: both syncs shared the historical key - if err := setOffset(dial, filerAddr, historical, sourceSig, 111); err != nil { + if err := setOffset(dial, filerAddr, nil, historical, sourceSig, 111); err != nil { t.Fatalf("seed historical offset: %v", err) } - if got, err := getOffsetWithFallback(dial, filerAddr, prefixA, sourceSig, historical, sourceSig); err != nil || got != 111 { + if got, err := getOffsetWithFallback(dial, filerAddr, nil, prefixA, sourceSig, historical, sourceSig); err != nil || got != 111 { t.Fatalf("A fallback read = (%d, %v), want (111, nil)", got, err) } // A checkpoints under its own key; B still resumes from the historical one - if err := setOffset(dial, filerAddr, prefixA, sourceSig, 222); err != nil { + if err := setOffset(dial, filerAddr, nil, prefixA, sourceSig, 222); err != nil { t.Fatalf("write A offset: %v", err) } - if got, err := getOffsetWithFallback(dial, filerAddr, prefixA, sourceSig, historical, sourceSig); err != nil || got != 222 { + if got, err := getOffsetWithFallback(dial, filerAddr, nil, prefixA, sourceSig, historical, sourceSig); err != nil || got != 222 { t.Fatalf("A read = (%d, %v), want (222, nil)", got, err) } - if got, err := getOffsetWithFallback(dial, filerAddr, prefixB, sourceSig, historical, sourceSig); err != nil || got != 111 { + if got, err := getOffsetWithFallback(dial, filerAddr, nil, prefixB, sourceSig, historical, sourceSig); err != nil || got != 111 { t.Fatalf("B read = (%d, %v), want (111, nil)", got, err) } } @@ -88,7 +88,7 @@ func TestSyncOffset_StaleWriteDropped(t *testing.T) { prefix := getSignaturePrefixByPath("/data", "/backup-stale") sourceSig := int32(77) - if err := setOffset(dial, filerAddr, prefix, sourceSig, 300); err != nil { + if err := setOffset(dial, filerAddr, nil, prefix, sourceSig, 300); err != nil { t.Fatalf("seed offset: %v", err) } @@ -107,10 +107,10 @@ func TestSyncOffset_StaleWriteDropped(t *testing.T) { checkpoint.lastSeq = offsetWriteSeq.Load() + 1000 checkpoint.Unlock() - if err := setOffset(dial, filerAddr, prefix, sourceSig, 100); err != nil { + if err := setOffset(dial, filerAddr, nil, prefix, sourceSig, 100); err != nil { t.Fatalf("stale write: %v", err) } - if got, err := getOffset(dial, filerAddr, prefix, sourceSig); err != nil || got != 300 { + if got, err := getOffset(dial, filerAddr, nil, prefix, sourceSig); err != nil || got != 300 { t.Fatalf("after stale write = (%d, %v), want (300, nil)", got, err) } @@ -118,10 +118,10 @@ func TestSyncOffset_StaleWriteDropped(t *testing.T) { checkpoint.Lock() checkpoint.lastSeq = 0 checkpoint.Unlock() - if err := setOffset(dial, filerAddr, prefix, sourceSig, 199); err != nil { + if err := setOffset(dial, filerAddr, nil, prefix, sourceSig, 199); err != nil { t.Fatalf("floored write: %v", err) } - if got, err := getOffset(dial, filerAddr, prefix, sourceSig); err != nil || got != 199 { + if got, err := getOffset(dial, filerAddr, nil, prefix, sourceSig); err != nil || got != 199 { t.Fatalf("after floored write = (%d, %v), want (199, nil)", got, err) } } diff --git a/weed/command/filer_sync_verify.go b/weed/command/filer_sync_verify.go index 378103f8e9..3fc00a93e2 100644 --- a/weed/command/filer_sync_verify.go +++ b/weed/command/filer_sync_verify.go @@ -89,6 +89,8 @@ func runFilerSyncVerify(cmd *Command, args []string) bool { glog.Fatalf("load security config for filer B: %v", err) } } + tokenSourceA := security.FilerAdminTokenFromFile(*syncVerifyOptions.aSecurity) + tokenSourceB := security.FilerAdminTokenFromFile(*syncVerifyOptions.bSecurity) filerA := pb.ServerAddress(*syncVerifyOptions.filerA) filerB := pb.ServerAddress(*syncVerifyOptions.filerB) @@ -96,7 +98,7 @@ func runFilerSyncVerify(cmd *Command, args []string) bool { if err := runVerifySync(filerA, filerB, *syncVerifyOptions.aPath, *syncVerifyOptions.bPath, *syncVerifyOptions.isActivePassive, *syncVerifyOptions.modifiedTimeAgo, *syncVerifyOptions.jsonOutput, - grpcDialOptionA, grpcDialOptionB); err != nil { + grpcDialOptionA, grpcDialOptionB, tokenSourceA, tokenSourceB); err != nil { glog.Errorf("verify sync: %v", err) os.Exit(2) } @@ -184,13 +186,13 @@ type summaryRecord struct { type simpleFilerClient struct { grpcAddress pb.ServerAddress grpcDialOption grpc.DialOption + tokenSource security.FilerTokenSource } func (c *simpleFilerClient) WithFilerClient(streamingMode bool, fn func(filer_pb.SeaweedFilerClient) error) error { - return pb.WithGrpcClient(context.Background(), streamingMode, 0, func(grpcConnection *grpc.ClientConn) error { - client := filer_pb.NewSeaweedFilerClient(grpcConnection) + return pb.WithGrpcFilerClient(streamingMode, 0, c.grpcAddress, c.grpcDialOption, c.tokenSource, func(client filer_pb.SeaweedFilerClient) error { return fn(client) - }, c.grpcAddress.ToGrpcAddress(), false, c.grpcDialOption) + }) } func (c *simpleFilerClient) AdjustedUrl(location *filer_pb.Location) string { @@ -204,10 +206,11 @@ func (c *simpleFilerClient) GetDataCenter() string { func runVerifySync(filerA, filerB pb.ServerAddress, aPath, bPath string, isActivePassive bool, modifiedTimeAgo time.Duration, jsonOutput bool, - grpcDialOptionA, grpcDialOptionB grpc.DialOption) error { + grpcDialOptionA, grpcDialOptionB grpc.DialOption, + tokenSourceA, tokenSourceB security.FilerTokenSource) error { - clientA := &simpleFilerClient{grpcAddress: filerA, grpcDialOption: grpcDialOptionA} - clientB := &simpleFilerClient{grpcAddress: filerB, grpcDialOption: grpcDialOptionB} + clientA := &simpleFilerClient{grpcAddress: filerA, grpcDialOption: grpcDialOptionA, tokenSource: tokenSourceA} + clientB := &simpleFilerClient{grpcAddress: filerB, grpcDialOption: grpcDialOptionB, tokenSource: tokenSourceB} var cutoffTime time.Time if modifiedTimeAgo > 0 { diff --git a/weed/command/iam.go b/weed/command/iam.go index 2ccc2bc9a9..fa68701169 100644 --- a/weed/command/iam.go +++ b/weed/command/iam.go @@ -89,7 +89,7 @@ func (iamopt *IamOptions) startIamServer() bool { grpcDialOption := security.LoadClientTLS(util.GetViper(), "grpc.client") var digest string for { - err := pb.WithOneOfGrpcFilerClients(false, filerAddresses, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + err := pb.WithOneOfGrpcFilerClients(false, filerAddresses, grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error { resp, err := client.GetFilerConfiguration(context.Background(), &filer_pb.GetFilerConfigurationRequest{}) if err != nil { return fmt.Errorf("get filer configuration: %v", err) diff --git a/weed/command/mini.go b/weed/command/mini.go index 2bdec985b2..03a819a38d 100644 --- a/weed/command/mini.go +++ b/weed/command/mini.go @@ -2474,7 +2474,7 @@ func ensureMiniBuckets(bucketSpec string) error { // Derive from miniClientsCtx so Ctrl+C cancels the bucket RPCs, and bound // with a short timeout (per bucket) so a stalled filer cannot block the // welcome message indefinitely. - return pb.WithGrpcFilerClient(false, 0, filerAddress, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + return pb.WithGrpcFilerClient(false, 0, filerAddress, grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error { for _, name := range names { if err := s3bucket.VerifyS3BucketName(name); err != nil { glog.Warningf("invalid bucket name %q: %v", name, err) @@ -2552,7 +2552,7 @@ func createMiniTableBuckets(servable []tableBucketEntry) ([]tableBucketEntry, er grpcDialOption := security.LoadClientTLS(util.GetViper(), "grpc.client") var ready []tableBucketEntry - err := pb.WithGrpcFilerClient(false, 0, filerAddress, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + err := pb.WithGrpcFilerClient(false, 0, filerAddress, grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error { manager := s3tables.NewManager() mgrClient := s3tables.NewManagerClient(client) for _, bucket := range servable { diff --git a/weed/command/mount_common.go b/weed/command/mount_common.go index 8c6839a7c8..457cfc6fc4 100644 --- a/weed/command/mount_common.go +++ b/weed/command/mount_common.go @@ -149,7 +149,7 @@ func connectToFiler(option *MountOptions) (filerAddresses []pb.ServerAddress, gr var err error var digest string for i := 0; i < 10; i++ { - err = pb.WithOneOfGrpcFilerClients(false, filerAddresses, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + err = pb.WithOneOfGrpcFilerClients(false, filerAddresses, grpcDialOption, nil, func(client filer_pb.SeaweedFilerClient) error { resp, err := client.GetFilerConfiguration(context.Background(), &filer_pb.GetFilerConfigurationRequest{}) if err != nil { return fmt.Errorf("get filer grpc address %v configuration: %w", filerAddresses, err) diff --git a/weed/command/s3.go b/weed/command/s3.go index 25164458f3..7e6628d260 100644 --- a/weed/command/s3.go +++ b/weed/command/s3.go @@ -328,7 +328,7 @@ func (s3opt *S3Options) startS3Server() bool { var filerDigest string for { - err := pb.WithOneOfGrpcFilerClients(false, filerAddresses, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + err := pb.WithOneOfGrpcFilerClients(false, filerAddresses, grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error { resp, err := client.GetFilerConfiguration(context.Background(), &filer_pb.GetFilerConfigurationRequest{}) if err != nil { return fmt.Errorf("get filer configuration: %v", err) diff --git a/weed/command/sftp.go b/weed/command/sftp.go index 38ccfb20e4..e4464b78d5 100644 --- a/weed/command/sftp.go +++ b/weed/command/sftp.go @@ -137,7 +137,7 @@ func (sftpOpt *SftpOptions) startSftpServer() bool { // Connect to the filer service and try to retrieve basic configuration. for { - err := pb.WithGrpcFilerClient(false, 0, filerAddress, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + err := pb.WithGrpcFilerClient(false, 0, filerAddress, grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error { resp, err := client.GetFilerConfiguration(context.Background(), &filer_pb.GetFilerConfigurationRequest{}) if err != nil { return fmt.Errorf("get filer %s configuration: %v", filerAddress, err) diff --git a/weed/command/shell.go b/weed/command/shell.go index f0aa1a30a7..5698d2d0f6 100644 --- a/weed/command/shell.go +++ b/weed/command/shell.go @@ -44,6 +44,7 @@ func runShell(command *Command, args []string) bool { util.LoadSecurityConfiguration() shellOptions.GrpcDialOption = security.LoadClientTLS(util.GetViper(), "grpc.client") + shellOptions.FilerTokenSource = security.FilerAdminToken shellOptions.Directory = "/" util.LoadConfiguration("shell", false) diff --git a/weed/command/webdav.go b/weed/command/webdav.go index a6576fc8b6..d49d0b0e22 100644 --- a/weed/command/webdav.go +++ b/weed/command/webdav.go @@ -118,7 +118,7 @@ func (wo *WebDavOption) startWebDav() bool { var digest string // connect to filer for { - err := pb.WithGrpcFilerClient(false, 0, filerAddress, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + err := pb.WithGrpcFilerClient(false, 0, filerAddress, grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error { resp, err := client.GetFilerConfiguration(context.Background(), &filer_pb.GetFilerConfigurationRequest{}) if err != nil { return fmt.Errorf("get filer %s configuration: %v", filerAddress, err) diff --git a/weed/credential/filer_etc/filer_etc_policy_test.go b/weed/credential/filer_etc/filer_etc_policy_test.go index ace971bc8f..465eb3658a 100644 --- a/weed/credential/filer_etc/filer_etc_policy_test.go +++ b/weed/credential/filer_etc/filer_etc_policy_test.go @@ -5,6 +5,7 @@ import ( "net" "sort" "strconv" + "strings" "sync" "testing" "time" @@ -14,11 +15,13 @@ import ( "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/pb/iam_pb" "github.com/seaweedfs/seaweedfs/weed/s3api/policy_engine" + "github.com/seaweedfs/seaweedfs/weed/security" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" "google.golang.org/protobuf/proto" ) @@ -34,6 +37,68 @@ type policyTestFilerServer struct { beforeUpdate func(string, string) error } +const filerEtcAuthTestKey = "filer-etc-auth-test-key-32-bytes-long" + +func TestFilerEtcStoreUsesPerCallAdminToken(t *testing.T) { + t.Setenv("WEED_JWT_FILER_SIGNING_GRPC_KEY", "") + t.Setenv("WEED_JWT_FILER_SIGNING_KEY", filerEtcAuthTestKey) + + server := newPolicyTestFilerServer() + checkAuth := func(ctx context.Context) error { + md, _ := metadata.FromIncomingContext(ctx) + values := md.Get("authorization") + if len(values) != 1 || !strings.HasPrefix(values[0], security.BearerPrefix) { + return status.Error(codes.Unauthenticated, "missing filer admin token") + } + token := security.EncodedJwt(strings.TrimPrefix(values[0], security.BearerPrefix)) + if !security.IsFilerAdminToken(security.SigningKey(filerEtcAuthTestKey), token) { + return status.Error(codes.Unauthenticated, "invalid filer admin token") + } + return nil + } + grpcServer := grpc.NewServer( + grpc.UnaryInterceptor(func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { + if err := checkAuth(ctx); err != nil { + return nil, err + } + return handler(ctx, req) + }), + grpc.StreamInterceptor(func(srv any, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { + if err := checkAuth(stream.Context()); err != nil { + return err + } + return handler(srv, stream) + }), + ) + filer_pb.RegisterSeaweedFilerServer(grpcServer, server) + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + go func() { _ = grpcServer.Serve(listener) }() + t.Cleanup(func() { + grpcServer.Stop() + _ = listener.Close() + }) + + host, portString, err := net.SplitHostPort(listener.Addr().String()) + if err != nil { + t.Fatal(err) + } + grpcPort, err := strconv.Atoi(portString) + if err != nil { + t.Fatal(err) + } + store := &FilerEtcStore{} + store.SetFilerAddressFunc(func() pb.ServerAddress { + return pb.NewServerAddress(host, 1, grpcPort) + }, grpc.WithTransportCredentials(insecure.NewCredentials())) + + if _, err := store.ListPolicyNames(context.Background()); err != nil { + t.Fatalf("ListPolicyNames: %v", err) + } +} + func newPolicyTestFilerServer() *policyTestFilerServer { return &policyTestFilerServer{ entries: make(map[string]*filer_pb.Entry), diff --git a/weed/credential/filer_etc/filer_etc_store.go b/weed/credential/filer_etc/filer_etc_store.go index ceb15b82f3..71aeb0b3ef 100644 --- a/weed/credential/filer_etc/filer_etc_store.go +++ b/weed/credential/filer_etc/filer_etc_store.go @@ -7,6 +7,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/credential" "github.com/seaweedfs/seaweedfs/weed/pb" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/security" "github.com/seaweedfs/seaweedfs/weed/util" "google.golang.org/grpc" ) @@ -71,7 +72,7 @@ func (store *FilerEtcStore) withFilerClient(fn func(client filer_pb.SeaweedFiler } // Use the pb.WithGrpcFilerClient helper similar to existing code - return pb.WithGrpcFilerClient(false, 0, filerAddress, dialOption, fn) + return pb.WithGrpcFilerClient(false, 0, filerAddress, dialOption, security.FilerAdminToken, fn) } func (store *FilerEtcStore) Shutdown() { diff --git a/weed/filer/filer_conf.go b/weed/filer/filer_conf.go index b61936f0a5..edc82c433a 100644 --- a/weed/filer/filer_conf.go +++ b/weed/filer/filer_conf.go @@ -15,6 +15,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/glog" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/security" "github.com/seaweedfs/seaweedfs/weed/util" "github.com/viant/ptrie" jsonpb "google.golang.org/protobuf/encoding/protojson" @@ -42,14 +43,20 @@ type FilerConf struct { rules ptrie.Trie[*filer_pb.FilerConf_PathConf] } -func ReadFilerConf(filerGrpcAddress pb.ServerAddress, grpcDialOption grpc.DialOption, masterClient *wdclient.MasterClient) (*FilerConf, error) { - return ReadFilerConfFromFilers([]pb.ServerAddress{filerGrpcAddress}, grpcDialOption, masterClient) +func ReadFilerConf(filerGrpcAddress pb.ServerAddress, grpcDialOption grpc.DialOption, masterClient *wdclient.MasterClient, tokenSource ...security.FilerTokenSource) (*FilerConf, error) { + return ReadFilerConfFromFilers([]pb.ServerAddress{filerGrpcAddress}, grpcDialOption, masterClient, tokenSource...) } -// ReadFilerConfFromFilers reads filer configuration with multi-filer failover support -func ReadFilerConfFromFilers(filerGrpcAddresses []pb.ServerAddress, grpcDialOption grpc.DialOption, masterClient *wdclient.MasterClient) (*FilerConf, error) { +// ReadFilerConfFromFilers reads filer configuration with multi-filer failover support. +// An optional token source authenticates the logical client per RPC; nil keeps +// the existing anonymous behavior for callers that do not hold a filer key. +func ReadFilerConfFromFilers(filerGrpcAddresses []pb.ServerAddress, grpcDialOption grpc.DialOption, masterClient *wdclient.MasterClient, tokenSource ...security.FilerTokenSource) (*FilerConf, error) { var data []byte - if err := pb.WithOneOfGrpcFilerClients(false, filerGrpcAddresses, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + var source security.FilerTokenSource + if len(tokenSource) > 0 { + source = tokenSource[0] + } + if err := pb.WithOneOfGrpcFilerClients(false, filerGrpcAddresses, grpcDialOption, source, func(client filer_pb.SeaweedFilerClient) error { if masterClient != nil { var buf bytes.Buffer if err := ReadEntry(masterClient, client, DirectoryEtcSeaweedFS, FilerConfName, &buf); err != nil { diff --git a/weed/filer/remote_mapping.go b/weed/filer/remote_mapping.go index 359fc44637..0812fec2d5 100644 --- a/weed/filer/remote_mapping.go +++ b/weed/filer/remote_mapping.go @@ -8,6 +8,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/pb" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/pb/remote_pb" + "github.com/seaweedfs/seaweedfs/weed/security" "google.golang.org/grpc" "google.golang.org/protobuf/proto" ) @@ -27,9 +28,9 @@ func FindMountedRemoteMapping(mappings *remote_pb.RemoteStorageMapping, dir stri return } -func ReadMountMappings(grpcDialOption grpc.DialOption, filerAddress pb.ServerAddress) (mappings *remote_pb.RemoteStorageMapping, readErr error) { +func ReadMountMappings(grpcDialOption grpc.DialOption, filerAddress pb.ServerAddress, tokenSource ...security.FilerTokenSource) (mappings *remote_pb.RemoteStorageMapping, readErr error) { var oldContent []byte - if readErr = pb.WithFilerClient(false, 0, filerAddress, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + if readErr = pb.WithGrpcFilerClient(false, 0, filerAddress, grpcDialOption, firstTokenSource(tokenSource), func(client filer_pb.SeaweedFilerClient) error { oldContent, readErr = ReadInsideFiler(context.Background(), client, DirectoryEtcRemote, REMOTE_STORAGE_MOUNT_FILE) return readErr }); readErr != nil { @@ -46,6 +47,13 @@ func ReadMountMappings(grpcDialOption grpc.DialOption, filerAddress pb.ServerAdd return } +func firstTokenSource(sources []security.FilerTokenSource) security.FilerTokenSource { + if len(sources) == 0 { + return nil + } + return sources[0] +} + func InsertMountMapping(filerClient filer_pb.FilerClient, dir string, remoteStorageLocation *remote_pb.RemoteStorageLocation) (err error) { // read current mapping diff --git a/weed/filer/remote_mapping_auth_test.go b/weed/filer/remote_mapping_auth_test.go new file mode 100644 index 0000000000..00d3977d90 --- /dev/null +++ b/weed/filer/remote_mapping_auth_test.go @@ -0,0 +1,87 @@ +package filer + +import ( + "context" + "crypto/rand" + "encoding/hex" + "net" + "strings" + "testing" + + "github.com/seaweedfs/seaweedfs/weed/pb" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/pb/remote_pb" + "github.com/seaweedfs/seaweedfs/weed/security" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" +) + +type remoteMappingAuthFiler struct { + filer_pb.UnimplementedSeaweedFilerServer + key security.SigningKey + content []byte +} + +func (s *remoteMappingAuthFiler) LookupDirectoryEntry(_ context.Context, _ *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) { + return &filer_pb.LookupDirectoryEntryResponse{Entry: &filer_pb.Entry{Content: s.content}}, nil +} + +func remoteMappingAuthKey(t *testing.T) security.SigningKey { + t.Helper() + buf := make([]byte, 32) + if _, err := rand.Read(buf); err != nil { + t.Fatal(err) + } + return security.SigningKey(hex.EncodeToString(buf)) +} + +func startRemoteMappingAuthFiler(t *testing.T, filer *remoteMappingAuthFiler) (pb.ServerAddress, grpc.DialOption) { + t.Helper() + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + server := grpc.NewServer(grpc.UnaryInterceptor(func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { + md, _ := metadata.FromIncomingContext(ctx) + values := md.Get("authorization") + if len(values) != 1 || !strings.HasPrefix(values[0], security.BearerPrefix) || + !security.IsFilerAdminToken(filer.key, security.EncodedJwt(strings.TrimPrefix(values[0], security.BearerPrefix))) { + return nil, status.Error(codes.Unauthenticated, "missing or invalid filer authorization") + } + return handler(ctx, req) + })) + filer_pb.RegisterSeaweedFilerServer(server, filer) + go func() { _ = server.Serve(listener) }() + t.Cleanup(func() { + server.Stop() + _ = listener.Close() + }) + port := listener.Addr().(*net.TCPAddr).Port + return pb.NewServerAddressWithGrpcPort("127.0.0.1:8888", port), grpc.WithTransportCredentials(insecure.NewCredentials()) +} + +func TestReadMountMappingsUsesProtectedFilerCall(t *testing.T) { + key := remoteMappingAuthKey(t) + content, err := proto.Marshal(&remote_pb.RemoteStorageMapping{Mappings: map[string]*remote_pb.RemoteStorageLocation{ + "/buckets/archive": {Name: "archive", Bucket: "bucket"}, + }}) + if err != nil { + t.Fatal(err) + } + filer := &remoteMappingAuthFiler{key: key, content: content} + address, dial := startRemoteMappingAuthFiler(t, filer) + tokenSource := security.FilerTokenSource(func(context.Context) (security.EncodedJwt, error) { + return security.GenJwtForFilerAdmin(key, 60), nil + }) + mappings, err := ReadMountMappings(dial, address, tokenSource) + if err != nil { + t.Fatalf("read protected mount mappings: %v", err) + } + if got := mappings.Mappings["/buckets/archive"].Bucket; got != "bucket" { + t.Fatalf("mount mapping bucket = %q, want bucket", got) + } +} diff --git a/weed/filer/remote_storage.go b/weed/filer/remote_storage.go index 1ea416ab41..0d300f4c9b 100644 --- a/weed/filer/remote_storage.go +++ b/weed/filer/remote_storage.go @@ -16,6 +16,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/glog" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/security" "github.com/viant/ptrie" ) @@ -247,9 +248,9 @@ func UnmarshalRemoteStorageMappings(oldContent []byte) (mappings *remote_pb.Remo return } -func ReadRemoteStorageConf(grpcDialOption grpc.DialOption, filerAddress pb.ServerAddress, storageName string) (conf *remote_pb.RemoteConf, readErr error) { +func ReadRemoteStorageConf(grpcDialOption grpc.DialOption, filerAddress pb.ServerAddress, storageName string, tokenSource ...security.FilerTokenSource) (conf *remote_pb.RemoteConf, readErr error) { var oldContent []byte - if readErr = pb.WithFilerClient(false, 0, filerAddress, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + if readErr = pb.WithGrpcFilerClient(false, 0, filerAddress, grpcDialOption, firstTokenSource(tokenSource), func(client filer_pb.SeaweedFilerClient) error { oldContent, readErr = ReadInsideFiler(context.Background(), client, DirectoryEtcRemote, storageName+REMOTE_STORAGE_CONF_SUFFIX) return readErr }); readErr != nil { @@ -266,9 +267,9 @@ func ReadRemoteStorageConf(grpcDialOption grpc.DialOption, filerAddress pb.Serve return } -func DetectMountInfo(grpcDialOption grpc.DialOption, filerAddress pb.ServerAddress, dir string) (*remote_pb.RemoteStorageMapping, string, *remote_pb.RemoteStorageLocation, *remote_pb.RemoteConf, error) { +func DetectMountInfo(grpcDialOption grpc.DialOption, filerAddress pb.ServerAddress, dir string, tokenSource ...security.FilerTokenSource) (*remote_pb.RemoteStorageMapping, string, *remote_pb.RemoteStorageLocation, *remote_pb.RemoteConf, error) { - mappings, listErr := ReadMountMappings(grpcDialOption, filerAddress) + mappings, listErr := ReadMountMappings(grpcDialOption, filerAddress, tokenSource...) if listErr != nil { return nil, "", nil, nil, listErr } @@ -282,7 +283,7 @@ func DetectMountInfo(grpcDialOption grpc.DialOption, filerAddress pb.ServerAddre } // find remote storage configuration - remoteStorageConf, err := ReadRemoteStorageConf(grpcDialOption, filerAddress, remoteStorageMountedLocation.Name) + remoteStorageConf, err := ReadRemoteStorageConf(grpcDialOption, filerAddress, remoteStorageMountedLocation.Name, tokenSource...) if err != nil { return mappings, localMountedDir, remoteStorageMountedLocation, remoteStorageConf, err } diff --git a/weed/filer_client/filer_client_accessor.go b/weed/filer_client/filer_client_accessor.go index 955a295cca..83b3255286 100644 --- a/weed/filer_client/filer_client_accessor.go +++ b/weed/filer_client/filer_client_accessor.go @@ -12,6 +12,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/pb" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/pb/mq_pb" + "github.com/seaweedfs/seaweedfs/weed/security" "google.golang.org/grpc" ) @@ -53,6 +54,9 @@ func (fh *filerHealth) recordSuccess() { type FilerClientAccessor struct { GetGrpcDialOption func() grpc.DialOption GetFilers func() []pb.ServerAddress // Returns multiple filer addresses for failover + // TokenSource supplies per-call filer authorization for this logical client. + // A nil source preserves the existing anonymous behavior. + TokenSource security.FilerTokenSource // Health tracking for smart failover filerHealthMap sync.Map // map[pb.ServerAddress]*filerHealth @@ -127,7 +131,7 @@ func (fca *FilerClientAccessor) withMultipleFilers(streamingMode bool, fn func(f for _, filerAddress := range healthyFilers { health := fca.getOrCreateFilerHealth(filerAddress) - err := pb.WithFilerClient(streamingMode, 0, filerAddress, fca.GetGrpcDialOption(), fn) + err := pb.WithGrpcFilerClient(streamingMode, 0, filerAddress, fca.GetGrpcDialOption(), fca.TokenSource, fn) if err == nil { // Success - record it and return health.recordSuccess() @@ -148,7 +152,7 @@ func (fca *FilerClientAccessor) withMultipleFilers(streamingMode bool, fn func(f for _, filerAddress := range backoffFilers { health := fca.getOrCreateFilerHealth(filerAddress) - err := pb.WithFilerClient(streamingMode, 0, filerAddress, fca.GetGrpcDialOption(), fn) + err := pb.WithGrpcFilerClient(streamingMode, 0, filerAddress, fca.GetGrpcDialOption(), fca.TokenSource, fn) if err == nil { // Success - record it and return health.recordSuccess() diff --git a/weed/iam/integration/oidc_provider_audit.go b/weed/iam/integration/oidc_provider_audit.go index 80efe0a904..ae0e8e0275 100644 --- a/weed/iam/integration/oidc_provider_audit.go +++ b/weed/iam/integration/oidc_provider_audit.go @@ -12,6 +12,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/glog" "github.com/seaweedfs/seaweedfs/weed/pb" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/security" "github.com/seaweedfs/seaweedfs/weed/util" "google.golang.org/grpc" ) @@ -153,7 +154,7 @@ func (f *FilerAuditSink) Emit(ctx context.Context, event *OIDCProviderAuditEvent arnHash.Write([]byte(event.ARN)) name := fmt.Sprintf("%d-%s-%s.json", event.OccurredAt.UnixNano(), event.Type, hex.EncodeToString(arnHash.Sum(nil)[:8])) occurredAt := event.OccurredAt.Unix() - return pb.WithGrpcFilerClient(false, 0, pb.ServerAddress(addr), f.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + return pb.WithGrpcFilerClient(false, 0, pb.ServerAddress(addr), f.grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error { err := filer_pb.CreateEntry(ctx, client, &filer_pb.CreateEntryRequest{ Directory: f.basePath, Entry: &filer_pb.Entry{ diff --git a/weed/iam/integration/oidc_provider_store.go b/weed/iam/integration/oidc_provider_store.go index bd27e99dd2..9f056a43fb 100644 --- a/weed/iam/integration/oidc_provider_store.go +++ b/weed/iam/integration/oidc_provider_store.go @@ -18,6 +18,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/pb" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants" + "github.com/seaweedfs/seaweedfs/weed/security" "github.com/seaweedfs/seaweedfs/weed/util" "google.golang.org/grpc" "google.golang.org/grpc/codes" @@ -603,7 +604,7 @@ func (f *FilerOIDCProviderStore) deleteProviderEntryIfUnchanged(ctx context.Cont } func (f *FilerOIDCProviderStore) withFilerClient(ctx context.Context, filerAddress string, fn func(filer_pb.SeaweedFilerClient) error) error { - return pb.WithGrpcFilerClient(false, 0, pb.ServerAddress(filerAddress), f.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + return pb.WithGrpcFilerClient(false, 0, pb.ServerAddress(filerAddress), f.grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error { if err := f.names.ensure(ctx, filerAddress, client); err != nil { return err } diff --git a/weed/iam/integration/role_store.go b/weed/iam/integration/role_store.go index 3c2ad6a4d9..d98dffd92b 100644 --- a/weed/iam/integration/role_store.go +++ b/weed/iam/integration/role_store.go @@ -18,6 +18,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/pb" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants" + "github.com/seaweedfs/seaweedfs/weed/security" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" @@ -579,7 +580,7 @@ func (f *FilerRoleStore) withFilerClient(filerAddress string, fn func(filer_pb.S if filerAddress == "" { return fmt.Errorf("filer address is required for FilerRoleStore") } - return pb.WithGrpcFilerClient(false, 0, pb.ServerAddress(filerAddress), f.grpcDialOption, fn) + return pb.WithGrpcFilerClient(false, 0, pb.ServerAddress(filerAddress), f.grpcDialOption, security.FilerAdminToken, fn) } // CachedFilerRoleStore implements RoleStore with TTL caching on top of FilerRoleStore diff --git a/weed/iam/integration/session_revocation.go b/weed/iam/integration/session_revocation.go index 8ad7147c44..f4350f5d06 100644 --- a/weed/iam/integration/session_revocation.go +++ b/weed/iam/integration/session_revocation.go @@ -14,6 +14,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/glog" "github.com/seaweedfs/seaweedfs/weed/pb" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/security" "github.com/seaweedfs/seaweedfs/weed/util" "google.golang.org/grpc" ) @@ -262,7 +263,7 @@ func (f *FilerSessionRevocationStore) Purge(ctx context.Context, filerAddress st } func (f *FilerSessionRevocationStore) withFilerClient(ctx context.Context, filerAddress string, fn func(filer_pb.SeaweedFilerClient) error) error { - return pb.WithGrpcFilerClient(false, 0, pb.ServerAddress(filerAddress), f.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + return pb.WithGrpcFilerClient(false, 0, pb.ServerAddress(filerAddress), f.grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error { if err := f.names.ensure(ctx, filerAddress, client); err != nil { return err } diff --git a/weed/iam/policy/policy_store.go b/weed/iam/policy/policy_store.go index a83f065ad5..1f56eda540 100644 --- a/weed/iam/policy/policy_store.go +++ b/weed/iam/policy/policy_store.go @@ -13,6 +13,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/glog" "github.com/seaweedfs/seaweedfs/weed/pb" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/security" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" @@ -407,7 +408,7 @@ func (s *FilerPolicyStore) withFilerClient(filerAddress string, fn func(client f } // Use the pb.WithGrpcFilerClient helper similar to existing SeaweedFS code - return pb.WithGrpcFilerClient(false, 0, pb.ServerAddress(filerAddress), s.grpcDialOption, fn) + return pb.WithGrpcFilerClient(false, 0, pb.ServerAddress(filerAddress), s.grpcDialOption, security.FilerAdminToken, fn) } // getPolicyPath returns the full path for a policy diff --git a/weed/iamapi/iamapi_filer_auth_test.go b/weed/iamapi/iamapi_filer_auth_test.go new file mode 100644 index 0000000000..d729a1e04e --- /dev/null +++ b/weed/iamapi/iamapi_filer_auth_test.go @@ -0,0 +1,121 @@ +package iamapi + +import ( + "context" + "net" + "strconv" + "strings" + "sync" + "testing" + + "github.com/seaweedfs/seaweedfs/weed/pb" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/pb/iam_pb" + "github.com/seaweedfs/seaweedfs/weed/security" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" +) + +type iamFilerAuthTestServer struct { + filer_pb.UnimplementedSeaweedFilerServer + + mu sync.Mutex + authorizations [][]string + created bool +} + +func (s *iamFilerAuthTestServer) recordAuthorization(ctx context.Context) error { + md, _ := metadata.FromIncomingContext(ctx) + values := append([]string(nil), md.Get("authorization")...) + s.mu.Lock() + s.authorizations = append(s.authorizations, values) + s.mu.Unlock() + if len(values) != 1 || !strings.HasPrefix(values[0], security.BearerPrefix) { + return status.Error(codes.Unauthenticated, "missing filer admin token") + } + token := security.EncodedJwt(strings.TrimPrefix(values[0], security.BearerPrefix)) + if !security.IsFilerAdminToken(iamFilerAuthTestKey, token) { + return status.Error(codes.Unauthenticated, "invalid filer admin token") + } + return nil +} + +func (s *iamFilerAuthTestServer) LookupDirectoryEntry(context.Context, *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) { + return &filer_pb.LookupDirectoryEntryResponse{}, nil +} + +func (s *iamFilerAuthTestServer) CreateEntry(_ context.Context, _ *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) { + s.mu.Lock() + s.created = true + s.mu.Unlock() + return &filer_pb.CreateEntryResponse{}, nil +} + +func (s *iamFilerAuthTestServer) authorizationValues() [][]string { + s.mu.Lock() + defer s.mu.Unlock() + values := make([][]string, len(s.authorizations)) + for i, auth := range s.authorizations { + values[i] = append([]string(nil), auth...) + } + return values +} + +var iamFilerAuthTestKey = security.SigningKey("iam-api-filer-auth-test-key-32-bytes-long") + +func startIamFilerAuthTestServer(t *testing.T, serverImpl *iamFilerAuthTestServer) pb.ServerAddress { + t.Helper() + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + grpcServer := grpc.NewServer(grpc.UnaryInterceptor(func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { + if err := serverImpl.recordAuthorization(ctx); err != nil { + return nil, err + } + return handler(ctx, req) + })) + filer_pb.RegisterSeaweedFilerServer(grpcServer, serverImpl) + go func() { _ = grpcServer.Serve(listener) }() + t.Cleanup(func() { + grpcServer.Stop() + _ = listener.Close() + }) + _, portText, err := net.SplitHostPort(listener.Addr().String()) + if err != nil { + t.Fatal(err) + } + grpcPort, err := strconv.Atoi(portText) + if err != nil { + t.Fatal(err) + } + return pb.NewServerAddressWithGrpcPort(listener.Addr().String(), grpcPort) +} + +func TestPutS3ApiConfigurationToFilerCarriesAdminAuth(t *testing.T) { + t.Setenv("WEED_JWT_FILER_SIGNING_GRPC_KEY", "") + t.Setenv("WEED_JWT_FILER_SIGNING_KEY", string(iamFilerAuthTestKey)) + server := &iamFilerAuthTestServer{} + address := startIamFilerAuthTestServer(t, server) + configure := &IamS3ApiConfigure{ + option: &IamServerOption{ + Filers: []pb.ServerAddress{address}, + GrpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()), + }, + } + if err := configure.PutS3ApiConfigurationToFiler(&iam_pb.S3ApiConfiguration{}); err != nil { + t.Fatalf("put IAM configuration: %v", err) + } + s := server.authorizationValues() + if len(s) != 2 || !server.created { + t.Fatalf("persistence made %d authenticated calls, created=%v; want lookup plus create", len(s), server.created) + } + for i, values := range s { + if len(values) != 1 || !strings.HasPrefix(values[0], security.BearerPrefix) { + t.Fatalf("persistence call %d did not carry one bearer authorization", i) + } + } +} diff --git a/weed/iamapi/iamapi_server.go b/weed/iamapi/iamapi_server.go index 63f85623f2..6988fd2c47 100644 --- a/weed/iamapi/iamapi_server.go +++ b/weed/iamapi/iamapi_server.go @@ -20,6 +20,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/s3api" "github.com/seaweedfs/seaweedfs/weed/s3api/policy_engine" "github.com/seaweedfs/seaweedfs/weed/s3api/s3err" + "github.com/seaweedfs/seaweedfs/weed/security" "github.com/seaweedfs/seaweedfs/weed/util" util_http "github.com/seaweedfs/seaweedfs/weed/util/http" "github.com/seaweedfs/seaweedfs/weed/util/request_id" @@ -94,7 +95,9 @@ func NewIamApiServerWithStore(router *mux.Router, option *IamServerOption, expli } // Initialize FilerClient for IAM - explicit filers only (no discovery as FilerGroup unspecified) - filerClient := wdclient.NewFilerClient(option.Filers, option.GrpcDialOption, "") + filerClient := wdclient.NewFilerClient(option.Filers, option.GrpcDialOption, "", &wdclient.FilerClientOption{ + FilerTokenSource: security.FilerAdminToken, + }) iam := s3api.NewIdentityAccessManagementWithStore(&s3Option, filerClient, explicitStore) configure.credentialManager = iam.GetCredentialManager() @@ -184,7 +187,7 @@ func (iama *IamS3ApiConfigure) PutS3ApiConfigurationToCredentialManager(s3cfg *i func (iama *IamS3ApiConfigure) GetS3ApiConfigurationFromFiler(s3cfg *iam_pb.S3ApiConfiguration) (err error) { var buf bytes.Buffer - err = pb.WithOneOfGrpcFilerClients(false, iama.option.Filers, iama.option.GrpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + err = pb.WithOneOfGrpcFilerClients(false, iama.option.Filers, iama.option.GrpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error { if err = filer.ReadEntry(iama.masterClient, client, filer.IamConfigDirectory, filer.IamIdentityFile, &buf); err != nil { return err } @@ -206,7 +209,7 @@ func (iama *IamS3ApiConfigure) PutS3ApiConfigurationToFiler(s3cfg *iam_pb.S3ApiC if err := filer.ProtoToText(&buf, s3cfg); err != nil { return fmt.Errorf("ProtoToText: %s", err) } - return pb.WithOneOfGrpcFilerClients(false, iama.option.Filers, iama.option.GrpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + return pb.WithOneOfGrpcFilerClients(false, iama.option.Filers, iama.option.GrpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error { err = util.Retry("saveIamIdentity", func() error { return filer.SaveInsideFiler(context.Background(), client, filer.IamConfigDirectory, filer.IamIdentityFile, buf.Bytes()) }) @@ -256,7 +259,7 @@ func (iama *IamS3ApiConfigure) GetPolicies(policies *Policies) (err error) { // conflict (per name / per (user, name) / per (group, name)) so we never // produce duplicates. var buf bytes.Buffer - rErr := pb.WithOneOfGrpcFilerClients(false, iama.option.Filers, iama.option.GrpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + rErr := pb.WithOneOfGrpcFilerClients(false, iama.option.Filers, iama.option.GrpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error { return filer.ReadEntry(iama.masterClient, client, filer.IamConfigDirectory, filer.IamPoliciesFile, &buf) }) if rErr != nil && rErr != filer_pb.ErrNotFound { @@ -403,7 +406,7 @@ func (iama *IamS3ApiConfigure) writeLegacyPolicies(ctx context.Context, p *Polic if err != nil { return fmt.Errorf("marshal legacy policies: %w", err) } - return pb.WithOneOfGrpcFilerClients(false, iama.option.Filers, iama.option.GrpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + return pb.WithOneOfGrpcFilerClients(false, iama.option.Filers, iama.option.GrpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error { return filer.SaveInsideFiler(ctx, client, filer.IamConfigDirectory, filer.IamPoliciesFile, b) }) } diff --git a/weed/mount/sse_s3_reader.go b/weed/mount/sse_s3_reader.go index fbcda14326..c707886fa9 100644 --- a/weed/mount/sse_s3_reader.go +++ b/weed/mount/sse_s3_reader.go @@ -66,7 +66,7 @@ func NewSSES3Reader(ctx context.Context, bucketPath string, filers []pb.ServerAd func listS3Endpoints(ctx context.Context, filers []pb.ServerAddress, grpcDialOption grpc.DialOption) ([]string, error) { var masters []string var filerGroup string - if err := pb.WithOneOfGrpcFilerClients(false, filers, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + if err := pb.WithOneOfGrpcFilerClients(false, filers, grpcDialOption, nil, func(client filer_pb.SeaweedFilerClient) error { resp, err := client.GetFilerConfiguration(ctx, &filer_pb.GetFilerConfigurationRequest{}) if err != nil { return err diff --git a/weed/mount/weedfs.go b/weed/mount/weedfs.go index 0c35b1bc5a..8009b911dd 100644 --- a/weed/mount/weedfs.go +++ b/weed/mount/weedfs.go @@ -423,7 +423,7 @@ func NewSeaweedFileSystem(option *Option) *WFS { option.PeerEnabled = false } else { dial := func(ctx context.Context, addr pb.ServerAddress, fn func(client filer_pb.SeaweedFilerClient) error) error { - return pb.WithGrpcFilerClient(false, 0, addr, option.GrpcDialOption, fn) + return pb.WithGrpcFilerClient(false, 0, addr, option.GrpcDialOption, nil, fn) } wfs.peerRegistrar = NewPeerRegistrar(option.FilerAddresses, dial, selfAddr, option.PeerDataCenter, option.PeerRack) if err := wfs.peerRegistrar.Start(context.Background()); err != nil { diff --git a/weed/mq/broker/broker_filer_auth_test.go b/weed/mq/broker/broker_filer_auth_test.go new file mode 100644 index 0000000000..843538b0d5 --- /dev/null +++ b/weed/mq/broker/broker_filer_auth_test.go @@ -0,0 +1,96 @@ +package broker + +import ( + "context" + "crypto/rand" + "encoding/hex" + "net" + "strconv" + "strings" + "testing" + + "github.com/seaweedfs/seaweedfs/weed/pb" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/security" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" +) + +type brokerAuthFiler struct { + filer_pb.UnimplementedSeaweedFilerServer + key security.SigningKey + authResults chan bool +} + +func (f *brokerAuthFiler) LookupDirectoryEntry(ctx context.Context, req *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) { + md, _ := metadata.FromIncomingContext(ctx) + values := md.Get("authorization") + valid := len(values) == 1 && strings.HasPrefix(values[0], security.BearerPrefix) && + security.IsFilerAdminToken(f.key, security.EncodedJwt(strings.TrimPrefix(values[0], security.BearerPrefix))) + f.authResults <- valid + if !valid { + return nil, status.Error(codes.Unauthenticated, "missing or invalid filer authorization") + } + return &filer_pb.LookupDirectoryEntryResponse{ + Entry: &filer_pb.Entry{Name: req.Name, Attributes: &filer_pb.FuseAttributes{}}, + }, nil +} + +func brokerTestSigningKey(t *testing.T) security.SigningKey { + t.Helper() + bytes := make([]byte, 32) + if _, err := rand.Read(bytes); err != nil { + t.Fatal(err) + } + return security.SigningKey(hex.EncodeToString(bytes)) +} + +func TestWithFilerClientSendsAdminToken(t *testing.T) { + key := brokerTestSigningKey(t) + t.Setenv("WEED_JWT_FILER_SIGNING_GRPC_KEY", string(key)) + t.Setenv("WEED_JWT_FILER_SIGNING_KEY", "") + + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + _, portText, err := net.SplitHostPort(listener.Addr().String()) + if err != nil { + t.Fatalf("split listener address: %v", err) + } + grpcPort, err := strconv.Atoi(portText) + if err != nil { + t.Fatalf("parse listener port: %v", err) + } + filer := &brokerAuthFiler{key: key, authResults: make(chan bool, 1)} + server := grpc.NewServer() + filer_pb.RegisterSeaweedFilerServer(server, filer) + go server.Serve(listener) + t.Cleanup(func() { + server.Stop() + _ = listener.Close() + }) + + broker := &MessageQueueBroker{ + currentFiler: pb.NewServerAddressWithGrpcPort(listener.Addr().String(), grpcPort), + grpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()), + } + err = broker.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error { + _, err := client.LookupDirectoryEntry(context.Background(), &filer_pb.LookupDirectoryEntryRequest{Directory: "/", Name: "entry"}) + return err + }) + if err != nil { + t.Fatalf("WithFilerClient: %v", err) + } + select { + case valid := <-filer.authResults: + if !valid { + t.Fatal("filer rejected the per-call admin token") + } + default: + t.Fatal("filer did not receive the request") + } +} diff --git a/weed/mq/broker/broker_server.go b/weed/mq/broker/broker_server.go index e9b3676172..df60ef710a 100644 --- a/weed/mq/broker/broker_server.go +++ b/weed/mq/broker/broker_server.go @@ -14,6 +14,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/cluster" "github.com/seaweedfs/seaweedfs/weed/cluster/lock_manager" "github.com/seaweedfs/seaweedfs/weed/pb/mq_pb" + "github.com/seaweedfs/seaweedfs/weed/security" "github.com/seaweedfs/seaweedfs/weed/wdclient" "google.golang.org/grpc" @@ -93,6 +94,7 @@ func NewMessageBroker(option *MessageQueueBrokerOption, grpcDialOption grpc.Dial // Create FilerClientAccessor that adapts broker's single filer to the new multi-filer interface fca := &filer_client.FilerClientAccessor{ GetGrpcDialOption: mqBroker.GetGrpcDialOption, + TokenSource: security.FilerAdminToken, GetFilers: func() []pb.ServerAddress { filer := mqBroker.GetFiler() if filer != "" { @@ -143,6 +145,7 @@ func NewMessageBroker(option *MessageQueueBrokerOption, grpcDialOption grpc.Dial newBrokerBalancerCh := make(chan string, 1) lockClient := cluster.NewLockClient(grpcDialOption, mqBroker.currentFiler) + lockClient.TokenSource = security.FilerAdminToken mqBroker.lockAsBalancer = lockClient.StartLongLivedLock(pub_balancer.LockBrokerBalancer, string(self), func(newLockOwner string) { glog.V(0).Infof("broker %s found balanacer %s", self, newLockOwner) newBrokerBalancerCh <- newLockOwner @@ -189,8 +192,7 @@ func (b *MessageQueueBroker) GetFiler() pb.ServerAddress { } func (b *MessageQueueBroker) WithFilerClient(streamingMode bool, fn func(filer_pb.SeaweedFilerClient) error) error { - - return pb.WithFilerClient(streamingMode, 0, b.GetFiler(), b.grpcDialOption, fn) + return pb.WithGrpcFilerClient(streamingMode, 0, b.GetFiler(), b.grpcDialOption, security.FilerAdminToken, fn) } diff --git a/weed/mq/kafka/gateway/coordinator_registry.go b/weed/mq/kafka/gateway/coordinator_registry.go index 278279b70d..e7d6a53a18 100644 --- a/weed/mq/kafka/gateway/coordinator_registry.go +++ b/weed/mq/kafka/gateway/coordinator_registry.go @@ -20,6 +20,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/pb" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/pb/master_pb" + "github.com/seaweedfs/seaweedfs/weed/security" "google.golang.org/grpc" ) @@ -103,6 +104,7 @@ func NewCoordinatorRegistry(gatewayAddress string, masters []pb.ServerAddress, g } lockClient := cluster.NewLockClient(grpcDialOption, seedFiler) + lockClient.TokenSource = security.FilerAdminToken registry := &CoordinatorRegistry{ activeGateways: make(map[string]*GatewayInfo), @@ -118,6 +120,7 @@ func NewCoordinatorRegistry(gatewayAddress string, masters []pb.ServerAddress, g GetGrpcDialOption: func() grpc.DialOption { return grpcDialOption }, + TokenSource: security.FilerAdminToken, GetFilers: func() []pb.ServerAddress { return registry.filerDiscoveryService.GetFilers() }, diff --git a/weed/mq/kafka/integration/seaweedmq_handler_utils.go b/weed/mq/kafka/integration/seaweedmq_handler_utils.go index e17cf4eb69..fe583fc9b8 100644 --- a/weed/mq/kafka/integration/seaweedmq_handler_utils.go +++ b/weed/mq/kafka/integration/seaweedmq_handler_utils.go @@ -78,6 +78,7 @@ func NewSeaweedMQBrokerHandler(masters string, filerGroup string, clientHost str filerAddresses, grpcDialOption, ) + sharedFilerAccessor.TokenSource = security.FilerAdminToken // For now, use the first broker (can be enhanced later for load balancing) brokerAddress := brokerAddresses[0] diff --git a/weed/pb/filer_client_auth_test.go b/weed/pb/filer_client_auth_test.go new file mode 100644 index 0000000000..705e7d0ae1 --- /dev/null +++ b/weed/pb/filer_client_auth_test.go @@ -0,0 +1,315 @@ +package pb + +import ( + "context" + "crypto/rand" + "encoding/hex" + "io" + "net" + "strconv" + "strings" + "sync" + "testing" + + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/security" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/metadata" +) + +func filerAuthTestKey(t *testing.T) security.SigningKey { + t.Helper() + bytes := make([]byte, 32) + if _, err := rand.Read(bytes); err != nil { + t.Fatal(err) + } + return security.SigningKey(hex.EncodeToString(bytes)) +} + +type authRecordingFiler struct { + filer_pb.UnimplementedSeaweedFilerServer + + mu sync.Mutex + authorizations [][]string +} + +func (s *authRecordingFiler) record(ctx context.Context) { + md, _ := metadata.FromIncomingContext(ctx) + values := append([]string(nil), md.Get("authorization")...) + s.mu.Lock() + s.authorizations = append(s.authorizations, values) + s.mu.Unlock() +} + +func (s *authRecordingFiler) LookupDirectoryEntry(ctx context.Context, _ *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) { + s.record(ctx) + return &filer_pb.LookupDirectoryEntryResponse{}, nil +} + +func (s *authRecordingFiler) ListEntries(_ *filer_pb.ListEntriesRequest, stream filer_pb.SeaweedFiler_ListEntriesServer) error { + s.record(stream.Context()) + return stream.Send(&filer_pb.ListEntriesResponse{Entry: &filer_pb.Entry{Name: "entry"}}) +} + +func (s *authRecordingFiler) SubscribeMetadata(_ *filer_pb.SubscribeMetadataRequest, stream filer_pb.SeaweedFiler_SubscribeMetadataServer) error { + s.record(stream.Context()) + return nil +} + +func (s *authRecordingFiler) authorizationValues() [][]string { + s.mu.Lock() + defer s.mu.Unlock() + values := make([][]string, len(s.authorizations)) + for i, auth := range s.authorizations { + values[i] = append([]string(nil), auth...) + } + return values +} + +func validAdminAuthorization(values []string, key security.SigningKey) bool { + if len(values) != 1 || !strings.HasPrefix(values[0], security.BearerPrefix) { + return false + } + return security.IsFilerAdminToken(key, security.EncodedJwt(strings.TrimPrefix(values[0], security.BearerPrefix))) +} + +func startAuthRecordingFiler(t *testing.T) (*authRecordingFiler, ServerAddress) { + t.Helper() + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + server := grpc.NewServer() + filer := &authRecordingFiler{} + filer_pb.RegisterSeaweedFilerServer(server, filer) + go func() { + _ = server.Serve(listener) + }() + t.Cleanup(func() { + server.Stop() + _ = listener.Close() + }) + _, portText, err := net.SplitHostPort(listener.Addr().String()) + if err != nil { + t.Fatal(err) + } + grpcPort, err := strconv.Atoi(portText) + if err != nil { + t.Fatal(err) + } + return filer, NewServerAddressWithGrpcPort(listener.Addr().String(), grpcPort) +} + +func callLookupWithAuth(t *testing.T, address ServerAddress, source security.FilerTokenSource) error { + t.Helper() + return WithGrpcFilerClient(false, 0, address, grpc.WithTransportCredentials(insecure.NewCredentials()), source, func(client filer_pb.SeaweedFilerClient) error { + _, err := client.LookupDirectoryEntry(context.Background(), &filer_pb.LookupDirectoryEntryRequest{Directory: "/", Name: "entry"}) + return err + }) +} + +func pooledFilerConnection(t *testing.T, address ServerAddress) *grpc.ClientConn { + t.Helper() + grpcClientsLock.Lock() + defer grpcClientsLock.Unlock() + client, ok := grpcClients[address.ToGrpcAddress()] + if !ok { + t.Fatal("pooled filer connection was not created") + } + return client.ClientConn +} + +func TestWithGrpcFilerClientPooledUnaryAuthAnonymousBothOrders(t *testing.T) { + for _, firstAuth := range []bool{false, true} { + t.Run(map[bool]string{false: "anonymous-first", true: "authenticated-first"}[firstAuth], func(t *testing.T) { + server, address := startAuthRecordingFiler(t) + t.Cleanup(func() { InvalidateGrpcConnection(address.ToGrpcAddress()) }) + key := filerAuthTestKey(t) + token := security.GenJwtForFilerAdmin(key, 60) + source := func(context.Context) (security.EncodedJwt, error) { return token, nil } + + var pooledConn *grpc.ClientConn + if firstAuth { + if err := callLookupWithAuth(t, address, source); err != nil { + t.Fatalf("authenticated first call: %v", err) + } + pooledConn = pooledFilerConnection(t, address) + if err := callLookupWithAuth(t, address, nil); err != nil { + t.Fatalf("anonymous second call: %v", err) + } + } else { + if err := callLookupWithAuth(t, address, nil); err != nil { + t.Fatalf("anonymous first call: %v", err) + } + pooledConn = pooledFilerConnection(t, address) + if err := callLookupWithAuth(t, address, source); err != nil { + t.Fatalf("authenticated second call: %v", err) + } + } + if pooledConn != pooledFilerConnection(t, address) { + t.Fatal("authenticated and anonymous calls did not reuse the same pooled client connection") + } + + auth := server.authorizationValues() + if len(auth) != 2 { + t.Fatalf("server saw %d calls, want two", len(auth)) + } + for i, values := range auth { + wantAuth := (i == 0) == firstAuth + if !wantAuth { + if len(values) != 0 { + t.Fatalf("call %d unexpectedly carried authorization metadata", i) + } + continue + } + if !validAdminAuthorization(values, key) { + t.Fatalf("call %d did not receive a valid admin token", i) + } + } + }) + } +} + +func TestWithGrpcFilerClientResolvesPooledTokenOnEveryUnaryCall(t *testing.T) { + server, address := startAuthRecordingFiler(t) + t.Cleanup(func() { InvalidateGrpcConnection(address.ToGrpcAddress()) }) + keys := []security.SigningKey{ + filerAuthTestKey(t), + filerAuthTestKey(t), + } + tokens := []security.EncodedJwt{ + security.GenJwtForFilerAdmin(keys[0], 60), + security.GenJwtForFilerAdmin(keys[1], 60), + } + index := 0 + source := func(context.Context) (security.EncodedJwt, error) { + token := tokens[index] + index++ + return token, nil + } + for i := 0; i < len(tokens); i++ { + if err := callLookupWithAuth(t, address, source); err != nil { + t.Fatalf("call %d: %v", i, err) + } + } + if index != len(tokens) { + t.Fatalf("token source called %d times, want %d", index, len(tokens)) + } + auth := server.authorizationValues() + if len(auth) != len(tokens) { + t.Fatalf("server saw %d calls, want %d", len(auth), len(tokens)) + } + for i, values := range auth { + if !validAdminAuthorization(values, keys[i]) { + t.Fatalf("call %d did not receive a valid admin token", i) + } + if values[0] != security.BearerPrefix+string(tokens[i]) { + t.Fatalf("call %d did not receive its freshly resolved token", i) + } + } +} + +func TestWithGrpcFilerClientStreamingReopensWithFreshToken(t *testing.T) { + server, address := startAuthRecordingFiler(t) + keys := []security.SigningKey{filerAuthTestKey(t), filerAuthTestKey(t)} + tokens := []security.EncodedJwt{ + security.GenJwtForFilerAdmin(keys[0], 60), + security.GenJwtForFilerAdmin(keys[1], 60), + } + call := 0 + source := func(context.Context) (security.EncodedJwt, error) { + token := tokens[call] + call++ + return token, nil + } + for i := range tokens { + err := WithGrpcFilerClient(true, 0, address, grpc.WithTransportCredentials(insecure.NewCredentials()), source, func(client filer_pb.SeaweedFilerClient) error { + stream, err := client.ListEntries(context.Background(), &filer_pb.ListEntriesRequest{Directory: "/"}) + if err != nil { + return err + } + if _, err := stream.Recv(); err != nil { + return err + } + _, err = stream.Recv() + return err + }) + if err != io.EOF { + t.Fatalf("stream call %d returned an unexpected result", i) + } + } + if call != len(tokens) { + t.Fatalf("token source called %d times, want %d", call, len(tokens)) + } + auth := server.authorizationValues() + if len(auth) != len(tokens) { + t.Fatalf("server saw %d stream calls, want %d", len(auth), len(tokens)) + } + for i, values := range auth { + if !validAdminAuthorization(values, keys[i]) || values[0] != security.BearerPrefix+string(tokens[i]) { + t.Fatalf("stream call %d did not receive its fresh token", i) + } + } +} + +func TestWithGrpcFilerClientStreamingListEntriesCarriesToken(t *testing.T) { + server, address := startAuthRecordingFiler(t) + key := filerAuthTestKey(t) + token := security.GenJwtForFilerAdmin(key, 60) + sourceCalls := 0 + source := func(context.Context) (security.EncodedJwt, error) { + sourceCalls++ + return token, nil + } + err := WithGrpcFilerClient(true, 0, address, grpc.WithTransportCredentials(insecure.NewCredentials()), source, func(client filer_pb.SeaweedFilerClient) error { + stream, err := client.ListEntries(context.Background(), &filer_pb.ListEntriesRequest{Directory: "/"}) + if err != nil { + return err + } + response, err := stream.Recv() + if err != nil { + return err + } + if response.GetEntry().GetName() != "entry" { + t.Fatalf("stream entry = %q, want entry", response.GetEntry().GetName()) + } + _, err = stream.Recv() + if err != io.EOF { + t.Fatalf("second stream receive = %v, want EOF", err) + } + return nil + }) + if err != nil { + t.Fatalf("streaming call: %v", err) + } + if sourceCalls != 1 { + t.Fatalf("token source called %d times, want one stream-open resolution", sourceCalls) + } + auth := server.authorizationValues() + if len(auth) != 1 || !validAdminAuthorization(auth[0], key) { + t.Fatal("ListEntries did not receive a valid admin token") + } +} + +func TestFollowMetadataUsesEndpointTokenSource(t *testing.T) { + server, address := startAuthRecordingFiler(t) + key := filerAuthTestKey(t) + token := security.GenJwtForFilerAdmin(key, 60) + sourceCalls := 0 + err := FollowMetadata(address, grpc.WithTransportCredentials(insecure.NewCredentials()), &MetadataFollowOption{ + ClientName: "auth-test", + EventErrorType: DontLogError, + FilerTokenSource: func(context.Context) (security.EncodedJwt, error) { sourceCalls++; return token, nil }, + }, func(*filer_pb.SubscribeMetadataResponse) error { return nil }) + if err != nil { + t.Fatalf("metadata follow: %v", err) + } + if sourceCalls != 1 { + t.Fatalf("token source called %d times, want one subscription attempt", sourceCalls) + } + auth := server.authorizationValues() + if len(auth) != 1 || !validAdminAuthorization(auth[0], key) { + t.Fatal("subscription did not receive a valid endpoint admin token") + } +} diff --git a/weed/pb/filer_clients_auth_retry_test.go b/weed/pb/filer_clients_auth_retry_test.go new file mode 100644 index 0000000000..d97ad6bf8a --- /dev/null +++ b/weed/pb/filer_clients_auth_retry_test.go @@ -0,0 +1,88 @@ +package pb + +import ( + "context" + "net" + "strconv" + "testing" + + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/security" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" +) + +type retryingAuthFiler struct { + authRecordingFiler +} + +func (f *retryingAuthFiler) LookupDirectoryEntry(ctx context.Context, _ *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) { + f.record(ctx) + return nil, status.Error(codes.Unavailable, "retry test") +} + +func startRetryingAuthFiler(t *testing.T) (*retryingAuthFiler, ServerAddress) { + t.Helper() + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + server := grpc.NewServer() + filer := &retryingAuthFiler{} + filer_pb.RegisterSeaweedFilerServer(server, filer) + go func() { + _ = server.Serve(listener) + }() + t.Cleanup(func() { + server.Stop() + _ = listener.Close() + }) + _, portText, err := net.SplitHostPort(listener.Addr().String()) + if err != nil { + t.Fatal(err) + } + grpcPort, err := strconv.Atoi(portText) + if err != nil { + t.Fatal(err) + } + return filer, NewServerAddressWithGrpcPort(listener.Addr().String(), grpcPort) +} + +func TestWithOneOfGrpcFilerClientsPreservesFailoverAndPerCallSource(t *testing.T) { + first, firstAddress := startRetryingAuthFiler(t) + second, secondAddress := startAuthRecordingFiler(t) + t.Cleanup(func() { + InvalidateGrpcConnection(firstAddress.ToGrpcAddress()) + InvalidateGrpcConnection(secondAddress.ToGrpcAddress()) + }) + keys := []security.SigningKey{filerAuthTestKey(t), filerAuthTestKey(t)} + tokens := []security.EncodedJwt{ + security.GenJwtForFilerAdmin(keys[0], 60), + security.GenJwtForFilerAdmin(keys[1], 60), + } + resolutions := 0 + err := WithOneOfGrpcFilerClients(false, []ServerAddress{firstAddress, secondAddress}, grpc.WithTransportCredentials(insecure.NewCredentials()), func(context.Context) (security.EncodedJwt, error) { + token := tokens[resolutions] + resolutions++ + return token, nil + }, func(client filer_pb.SeaweedFilerClient) error { + _, err := client.LookupDirectoryEntry(context.Background(), &filer_pb.LookupDirectoryEntryRequest{Directory: "/", Name: "entry"}) + return err + }) + if err != nil { + t.Fatalf("failover call: %v", err) + } + if resolutions != len(tokens) { + t.Fatalf("token source called %d times, want %d", resolutions, len(tokens)) + } + firstAuth := first.authorizationValues() + if len(firstAuth) != 1 || !validAdminAuthorization(firstAuth[0], keys[0]) { + t.Fatal("first filer did not receive its per-attempt admin token") + } + secondAuth := second.authorizationValues() + if len(secondAuth) != 1 || !validAdminAuthorization(secondAuth[0], keys[1]) { + t.Fatal("second filer did not receive its per-attempt admin token") + } +} diff --git a/weed/pb/filer_pb_tail.go b/weed/pb/filer_pb_tail.go index 8fbb145419..c84ee36498 100644 --- a/weed/pb/filer_pb_tail.go +++ b/weed/pb/filer_pb_tail.go @@ -12,6 +12,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/security" "github.com/seaweedfs/seaweedfs/weed/util" "google.golang.org/grpc" + "google.golang.org/grpc/metadata" ) type EventErrorType int @@ -43,6 +44,10 @@ type MetadataFollowOption struct { // FilerJwtProvider, when non-nil, signs the subscription with the source // cluster's own filer key instead of this process's configuration. FilerJwtProvider security.FilerJwtProvider + // FilerTokenSource, when non-nil, supplies the receiving filer's admin + // token for this endpoint on each subscription attempt. An empty token + // preserves the legacy subscription-credential fallback above the client. + FilerTokenSource security.FilerTokenSource // OnIdleHeartbeat, when non-nil, opts in to idle heartbeats: while the // subscriber is caught up the server periodically sends an empty response // carrying the current time, and this is called with that timestamp. It is @@ -95,7 +100,20 @@ func makeSubscribeMetadataFunc(option *MetadataFollowOption, processEventFn Proc if option.GetResumeTsNs != nil { sinceNs = option.GetResumeTsNs() } - stream, err := client.SubscribeMetadata(security.WithMetadataSubscriptionCredentials(ctx, option.FilerJwtProvider), &filer_pb.SubscribeMetadataRequest{ + subscribeCtx := ctx + if option.FilerTokenSource != nil { + var authErr error + subscribeCtx, authErr = security.WithFilerSubscriptionToken(ctx, option.FilerTokenSource) + if authErr != nil { + return fmt.Errorf("resolve subscription credentials: %w", authErr) + } + if md, ok := metadata.FromOutgoingContext(subscribeCtx); !ok || len(md.Get("authorization")) == 0 { + subscribeCtx = security.WithMetadataSubscriptionCredentials(subscribeCtx, option.FilerJwtProvider) + } + } else { + subscribeCtx = security.WithMetadataSubscriptionCredentials(subscribeCtx, option.FilerJwtProvider) + } + stream, err := client.SubscribeMetadata(subscribeCtx, &filer_pb.SubscribeMetadataRequest{ ClientName: option.ClientName, PathPrefix: option.PathPrefix, PathPrefixes: option.AdditionalPathPrefixes, diff --git a/weed/pb/grpc_client_server.go b/weed/pb/grpc_client_server.go index e68f4d9f49..2e25cc5589 100644 --- a/weed/pb/grpc_client_server.go +++ b/weed/pb/grpc_client_server.go @@ -21,6 +21,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/glog" "github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb" + "github.com/seaweedfs/seaweedfs/weed/security" "github.com/seaweedfs/seaweedfs/weed/util" "google.golang.org/grpc" @@ -752,26 +753,26 @@ func WithBrokerGrpcClient(streamingMode bool, brokerGrpcAddress string, grpcDial func WithFilerClient(streamingMode bool, signature int32, filer ServerAddress, grpcDialOption grpc.DialOption, fn func(client filer_pb.SeaweedFilerClient) error) error { - return WithGrpcFilerClient(streamingMode, signature, filer, grpcDialOption, fn) + return WithGrpcFilerClient(streamingMode, signature, filer, grpcDialOption, nil, fn) } -func WithGrpcFilerClient(streamingMode bool, signature int32, filerAddress ServerAddress, grpcDialOption grpc.DialOption, fn func(client filer_pb.SeaweedFilerClient) error) error { +// WithGrpcFilerClient selects credentials for this logical client, not for +// the shared pooled connection: source is called at each RPC invocation or +// stream open inside fn. A nil source sends no token. +func WithGrpcFilerClient(streamingMode bool, signature int32, filerAddress ServerAddress, grpcDialOption grpc.DialOption, source security.FilerTokenSource, fn func(client filer_pb.SeaweedFilerClient) error) error { return WithGrpcClient(context.Background(), streamingMode, signature, func(grpcConnection *grpc.ClientConn) error { - client := filer_pb.NewSeaweedFilerClient(grpcConnection) + client := filer_pb.NewSeaweedFilerClient(security.WithFilerClientAuth(grpcConnection, source)) return fn(client) }, filerAddress.ToGrpcAddress(), false, grpcDialOption) } -func WithOneOfGrpcFilerClients(streamingMode bool, filerAddresses []ServerAddress, grpcDialOption grpc.DialOption, fn func(client filer_pb.SeaweedFilerClient) error) (err error) { +func WithOneOfGrpcFilerClients(streamingMode bool, filerAddresses []ServerAddress, grpcDialOption grpc.DialOption, source security.FilerTokenSource, fn func(client filer_pb.SeaweedFilerClient) error) (err error) { for _, filerAddress := range filerAddresses { - err = WithGrpcClient(context.Background(), streamingMode, 0, func(grpcConnection *grpc.ClientConn) error { - client := filer_pb.NewSeaweedFilerClient(grpcConnection) - return fn(client) - }, filerAddress.ToGrpcAddress(), false, grpcDialOption) + err = WithGrpcFilerClient(streamingMode, 0, filerAddress, grpcDialOption, source, fn) if err == nil { return nil } diff --git a/weed/plugin/worker/admin_script_handler.go b/weed/plugin/worker/admin_script_handler.go index b11bd420d8..64838c6e7c 100644 --- a/weed/plugin/worker/admin_script_handler.go +++ b/weed/plugin/worker/admin_script_handler.go @@ -12,6 +12,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/glog" "github.com/seaweedfs/seaweedfs/weed/pb" "github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb" + "github.com/seaweedfs/seaweedfs/weed/security" "github.com/seaweedfs/seaweedfs/weed/shell" "google.golang.org/grpc" "google.golang.org/protobuf/types/known/timestamppb" @@ -553,10 +554,11 @@ func (h *AdminScriptHandler) buildAdminScriptShellOptions(clusterContext *plugin filerGroup := "" mastersValue := strings.Join(masters, ",") options := shell.ShellOptions{ - Masters: &mastersValue, - GrpcDialOption: h.grpcDialOption, - FilerGroup: &filerGroup, - Directory: "/", + Masters: &mastersValue, + GrpcDialOption: h.grpcDialOption, + FilerGroup: &filerGroup, + Directory: "/", + FilerTokenSource: security.FilerAdminToken, } // FilerAddresses are pb.ServerAddress strings (host:httpPort.grpcPort). diff --git a/weed/plugin/worker/admin_script_handler_test.go b/weed/plugin/worker/admin_script_handler_test.go index 235cff769a..44bf5a6295 100644 --- a/weed/plugin/worker/admin_script_handler_test.go +++ b/weed/plugin/worker/admin_script_handler_test.go @@ -2,14 +2,50 @@ package pluginworker import ( "context" + "os" + "path/filepath" "strings" "testing" "time" "github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb" + "github.com/seaweedfs/seaweedfs/weed/security" + "github.com/seaweedfs/seaweedfs/weed/util" "google.golang.org/protobuf/types/known/timestamppb" ) +func TestAdminScriptShellOptionsAuthenticateFilerCalls(t *testing.T) { + // Admin scripts run shell commands against the filer, so under + // grpc_require_token they must present the worker's filer admin token. + // Environment overrides take precedence over the file; clear them. + t.Setenv("WEED_JWT_FILER_SIGNING_GRPC_KEY", "") + t.Setenv("WEED_JWT_FILER_SIGNING_KEY", "") + dir := t.TempDir() + saved := util.ConfigurationFileDirectory + util.ConfigurationFileDirectory = util.DirectoryValueType(dir) + t.Cleanup(func() { util.ConfigurationFileDirectory = saved }) + key := security.SigningKey("admin-script-test-signing-key-0123456789") + if err := os.WriteFile(filepath.Join(dir, "security.toml"), []byte("[jwt.filer_signing]\nkey = \""+string(key)+"\"\n"), 0600); err != nil { + t.Fatal(err) + } + + h := NewAdminScriptHandler(nil) + options, err := h.buildAdminScriptShellOptions(&plugin_pb.ClusterContext{ + MasterGrpcAddresses: []string{"master:19333"}, + FilerAddresses: []string{"filer:8888.18890"}, + }) + if err != nil { + t.Fatalf("buildAdminScriptShellOptions returned err = %v", err) + } + if options.FilerTokenSource == nil { + t.Fatal("admin script shell options carry no filer token source") + } + token, err := options.FilerTokenSource(context.Background()) + if err != nil || !security.IsFilerAdminToken(key, token) { + t.Fatalf("admin script filer token is not a valid admin token for the configured key: err=%v", err) + } +} + func TestAdminScriptFilerAddressKeepsGrpcPortOffConvention(t *testing.T) { // FilerAddresses arrive as pb.ServerAddress (host:httpPort.grpcPort). The // shell derives the gRPC port from FilerAddress via ToGrpcAddress(); it must diff --git a/weed/query/engine/broker_client.go b/weed/query/engine/broker_client.go index 8df893546a..4ffa769ce0 100644 --- a/weed/query/engine/broker_client.go +++ b/weed/query/engine/broker_client.go @@ -17,8 +17,9 @@ import ( "github.com/seaweedfs/seaweedfs/weed/pb/master_pb" "github.com/seaweedfs/seaweedfs/weed/pb/mq_pb" "github.com/seaweedfs/seaweedfs/weed/pb/schema_pb" + "github.com/seaweedfs/seaweedfs/weed/security" + "github.com/seaweedfs/seaweedfs/weed/util" "google.golang.org/grpc" - "google.golang.org/grpc/credentials/insecure" jsonpb "google.golang.org/protobuf/encoding/protojson" ) @@ -33,6 +34,7 @@ type BrokerClient struct { filerAddress string brokerAddress string grpcDialOption grpc.DialOption + tokenSource security.FilerTokenSource } // NewBrokerClient creates a new MQ broker client @@ -44,7 +46,8 @@ func NewBrokerClient(masterHTTPAddress string) *BrokerClient { return &BrokerClient{ masterAddress: masterGRPCAddress, - grpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()), + grpcDialOption: security.LoadClientTLS(util.GetViper(), "grpc.client"), + tokenSource: security.FilerAdminToken, } } @@ -103,7 +106,7 @@ func (c *BrokerClient) findBrokerBalancer() error { } defer conn.Close() - client := filer_pb.NewSeaweedFilerClient(conn) + client := filer_pb.NewSeaweedFilerClient(security.WithFilerClientAuth(conn, c.tokenSource)) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() @@ -129,6 +132,7 @@ func (c *BrokerClient) GetFilerClient() (filer_pb.FilerClient, error) { return &filerClientImpl{ filerAddress: c.filerAddress, grpcDialOption: c.grpcDialOption, + tokenSource: c.tokenSource, }, nil } @@ -136,6 +140,7 @@ func (c *BrokerClient) GetFilerClient() (filer_pb.FilerClient, error) { type filerClientImpl struct { filerAddress string grpcDialOption grpc.DialOption + tokenSource security.FilerTokenSource } // WithFilerClient executes a function with a connected filer client @@ -146,7 +151,7 @@ func (f *filerClientImpl) WithFilerClient(followRedirect bool, fn func(client fi } defer conn.Close() - client := filer_pb.NewSeaweedFilerClient(conn) + client := filer_pb.NewSeaweedFilerClient(security.WithFilerClientAuth(conn, f.tokenSource)) return fn(client) } diff --git a/weed/query/engine/broker_client_auth_test.go b/weed/query/engine/broker_client_auth_test.go new file mode 100644 index 0000000000..884d31fd33 --- /dev/null +++ b/weed/query/engine/broker_client_auth_test.go @@ -0,0 +1,86 @@ +package engine + +import ( + "context" + "crypto/rand" + "encoding/hex" + "net" + "strings" + "testing" + + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/security" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" +) + +type queryAuthFiler struct { + filer_pb.UnimplementedSeaweedFilerServer + key security.SigningKey + authResults chan bool +} + +func (f *queryAuthFiler) LookupDirectoryEntry(ctx context.Context, req *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) { + md, _ := metadata.FromIncomingContext(ctx) + values := md.Get("authorization") + valid := len(values) == 1 && strings.HasPrefix(values[0], security.BearerPrefix) && + security.IsFilerAdminToken(f.key, security.EncodedJwt(strings.TrimPrefix(values[0], security.BearerPrefix))) + f.authResults <- valid + if !valid { + return nil, status.Error(codes.Unauthenticated, "missing or invalid filer authorization") + } + return &filer_pb.LookupDirectoryEntryResponse{ + Entry: &filer_pb.Entry{Name: req.Name, Attributes: &filer_pb.FuseAttributes{}}, + }, nil +} + +func queryTestSigningKey(t *testing.T) security.SigningKey { + t.Helper() + bytes := make([]byte, 32) + if _, err := rand.Read(bytes); err != nil { + t.Fatal(err) + } + return security.SigningKey(hex.EncodeToString(bytes)) +} + +func TestFilerClientImplSendsAdminToken(t *testing.T) { + key := queryTestSigningKey(t) + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + filer := &queryAuthFiler{key: key, authResults: make(chan bool, 1)} + server := grpc.NewServer() + filer_pb.RegisterSeaweedFilerServer(server, filer) + go server.Serve(listener) + t.Cleanup(func() { + server.Stop() + _ = listener.Close() + }) + + client := &filerClientImpl{ + filerAddress: listener.Addr().String(), + grpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()), + tokenSource: func(context.Context) (security.EncodedJwt, error) { + return security.GenJwtForFilerAdmin(key, 60), nil + }, + } + err = client.WithFilerClient(false, func(filerClient filer_pb.SeaweedFilerClient) error { + _, err := filerClient.LookupDirectoryEntry(context.Background(), &filer_pb.LookupDirectoryEntryRequest{Directory: "/", Name: "entry"}) + return err + }) + if err != nil { + t.Fatalf("WithFilerClient: %v", err) + } + select { + case valid := <-filer.authResults: + if !valid { + t.Fatal("filer rejected the per-call admin token") + } + default: + t.Fatal("filer did not receive the request") + } +} diff --git a/weed/remote_storage/track_sync_offset.go b/weed/remote_storage/track_sync_offset.go index a762a815e5..9642ca4c06 100644 --- a/weed/remote_storage/track_sync_offset.go +++ b/weed/remote_storage/track_sync_offset.go @@ -7,6 +7,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/pb" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/security" "github.com/seaweedfs/seaweedfs/weed/util" "google.golang.org/grpc" ) @@ -28,9 +29,9 @@ func SyncOffsetKey(dir string) []byte { // would hold the daemon's start, or its event stream behind the checkpoint. const syncOffsetTimeout = 30 * time.Second -func GetSyncOffset(grpcDialOption grpc.DialOption, filer pb.ServerAddress, dir string) (lastOffsetTsNs int64, readErr error) { +func GetSyncOffset(grpcDialOption grpc.DialOption, filer pb.ServerAddress, dir string, tokenSource ...security.FilerTokenSource) (lastOffsetTsNs int64, readErr error) { - readErr = pb.WithFilerClient(false, 0, filer, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + readErr = pb.WithGrpcFilerClient(false, 0, filer, grpcDialOption, firstTokenSource(tokenSource), func(client filer_pb.SeaweedFilerClient) error { ctx, cancel := context.WithTimeout(context.Background(), syncOffsetTimeout) defer cancel() resp, err := client.KvGet(ctx, &filer_pb.KvGetRequest{Key: SyncOffsetKey(dir)}) @@ -54,9 +55,9 @@ func GetSyncOffset(grpcDialOption grpc.DialOption, filer pb.ServerAddress, dir s } -func SetSyncOffset(grpcDialOption grpc.DialOption, filer pb.ServerAddress, dir string, offsetTsNs int64) error { +func SetSyncOffset(grpcDialOption grpc.DialOption, filer pb.ServerAddress, dir string, offsetTsNs int64, tokenSource ...security.FilerTokenSource) error { - return pb.WithFilerClient(false, 0, filer, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + return pb.WithGrpcFilerClient(false, 0, filer, grpcDialOption, firstTokenSource(tokenSource), func(client filer_pb.SeaweedFilerClient) error { valueBuf := make([]byte, 8) util.Uint64toBytes(valueBuf, uint64(offsetTsNs)) @@ -80,3 +81,10 @@ func SetSyncOffset(grpcDialOption grpc.DialOption, filer pb.ServerAddress, dir s }) } + +func firstTokenSource(sources []security.FilerTokenSource) security.FilerTokenSource { + if len(sources) == 0 { + return nil + } + return sources[0] +} diff --git a/weed/replication/replicator.go b/weed/replication/replicator.go index 190e39a630..6515ea6a4e 100644 --- a/weed/replication/replicator.go +++ b/weed/replication/replicator.go @@ -12,6 +12,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/replication/repl_util" "github.com/seaweedfs/seaweedfs/weed/replication/sink" "github.com/seaweedfs/seaweedfs/weed/replication/source" + "github.com/seaweedfs/seaweedfs/weed/security" "github.com/seaweedfs/seaweedfs/weed/util" "google.golang.org/grpc" ) @@ -26,12 +27,18 @@ func NewReplicator(sourceConfig util.Configuration, configPrefix string, dataSin source := &source.FilerSource{} source.Initialize(sourceConfig, configPrefix) + source.SetFilerTokenSource(security.FilerAdminToken) if err := repl_util.InitializeSSEForReplication(source); err != nil { glog.Warningf("SSE initialization failed: %v (encrypted objects may fail to replicate)", err) } dataSink.SetSourceFiler(source) + if tokenSink, ok := dataSink.(interface { + SetFilerTokenSource(security.FilerTokenSource) + }); ok { + tokenSink.SetFilerTokenSource(security.FilerAdminToken) + } return &Replicator{ sink: dataSink, @@ -180,8 +187,8 @@ func metadataEventTarget(key string, newEntry *filer_pb.Entry, newParentPath str // ReadFilerSignature returns the filer's signature and the digest it reports, // empty for a filer that predates the setting. -func ReadFilerSignature(grpcDialOption grpc.DialOption, filer pb.ServerAddress) (filerSignature int32, digest string, readErr error) { - if readErr = pb.WithFilerClient(false, 0, filer, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error { +func ReadFilerSignature(grpcDialOption grpc.DialOption, filer pb.ServerAddress, tokenSource security.FilerTokenSource) (filerSignature int32, digest string, readErr error) { + if readErr = pb.WithGrpcFilerClient(false, 0, filer, grpcDialOption, tokenSource, func(client filer_pb.SeaweedFilerClient) error { if resp, err := client.GetFilerConfiguration(context.Background(), &filer_pb.GetFilerConfigurationRequest{}); err != nil { return fmt.Errorf("GetFilerConfiguration %s: %v", filer, err) } else { diff --git a/weed/replication/sink/filersink/fetch_write.go b/weed/replication/sink/filersink/fetch_write.go index 5c9b5f2cea..dcf00fdd76 100644 --- a/weed/replication/sink/filersink/fetch_write.go +++ b/weed/replication/sink/filersink/fetch_write.go @@ -14,18 +14,18 @@ import ( "time" "github.com/schollz/progressbar/v3" + "google.golang.org/grpc" "google.golang.org/protobuf/proto" "github.com/seaweedfs/seaweedfs/weed/filer" "github.com/seaweedfs/seaweedfs/weed/util" - "google.golang.org/grpc" - "github.com/seaweedfs/seaweedfs/weed/glog" "github.com/seaweedfs/seaweedfs/weed/operation" "github.com/seaweedfs/seaweedfs/weed/pb" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/replication/source" + "github.com/seaweedfs/seaweedfs/weed/security" util_http "github.com/seaweedfs/seaweedfs/weed/util/http" ) @@ -779,7 +779,7 @@ var _ = filer_pb.FilerClient(&FilerSink{}) func (fs *FilerSink) WithFilerClient(streamingMode bool, fn func(filer_pb.SeaweedFilerClient) error) error { return pb.WithGrpcClient(context.Background(), streamingMode, fs.signature, func(grpcConnection *grpc.ClientConn) error { - client := filer_pb.NewSeaweedFilerClient(grpcConnection) + client := filer_pb.NewSeaweedFilerClient(security.WithFilerClientAuth(grpcConnection, fs.filerTokenSource)) return fn(client) }, fs.grpcAddress, false, fs.grpcDialOption) diff --git a/weed/replication/sink/filersink/filer_auth_test.go b/weed/replication/sink/filersink/filer_auth_test.go new file mode 100644 index 0000000000..d298090971 --- /dev/null +++ b/weed/replication/sink/filersink/filer_auth_test.go @@ -0,0 +1,196 @@ +package filersink + +import ( + "context" + "crypto/rand" + "encoding/hex" + "net" + "strings" + "sync/atomic" + "testing" + + "github.com/seaweedfs/seaweedfs/weed/pb" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/replication/source" + "github.com/seaweedfs/seaweedfs/weed/security" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" +) + +type adapterAuthFiler struct { + filer_pb.UnimplementedSeaweedFilerServer + key security.SigningKey + allowAnonymous bool + failFirstStream bool + subscribeCalls atomic.Int32 + createEntryCalls atomic.Int32 + configCalls atomic.Int32 +} + +func (f *adapterAuthFiler) authenticate(ctx context.Context) error { + md, _ := metadata.FromIncomingContext(ctx) + values := md.Get("authorization") + if len(values) == 0 && f.allowAnonymous { + return nil + } + if len(values) != 1 || !strings.HasPrefix(values[0], security.BearerPrefix) { + return status.Error(codes.Unauthenticated, "missing filer authorization") + } + if !security.IsFilerAdminToken(f.key, security.EncodedJwt(strings.TrimPrefix(values[0], security.BearerPrefix))) { + return status.Error(codes.Unauthenticated, "invalid filer authorization") + } + return nil +} + +func (f *adapterAuthFiler) SubscribeMetadata(_ *filer_pb.SubscribeMetadataRequest, stream filer_pb.SeaweedFiler_SubscribeMetadataServer) error { + if f.subscribeCalls.Add(1) == 1 && f.failFirstStream { + return status.Error(codes.Unavailable, "subscription dropped") + } + return stream.Send(&filer_pb.SubscribeMetadataResponse{TsNs: 1}) +} + +func (f *adapterAuthFiler) GetFilerConfiguration(context.Context, *filer_pb.GetFilerConfigurationRequest) (*filer_pb.GetFilerConfigurationResponse, error) { + f.configCalls.Add(1) + return &filer_pb.GetFilerConfigurationResponse{Signature: 1}, nil +} + +func (f *adapterAuthFiler) CreateEntry(_ context.Context, _ *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) { + f.createEntryCalls.Add(1) + return &filer_pb.CreateEntryResponse{}, nil +} + +func adapterTestKey(t *testing.T) security.SigningKey { + t.Helper() + buf := make([]byte, 32) + if _, err := rand.Read(buf); err != nil { + t.Fatal(err) + } + return security.SigningKey(hex.EncodeToString(buf)) +} + +func startAdapterAuthFiler(t *testing.T, filer *adapterAuthFiler) pb.ServerAddress { + t.Helper() + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + server := grpc.NewServer( + grpc.UnaryInterceptor(func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { + if err := filer.authenticate(ctx); err != nil { + return nil, err + } + return handler(ctx, req) + }), + grpc.StreamInterceptor(func(srv any, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { + if err := filer.authenticate(stream.Context()); err != nil { + return err + } + return handler(srv, stream) + }), + ) + filer_pb.RegisterSeaweedFilerServer(server, filer) + go func() { _ = server.Serve(listener) }() + t.Cleanup(func() { + server.Stop() + _ = listener.Close() + }) + port := listener.Addr().(*net.TCPAddr).Port + return pb.NewServerAddressWithGrpcPort(listener.Addr().String(), port) +} + +func TestFilerSyncAdaptersUseIndependentEndpointTokens(t *testing.T) { + sourceKey := adapterTestKey(t) + destinationKey := adapterTestKey(t) + if string(sourceKey) == string(destinationKey) { + t.Fatal("test endpoint keys unexpectedly match") + } + sourceFiler := &adapterAuthFiler{key: sourceKey, failFirstStream: true} + destinationFiler := &adapterAuthFiler{key: destinationKey} + sourceAddress := startAdapterAuthFiler(t, sourceFiler) + destinationAddress := startAdapterAuthFiler(t, destinationFiler) + dial := grpc.WithTransportCredentials(insecure.NewCredentials()) + + sourceClient := &source.FilerSource{} + if err := sourceClient.DoInitialize(sourceAddress.String(), sourceAddress.ToGrpcAddress(), "/", false); err != nil { + t.Fatal(err) + } + sourceClient.SetGrpcDialOption(dial) + sourceCalls := atomic.Int32{} + sourceClient.SetFilerTokenSource(func(context.Context) (security.EncodedJwt, error) { + sourceCalls.Add(1) + return security.GenJwtForFilerAdmin(sourceKey, 60), nil + }) + for attempt := 0; attempt < 2; attempt++ { + err := sourceClient.WithFilerClient(true, func(client filer_pb.SeaweedFilerClient) error { + stream, err := client.SubscribeMetadata(context.Background(), &filer_pb.SubscribeMetadataRequest{PathPrefix: "/"}) + if err != nil { + return err + } + _, err = stream.Recv() + return err + }) + if attempt == 0 && status.Code(err) != codes.Unavailable { + t.Fatalf("first source metadata attempt error = %v, want Unavailable", err) + } + if attempt == 1 && err != nil { + t.Fatalf("reconnected source metadata subscription: %v", err) + } + } + if sourceCalls.Load() < 2 || sourceFiler.subscribeCalls.Load() != 2 { + t.Fatalf("source token/subscription calls = %d/%d, want at least 2/2", sourceCalls.Load(), sourceFiler.subscribeCalls.Load()) + } + + destinationClient := &FilerSink{} + if err := destinationClient.DoInitialize(destinationAddress.String(), destinationAddress.ToGrpcAddress(), "/", "", "", 0, "", dial, false); err != nil { + t.Fatal(err) + } + destinationCalls := atomic.Int32{} + destinationClient.SetFilerTokenSource(func(context.Context) (security.EncodedJwt, error) { + destinationCalls.Add(1) + return security.GenJwtForFilerAdmin(destinationKey, 60), nil + }) + if err := destinationClient.CreateEntry("/file", &filer_pb.Entry{Name: "file"}, nil); err != nil { + t.Fatalf("destination create: %v", err) + } + if destinationCalls.Load() < 1 || destinationFiler.createEntryCalls.Load() != 1 { + t.Fatalf("destination token/create calls = %d/%d, want at least 1/1", destinationCalls.Load(), destinationFiler.createEntryCalls.Load()) + } +} + +func TestFilerSourceTokenResolutionFailureIsFailClosedAndNilIsLegacy(t *testing.T) { + key := adapterTestKey(t) + filer := &adapterAuthFiler{key: key, allowAnonymous: true} + address := startAdapterAuthFiler(t, filer) + dial := grpc.WithTransportCredentials(insecure.NewCredentials()) + client := &source.FilerSource{} + if err := client.DoInitialize(address.String(), address.ToGrpcAddress(), "/", false); err != nil { + t.Fatal(err) + } + client.SetGrpcDialOption(dial) + client.SetFilerTokenSource(func(context.Context) (security.EncodedJwt, error) { + return "", status.Error(codes.Unauthenticated, "token source unavailable") + }) + if err := client.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error { + _, err := client.GetFilerConfiguration(context.Background(), &filer_pb.GetFilerConfigurationRequest{}) + return err + }); err == nil { + t.Fatal("token source failure unexpectedly reached the filer") + } + if filer.configCalls.Load() != 0 || filer.subscribeCalls.Load() != 0 { + t.Fatalf("token source failure unexpectedly reached filer: configuration=%d subscriptions=%d", filer.configCalls.Load(), filer.subscribeCalls.Load()) + } + + client.SetFilerTokenSource(nil) + if err := client.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error { + _, err := client.GetFilerConfiguration(context.Background(), &filer_pb.GetFilerConfigurationRequest{}) + return err + }); err != nil { + t.Fatalf("nil token source did not preserve the legacy call: %v", err) + } + if filer.configCalls.Load() != 1 { + t.Fatalf("legacy call count = %d, want 1", filer.configCalls.Load()) + } +} diff --git a/weed/replication/sink/filersink/filer_sink.go b/weed/replication/sink/filersink/filer_sink.go index 2d7cba5968..bf294d50e4 100644 --- a/weed/replication/sink/filersink/filer_sink.go +++ b/weed/replication/sink/filersink/filer_sink.go @@ -65,6 +65,7 @@ type FilerSink struct { activeTransfers sync.Map // chunkFileId -> *ChunkTransferStatus uploader *operation.Uploader jwtForFiler security.FilerJwtProvider + filerTokenSource security.FilerTokenSource // lastServedFileId is the most recent chunk the source did serve, the probe // sourceStillServesChunks re-checks before writing an entry off. lastServedFileId atomic.Pointer[string] @@ -148,6 +149,12 @@ func (fs *FilerSink) SetFilerJwtProvider(provider security.FilerJwtProvider) { fs.jwtForFiler = provider } +// SetFilerTokenSource sets the per-RPC gRPC credential source for this filer. +// It is resolved again for every RPC attempt, including reconnects. +func (fs *FilerSink) SetFilerTokenSource(source security.FilerTokenSource) { + fs.filerTokenSource = source +} + func (fs *FilerSink) getUploader() (*operation.Uploader, error) { if fs.uploader != nil { return fs.uploader, nil diff --git a/weed/replication/source/filer_source.go b/weed/replication/source/filer_source.go index 2fb4dce206..382b49c7da 100644 --- a/weed/replication/source/filer_source.go +++ b/weed/replication/source/filer_source.go @@ -31,15 +31,16 @@ var ErrVolumeNotFound = errors.New("volume not found") var ErrChunkNotFound = errors.New("chunk not found on any volume replica") type FilerSource struct { - grpcAddress string - grpcDialOption grpc.DialOption - Dir string - address string - proxyByFiler bool - dataCenter string - signature int32 - httpClient *util_http_client.HTTPClient - jwtForFiler security.FilerJwtProvider + grpcAddress string + grpcDialOption grpc.DialOption + Dir string + address string + proxyByFiler bool + dataCenter string + signature int32 + httpClient *util_http_client.HTTPClient + jwtForFiler security.FilerJwtProvider + filerTokenSource security.FilerTokenSource digestMu sync.Mutex digestKnown bool @@ -81,6 +82,13 @@ func (fs *FilerSource) SetFilerJwtProvider(provider security.FilerJwtProvider) { fs.jwtForFiler = provider } +// SetFilerTokenSource sets the per-RPC gRPC credential source for this filer. +// It is separate from the HTTP filer JWT provider because each destination +// may use a different gRPC signing key. +func (fs *FilerSource) SetFilerTokenSource(source security.FilerTokenSource) { + fs.filerTokenSource = source +} + // FilerJwt returns the side-specific filer API credential, or nil when the // process-wide jwt.filer_signing configuration applies. // ProxyByFiler reports whether chunk reads are proxied through the source @@ -269,7 +277,7 @@ var _ = filer_pb.FilerClient(&FilerSource{}) func (fs *FilerSource) WithFilerClient(streamingMode bool, fn func(filer_pb.SeaweedFilerClient) error) error { return pb.WithGrpcClient(context.Background(), streamingMode, fs.signature, func(grpcConnection *grpc.ClientConn) error { - client := filer_pb.NewSeaweedFilerClient(grpcConnection) + client := filer_pb.NewSeaweedFilerClient(security.WithFilerClientAuth(grpcConnection, fs.filerTokenSource)) return fn(client) }, fs.grpcAddress, false, fs.grpcDialOption) diff --git a/weed/s3api/bucket_size_metrics.go b/weed/s3api/bucket_size_metrics.go index 0846923ff4..62cfd0a6ec 100644 --- a/weed/s3api/bucket_size_metrics.go +++ b/weed/s3api/bucket_size_metrics.go @@ -14,6 +14,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/pb" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/pb/master_pb" + "github.com/seaweedfs/seaweedfs/weed/security" "github.com/seaweedfs/seaweedfs/weed/stats" ) @@ -63,6 +64,7 @@ func (s3a *S3ApiServer) startBucketSizeMetricsLoop(ctx context.Context) { } filer := s3a.option.Filers[0] lockClient := cluster.NewLockClient(s3a.option.GrpcDialOption, filer) + lockClient.TokenSource = security.FilerAdminToken owner := string(filer) + "-s3-metrics" // Start long-lived lock - this S3 instance will only collect metrics when it holds the lock @@ -135,7 +137,7 @@ func (s3a *S3ApiServer) enforceBucketQuotas(ctx context.Context, buckets []*file return } - fc, err := filer.ReadFilerConfFromFilers(s3a.option.Filers, s3a.option.GrpcDialOption, nil) + fc, err := filer.ReadFilerConfFromFilers(s3a.option.Filers, s3a.option.GrpcDialOption, nil, security.FilerAdminToken) if err != nil { glog.V(1).Infof("read filer.conf for quota enforcement: %v", err) return diff --git a/weed/s3api/s3_sse_s3.go b/weed/s3api/s3_sse_s3.go index c014c47e18..254dc6e825 100644 --- a/weed/s3api/s3_sse_s3.go +++ b/weed/s3api/s3_sse_s3.go @@ -24,6 +24,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/pb" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants" + "github.com/seaweedfs/seaweedfs/weed/security" "github.com/seaweedfs/seaweedfs/weed/util" "github.com/seaweedfs/seaweedfs/weed/wdclient" "golang.org/x/crypto/hkdf" @@ -803,7 +804,7 @@ func (k *KeyManagerFilerClient) WithFilerClient(streamingMode bool, fn func(file if filerAddress == "" { return fmt.Errorf("no filer available") } - return pb.WithGrpcFilerClient(streamingMode, 0, filerAddress, k.grpcDialOption, fn) + return pb.WithGrpcFilerClient(streamingMode, 0, filerAddress, k.grpcDialOption, security.FilerAdminToken, fn) } // InitializeGlobalSSES3KeyManager initializes the global key manager with diff --git a/weed/s3api/s3api_bucket_handlers.go b/weed/s3api/s3api_bucket_handlers.go index 73fa2bd8ae..6d998fbe6a 100644 --- a/weed/s3api/s3api_bucket_handlers.go +++ b/weed/s3api/s3api_bucket_handlers.go @@ -31,6 +31,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/glog" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/security" util_http "github.com/seaweedfs/seaweedfs/weed/util/http" ) @@ -1210,7 +1211,7 @@ func (s3a *S3ApiServer) GetBucketLifecycleConfigurationHandler(w http.ResponseWr return } // ReadFilerConfFromFilers provides multi-filer failover - fc, err := filer.ReadFilerConfFromFilers(s3a.option.Filers, s3a.option.GrpcDialOption, nil) + fc, err := filer.ReadFilerConfFromFilers(s3a.option.Filers, s3a.option.GrpcDialOption, nil, security.FilerAdminToken) if err != nil { glog.Errorf("GetBucketLifecycleConfigurationHandler: %s", err) s3err.WriteErrorResponse(w, r, s3err.ErrInternalError) diff --git a/weed/s3api/s3api_circuit_breaker.go b/weed/s3api/s3api_circuit_breaker.go index 366f67f6b1..633e269acc 100644 --- a/weed/s3api/s3api_circuit_breaker.go +++ b/weed/s3api/s3api_circuit_breaker.go @@ -16,6 +16,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/pb/s3_pb" "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants" "github.com/seaweedfs/seaweedfs/weed/s3api/s3err" + "github.com/seaweedfs/seaweedfs/weed/security" "github.com/seaweedfs/seaweedfs/weed/stats" "github.com/seaweedfs/seaweedfs/weed/util" ) @@ -43,7 +44,7 @@ func NewCircuitBreaker(option *S3ApiServerOption) *CircuitBreaker { } // Use WithOneOfGrpcFilerClients to support multiple filers with failover - err := pb.WithOneOfGrpcFilerClients(false, option.Filers, option.GrpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + err := pb.WithOneOfGrpcFilerClients(false, option.Filers, option.GrpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error { content, err := filer.ReadInsideFiler(context.Background(), client, s3_constants.CircuitBreakerConfigDir, s3_constants.CircuitBreakerConfigFile) if errors.Is(err, filer_pb.ErrNotFound) { return nil diff --git a/weed/s3api/s3api_directory_marker.go b/weed/s3api/s3api_directory_marker.go index 036713d928..d73e1df853 100644 --- a/weed/s3api/s3api_directory_marker.go +++ b/weed/s3api/s3api_directory_marker.go @@ -10,6 +10,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants" "github.com/seaweedfs/seaweedfs/weed/s3api/s3err" + "github.com/seaweedfs/seaweedfs/weed/security" "github.com/seaweedfs/seaweedfs/weed/util" ) @@ -159,7 +160,7 @@ func (s3a *S3ApiServer) deleteDirectoryMarker(r *http.Request, bucket, object st } return s3err.ErrNone } - if err := pb.WithFilerClient(false, 0, priorOwner, s3a.option.GrpcDialOption, deleteMarker); err != nil { + if err := pb.WithGrpcFilerClient(false, 0, priorOwner, s3a.option.GrpcDialOption, security.FilerAdminToken, deleteMarker); err != nil { glog.Errorf("deleteDirectoryMarker: failed to delete %s/%s on prior owner %s: %v", bucket, object, priorOwner, err) return s3err.ErrInternalError } diff --git a/weed/s3api/s3api_filer_auth_test.go b/weed/s3api/s3api_filer_auth_test.go new file mode 100644 index 0000000000..2ed85d08b8 --- /dev/null +++ b/weed/s3api/s3api_filer_auth_test.go @@ -0,0 +1,321 @@ +package s3api + +import ( + "context" + "fmt" + "net" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/gorilla/mux" + "github.com/seaweedfs/seaweedfs/weed/filer" + "github.com/seaweedfs/seaweedfs/weed/pb" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/pb/s3_pb" + "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants" + "github.com/seaweedfs/seaweedfs/weed/security" + "github.com/seaweedfs/seaweedfs/weed/wdclient" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/encoding/protojson" +) + +type filerAuthTestServer struct { + filer_pb.UnimplementedSeaweedFilerServer + + mu sync.Mutex + authorizations [][]string + allowAnonymous bool + lookupContent []byte +} + +func (s *filerAuthTestServer) recordAuthorization(ctx context.Context) error { + md, _ := metadata.FromIncomingContext(ctx) + values := append([]string(nil), md.Get("authorization")...) + s.mu.Lock() + s.authorizations = append(s.authorizations, values) + allowAnonymous := s.allowAnonymous + s.mu.Unlock() + if allowAnonymous { + return nil + } + if len(values) != 1 || !strings.HasPrefix(values[0], security.BearerPrefix) { + return status.Error(codes.Unauthenticated, "missing filer admin token") + } + token := security.EncodedJwt(strings.TrimPrefix(values[0], security.BearerPrefix)) + if !security.IsFilerAdminToken(testFilerAuthKey, token) { + return status.Error(codes.Unauthenticated, "invalid filer admin token") + } + return nil +} + +func (s *filerAuthTestServer) CollectionList(ctx context.Context, _ *filer_pb.CollectionListRequest) (*filer_pb.CollectionListResponse, error) { + return &filer_pb.CollectionListResponse{}, nil +} + +func (s *filerAuthTestServer) LookupDirectoryEntry(_ context.Context, _ *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) { + return &filer_pb.LookupDirectoryEntryResponse{Entry: &filer_pb.Entry{Content: s.lookupContent}}, nil +} + +func (s *filerAuthTestServer) LookupVolume(_ context.Context, req *filer_pb.LookupVolumeRequest) (*filer_pb.LookupVolumeResponse, error) { + locations := make(map[string]*filer_pb.Locations, len(req.GetVolumeIds())) + for _, volumeID := range req.GetVolumeIds() { + locations[volumeID] = &filer_pb.Locations{} + } + return &filer_pb.LookupVolumeResponse{LocationsMap: locations}, nil +} + +func (s *filerAuthTestServer) ListEntries(_ *filer_pb.ListEntriesRequest, stream filer_pb.SeaweedFiler_ListEntriesServer) error { + return stream.Send(&filer_pb.ListEntriesResponse{Entry: &filer_pb.Entry{Name: "entry"}}) +} + +func (s *filerAuthTestServer) authorizationValues() [][]string { + s.mu.Lock() + defer s.mu.Unlock() + values := make([][]string, len(s.authorizations)) + for i, auth := range s.authorizations { + values[i] = append([]string(nil), auth...) + } + return values +} + +var testFilerAuthKey = security.SigningKey("s3-api-filer-auth-test-key-32-bytes-long") + +func startFilerAuthTestServer(t *testing.T, serverImpl *filerAuthTestServer) pb.ServerAddress { + t.Helper() + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + grpcServer := grpc.NewServer( + grpc.UnaryInterceptor(func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { + if err := serverImpl.recordAuthorization(ctx); err != nil { + return nil, err + } + return handler(ctx, req) + }), + grpc.StreamInterceptor(func(srv any, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { + if err := serverImpl.recordAuthorization(stream.Context()); err != nil { + return err + } + return handler(srv, stream) + }), + ) + filer_pb.RegisterSeaweedFilerServer(grpcServer, serverImpl) + go func() { _ = grpcServer.Serve(listener) }() + t.Cleanup(func() { + grpcServer.Stop() + _ = listener.Close() + }) + address := pb.ServerAddress(fmt.Sprintf("127.0.0.1:1.%d", listener.Addr().(*net.TCPAddr).Port)) + pb.InvalidateGrpcConnection(address.ToGrpcAddress()) + return address +} + +func startProtectedFilerAuthTestServer(t *testing.T, delegate filer_pb.SeaweedFilerServer) (*filerAuthTestServer, pb.ServerAddress) { + t.Helper() + auth := &filerAuthTestServer{} + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + grpcServer := grpc.NewServer( + grpc.UnaryInterceptor(func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { + if err := auth.recordAuthorization(ctx); err != nil { + return nil, err + } + return handler(ctx, req) + }), + grpc.StreamInterceptor(func(srv any, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { + if err := auth.recordAuthorization(stream.Context()); err != nil { + return err + } + return handler(srv, stream) + }), + ) + filer_pb.RegisterSeaweedFilerServer(grpcServer, delegate) + go func() { _ = grpcServer.Serve(listener) }() + t.Cleanup(func() { + grpcServer.Stop() + _ = listener.Close() + }) + return auth, pb.ServerAddress(fmt.Sprintf("127.0.0.1:1.%d", listener.Addr().(*net.TCPAddr).Port)) +} + +func setFilerAuthTestKey(t *testing.T, key string) { + t.Helper() + t.Setenv("WEED_JWT_FILER_SIGNING_GRPC_KEY", "") + t.Setenv("WEED_JWT_FILER_SIGNING_KEY", key) +} + +func TestS3FilerCallsCarryFreshAdminAuthForUnaryAndStreaming(t *testing.T) { + setFilerAuthTestKey(t, string(testFilerAuthKey)) + server := &filerAuthTestServer{} + address := startFilerAuthTestServer(t, server) + s3a := &S3ApiServer{ + option: &S3ApiServerOption{ + Filers: []pb.ServerAddress{address}, + GrpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()), + }, + } + + if err := s3a.withFilerClient(context.Background(), false, func(client filer_pb.SeaweedFilerClient) error { + _, err := client.CollectionList(context.Background(), &filer_pb.CollectionListRequest{}) + return err + }); err != nil { + t.Fatalf("unary filer call: %v", err) + } + if err := s3a.withFilerClient(context.Background(), true, func(client filer_pb.SeaweedFilerClient) error { + stream, err := client.ListEntries(context.Background(), &filer_pb.ListEntriesRequest{Directory: "/"}) + if err != nil { + return err + } + _, err = stream.Recv() + return err + }); err != nil { + t.Fatalf("streaming filer call: %v", err) + } + + for i, values := range server.authorizationValues() { + if len(values) != 1 || !strings.HasPrefix(values[0], security.BearerPrefix) { + t.Fatalf("call %d did not receive one bearer authorization", i) + } + } +} + +func TestS3FilerCallsRemainAnonymousWithoutAKey(t *testing.T) { + setFilerAuthTestKey(t, "") + server := &filerAuthTestServer{allowAnonymous: true} + address := startFilerAuthTestServer(t, server) + s3a := &S3ApiServer{ + option: &S3ApiServerOption{ + Filers: []pb.ServerAddress{address}, + GrpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()), + }, + } + if err := s3a.withFilerClient(context.Background(), false, func(client filer_pb.SeaweedFilerClient) error { + _, err := client.CollectionList(context.Background(), &filer_pb.CollectionListRequest{}) + return err + }); err != nil { + t.Fatalf("anonymous filer call: %v", err) + } + values := server.authorizationValues() + if len(values) != 1 || len(values[0]) != 0 { + t.Fatalf("filer call carried authorization, want anonymous") + } +} + +func TestInitializedS3FilerClientCarriesAdminAuth(t *testing.T) { + setFilerAuthTestKey(t, string(testFilerAuthKey)) + server := &filerAuthTestServer{} + address := startFilerAuthTestServer(t, server) + dialOption := grpc.WithTransportCredentials(insecure.NewCredentials()) + filerClient := wdclient.NewFilerClient([]pb.ServerAddress{address}, dialOption, "", &wdclient.FilerClientOption{ + FilerTokenSource: security.FilerAdminToken, + }) + if _, err := filerClient.LookupVolumeIdsAuthoritative(context.Background(), []string{"7"}); err != nil { + t.Fatalf("initialized filer client volume lookup: %v", err) + } + if values := server.authorizationValues(); len(values) != 1 || len(values[0]) != 1 { + t.Fatalf("initialized filer client did not send one authorization") + } +} + +func TestCircuitBreakerBootstrapCarriesAdminAuth(t *testing.T) { + setFilerAuthTestKey(t, string(testFilerAuthKey)) + config, err := protojson.Marshal(&s3_pb.S3CircuitBreakerConfig{ + Global: &s3_pb.S3CircuitBreakerOptions{ + Enabled: true, + Actions: map[string]int64{s3_constants.ACTION_WRITE: 1}, + }, + }) + if err != nil { + t.Fatal(err) + } + server := &filerAuthTestServer{lookupContent: config} + address := startFilerAuthTestServer(t, server) + cb := NewCircuitBreaker(&S3ApiServerOption{ + Filers: []pb.ServerAddress{address}, + GrpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()), + }) + if !cb.Enabled { + t.Fatal("circuit breaker configuration was not loaded") + } + values := server.authorizationValues() + if len(values) != 1 || len(values[0]) != 1 || !strings.HasPrefix(values[0][0], security.BearerPrefix) { + t.Fatal("circuit breaker bootstrap did not carry one bearer authorization") + } +} + +func TestS3FilerConfReadCarriesAdminAuth(t *testing.T) { + setFilerAuthTestKey(t, string(testFilerAuthKey)) + content, err := protojson.Marshal(&filer_pb.FilerConf{ + Version: filer.FilerConfVersion, + Locations: []*filer_pb.FilerConf_PathConf{{LocationPrefix: "/buckets/", Collection: "buckets"}}, + }) + if err != nil { + t.Fatal(err) + } + server := &filerAuthTestServer{lookupContent: content} + address := startFilerAuthTestServer(t, server) + fc, err := filer.ReadFilerConfFromFilers([]pb.ServerAddress{address}, grpc.WithTransportCredentials(insecure.NewCredentials()), nil, security.FilerAdminToken) + if err != nil { + t.Fatalf("read filer.conf: %v", err) + } + if got := fc.MatchStorageRule("/buckets/example").GetCollection(); got != "buckets" { + t.Fatalf("collection = %q, want buckets", got) + } + values := server.authorizationValues() + if len(values) != 1 || len(values[0]) != 1 || !strings.HasPrefix(values[0][0], security.BearerPrefix) { + t.Fatal("filer.conf read did not carry one bearer authorization") + } +} + +func TestS3MultipartHandlerCarriesAdminAuthToProtectedFiler(t *testing.T) { + setFilerAuthTestKey(t, string(testFilerAuthKey)) + volume := startFakeVolumeServer(t) + impl := &ambiguousPutFiler{ + volume: volume, + entries: map[string]*filer_pb.Entry{}, + apply: true, + } + impl.entries["/buckets/b"] = &filer_pb.Entry{ + Name: "b", + IsDirectory: true, + Attributes: &filer_pb.FuseAttributes{}, + } + auth, address := startProtectedFilerAuthTestServer(t, impl) + dialOption := grpc.WithTransportCredentials(insecure.NewCredentials()) + s3a := newPutTestServer(t, address) + s3a.filerClient = wdclient.NewFilerClient([]pb.ServerAddress{address}, dialOption, "", &wdclient.FilerClientOption{ + FilerTokenSource: security.FilerAdminToken, + }) + s3a.iam = NewIdentityAccessManagementWithStore(s3a.option, nil, "memory") + t.Cleanup(s3a.iam.Shutdown) + s3a.bucketConfigCache = NewBucketConfigCache(time.Minute) + s3a.bucketConfigCache.Set("b", &BucketConfig{Name: "b"}) + + req := httptest.NewRequest(http.MethodPost, "http://s3/b/o?uploads", nil) + req = mux.SetURLVars(req, map[string]string{"bucket": "b", "object": "o"}) + response := httptest.NewRecorder() + s3a.NewMultipartUploadHandler(response, req) + if response.Code != http.StatusOK { + t.Fatalf("multipart initiation status = %d, want 200: %s", response.Code, response.Body.String()) + } + values := auth.authorizationValues() + if len(values) == 0 { + t.Fatal("multipart initiation made no filer calls") + } + for i, authorization := range values { + if len(authorization) != 1 || !strings.HasPrefix(authorization[0], security.BearerPrefix) { + t.Fatalf("filer call %d did not carry one bearer authorization", i) + } + } +} diff --git a/weed/s3api/s3api_handlers.go b/weed/s3api/s3api_handlers.go index 32f6004fb6..fdaa7361a1 100644 --- a/weed/s3api/s3api_handlers.go +++ b/weed/s3api/s3api_handlers.go @@ -11,6 +11,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/glog" "github.com/seaweedfs/seaweedfs/weed/s3api/s3err" + "github.com/seaweedfs/seaweedfs/weed/security" "google.golang.org/grpc" "google.golang.org/grpc/connectivity" @@ -39,7 +40,7 @@ func (s3a *S3ApiServer) withFilerClient(ctx context.Context, streamingMode bool, // Fallback to direct connection if filerClient not initialized // This should only happen during initialization or testing return pb.WithGrpcClient(context.Background(), streamingMode, s3a.randomClientId, func(grpcConnection *grpc.ClientConn) error { - client := filer_pb.NewSeaweedFilerClient(grpcConnection) + client := filer_pb.NewSeaweedFilerClient(security.WithFilerClientAuth(grpcConnection, security.FilerAdminToken)) return fn(client) }, s3a.getFilerAddress().ToGrpcAddress(), false, s3a.option.GrpcDialOption) @@ -118,7 +119,8 @@ func (s3a *S3ApiServer) withFilerClientFailover(ctx context.Context, preferred p return errFilerConnNotReady } fnRan = true - return fn(filer_pb.NewSeaweedFilerClient(receiveTrackingConn{ClientConnInterface: grpcConnection, received: &received})) + authedConn := security.WithFilerClientAuth(grpcConnection, security.FilerAdminToken) + return fn(filer_pb.NewSeaweedFilerClient(receiveTrackingConn{ClientConnInterface: authedConn, received: &received})) }, filer.ToGrpcAddress(), false, s3a.option.GrpcDialOption) if err == nil { diff --git a/weed/s3api/s3api_object_handlers.go b/weed/s3api/s3api_object_handlers.go index 6cb5a855e8..d88a2637a5 100644 --- a/weed/s3api/s3api_object_handlers.go +++ b/weed/s3api/s3api_object_handlers.go @@ -3716,7 +3716,7 @@ func (s3a *S3ApiServer) doCacheRemoteObjectOnFiler(ctx context.Context, filer pb return s3a.doCacheRemoteObject(ctx, dir, name) } var cachedEntry *filer_pb.Entry - err := pb.WithFilerClient(false, 0, filer, s3a.option.GrpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + err := pb.WithGrpcFilerClient(false, 0, filer, s3a.option.GrpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error { resp, cacheErr := client.CacheRemoteObjectToLocalCluster(ctx, &filer_pb.CacheRemoteObjectToLocalClusterRequest{ Directory: dir, Name: name, diff --git a/weed/s3api/s3api_object_handlers_put.go b/weed/s3api/s3api_object_handlers_put.go index 1c3850851d..71735ad2ed 100644 --- a/weed/s3api/s3api_object_handlers_put.go +++ b/weed/s3api/s3api_object_handlers_put.go @@ -1106,7 +1106,7 @@ func (s3a *S3ApiServer) putToFiler(r *http.Request, filePath string, dataReader // its ring view agrees — exactly what is not guaranteed after an // ambiguous write. The create goes to the owner alone; an // unreachable owner leaves the outcome uncertain. - createErr = pb.WithFilerClient(false, 0, owner, s3a.option.GrpcDialOption, create) + createErr = pb.WithGrpcFilerClient(false, 0, owner, s3a.option.GrpcDialOption, security.FilerAdminToken, create) switch status.Code(createErr) { case codes.Unavailable, codes.Canceled, codes.DeadlineExceeded: s3a.markOwnerUnreachable(owner) diff --git a/weed/s3api/s3api_object_routed_read.go b/weed/s3api/s3api_object_routed_read.go index 9e633e815a..93f0820963 100644 --- a/weed/s3api/s3api_object_routed_read.go +++ b/weed/s3api/s3api_object_routed_read.go @@ -7,6 +7,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/pb" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/security" "github.com/seaweedfs/seaweedfs/weed/util" "google.golang.org/grpc" ) @@ -209,7 +210,7 @@ func (s3a *S3ApiServer) lookupEntryPreferringOwner(owner pb.ServerAddress, dir, // lookupEntryOnFiler resolves dir/name against a single filer, without failover. func (s3a *S3ApiServer) lookupEntryOnFiler(ctx context.Context, filer pb.ServerAddress, dir, name string) (*filer_pb.Entry, error) { var entry *filer_pb.Entry - err := pb.WithFilerClient(false, 0, filer, s3a.option.GrpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + err := pb.WithGrpcFilerClient(false, 0, filer, s3a.option.GrpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error { resp, lookupErr := filer_pb.LookupEntry(ctx, client, &filer_pb.LookupDirectoryEntryRequest{ Directory: dir, Name: name, diff --git a/weed/s3api/s3api_object_routed_upload.go b/weed/s3api/s3api_object_routed_upload.go index 50075df7de..bb65c60366 100644 --- a/weed/s3api/s3api_object_routed_upload.go +++ b/weed/s3api/s3api_object_routed_upload.go @@ -7,6 +7,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/pb" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/security" ) // uploadFilerClient reads and writes one multipart upload's .uploads/ @@ -79,7 +80,7 @@ func (u uploadFilerClient) list(parentDirectoryPath, prefix, startFrom string, i } var priorEntries []*filer_pb.Entry priorLast := false - priorErr := pb.WithFilerClient(true, 0, prior, u.s3a.option.GrpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + priorErr := pb.WithGrpcFilerClient(true, 0, prior, u.s3a.option.GrpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error { return filer_pb.SeaweedList(context.Background(), client, parentDirectoryPath, prefix, func(entry *filer_pb.Entry, isLastEntry bool) error { priorEntries = append(priorEntries, entry) priorLast = priorLast || isLastEntry diff --git a/weed/s3api/s3api_object_routed_write.go b/weed/s3api/s3api_object_routed_write.go index aa2f6d2e26..bc3d44782e 100644 --- a/weed/s3api/s3api_object_routed_write.go +++ b/weed/s3api/s3api_object_routed_write.go @@ -14,6 +14,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants" "github.com/seaweedfs/seaweedfs/weed/s3api/s3err" + "github.com/seaweedfs/seaweedfs/weed/security" "github.com/seaweedfs/seaweedfs/weed/util" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" @@ -167,7 +168,7 @@ func (s3a *S3ApiServer) objectTxnOnFiler(owner pb.ServerAddress, req *filer_pb.O return e } if s3a.filerClient == nil { - err := pb.WithFilerClient(false, 0, owner, s3a.option.GrpcDialOption, txn) + err := pb.WithGrpcFilerClient(false, 0, owner, s3a.option.GrpcDialOption, security.FilerAdminToken, txn) return resp, err } // Skip an owner whose recent write hit a transport error so a dead/stale @@ -192,7 +193,7 @@ func (s3a *S3ApiServer) withWriteOwnerFilerClient(owner pb.ServerAddress, fn fun return s3a.WithFilerClient(false, fn) } if s3a.filerClient == nil { - return pb.WithFilerClient(false, 0, owner, s3a.option.GrpcDialOption, fn) + return pb.WithGrpcFilerClient(false, 0, owner, s3a.option.GrpcDialOption, security.FilerAdminToken, fn) } preferred := owner if s3a.ownerRecentlyUnreachable(owner) { @@ -395,7 +396,7 @@ func (s3a *S3ApiServer) routedSelfCopy(ctx context.Context, owner pb.ServerAddre } var err error if s3a.filerClient == nil { - err = pb.WithFilerClient(false, 0, owner, s3a.option.GrpcDialOption, update) + err = pb.WithGrpcFilerClient(false, 0, owner, s3a.option.GrpcDialOption, security.FilerAdminToken, update) } else { err = s3a.withFilerClientFailover(ctx, owner, false, false, update) } diff --git a/weed/s3api/s3api_server.go b/weed/s3api/s3api_server.go index 719952ac0c..aae9b021cd 100644 --- a/weed/s3api/s3api_server.go +++ b/weed/s3api/s3api_server.go @@ -250,6 +250,7 @@ func NewS3ApiServerWithStore(router *mux.Router, option *S3ApiServerOption, expl // server's filer group. if len(option.Filers) > 0 { objectWriteLockClient = cluster.NewLockClient(option.GrpcDialOption, option.Filers[0]) + objectWriteLockClient.TokenSource = security.FilerAdminToken masterClient.SetOnLockRingUpdateFn(func(update *master_pb.LockRingUpdate) { servers := make([]pb.ServerAddress, 0, len(update.Servers)) for _, s := range update.Servers { @@ -267,6 +268,7 @@ func NewS3ApiServerWithStore(router *mux.Router, option *S3ApiServerOption, expl DiscoveryInterval: 5 * time.Minute, HomeFiler: option.HomeFiler, GrpcTimeout: option.VolumeLookupTimeout, + FilerTokenSource: security.FilerAdminToken, }) masterClient.SetOnPeerUpdateFn(filerClient.OnPeerUpdate) masterClient.SetOnVolumeLocationChangeFn(filerClient.OnVolumeLocationChange) @@ -281,8 +283,9 @@ func NewS3ApiServerWithStore(router *mux.Router, option *S3ApiServerOption, expl len(option.Filers), option.FilerGroup, option.Masters) } else { filerClient = wdclient.NewFilerClient(option.Filers, option.GrpcDialOption, option.DataCenter, &wdclient.FilerClientOption{ - HomeFiler: option.HomeFiler, - GrpcTimeout: option.VolumeLookupTimeout, + HomeFiler: option.HomeFiler, + GrpcTimeout: option.VolumeLookupTimeout, + FilerTokenSource: security.FilerAdminToken, }) glog.V(1).Infof("S3 API initialized FilerClient with %d filer(s) (no discovery)", len(option.Filers)) } @@ -389,6 +392,7 @@ func NewS3ApiServerWithStore(router *mux.Router, option *S3ApiServerOption, expl // ring updates); create a plain one when no masters are configured. if objectWriteLockClient == nil { objectWriteLockClient = cluster.NewLockClient(option.GrpcDialOption, option.Filers[0]) + objectWriteLockClient.TokenSource = security.FilerAdminToken } s3ApiServer.objectWriteLockClient = objectWriteLockClient s3ApiServer.newObjectWriteLock = func(bucket, object string) (objectWriteLock, error) { diff --git a/weed/security/filer_client_auth.go b/weed/security/filer_client_auth.go new file mode 100644 index 0000000000..8349392ac7 --- /dev/null +++ b/weed/security/filer_client_auth.go @@ -0,0 +1,246 @@ +package security + +import ( + "context" + "errors" + "os" + "strings" + "sync" + "time" + + "github.com/seaweedfs/seaweedfs/weed/util" + "github.com/spf13/viper" + "google.golang.org/grpc" + "google.golang.org/grpc/metadata" +) + +// FilerTokenSource resolves a logical client's token for one RPC attempt. +// An empty token leaves the call unchanged; an error prevents the call. +// Sources must be safe for concurrent use and must not log token material. +type FilerTokenSource func(context.Context) (EncodedJwt, error) + +// filerClientKeyTTL bounds how often a token source re-reads its security +// configuration. Reading and parsing the file costs far more than signing, and +// sources run on every RPC; a rotation is picked up within this interval. +var filerClientKeyTTL = time.Second + +var errFilerClientConfig = errors.New("filer: cannot read client security configuration") + +// filerClientKeys caches the signing keys read from one security +// configuration. A read failure is not cached, so the next call retries. +type filerClientKeys struct { + mu sync.Mutex + readAt time.Time + read bool + known bool // grpc and shared hold the last keys read successfully + grpc SigningKey + shared SigningKey + load func() (interface{ GetString(string) string }, error) + // fallback, when set, supplies keys for a failed read that has no last + // successful read to fall back to; without it a failed read fails closed. + fallback func() interface{ GetString(string) string } + // stamp identifies the inputs besides the file contents, such as the + // WEED_ environment overrides; a change invalidates the cached keys. + stamp func() string + stamped string +} + +// filerClientKeyEnvStamp covers the environment overrides of the two keys. +func filerClientKeyEnvStamp() string { + return os.Getenv("WEED_JWT_FILER_SIGNING_GRPC_KEY") + "\x00" + os.Getenv("WEED_JWT_FILER_SIGNING_KEY") +} + +func (k *filerClientKeys) get() (grpcKey, sharedKey SigningKey, err error) { + k.mu.Lock() + defer k.mu.Unlock() + stamp := "" + if k.stamp != nil { + stamp = k.stamp() + } + if k.read && stamp == k.stamped && time.Since(k.readAt) < filerClientKeyTTL { + return k.grpc, k.shared, nil + } + v, err := k.load() + if err == nil { + grpcKey, sharedKey, err = filerClientKeysFrom(v) + } + if err != nil { + k.read = false + if k.fallback == nil { + return nil, nil, err + } + if k.known { + return k.grpc, k.shared, nil + } + return filerClientKeysFrom(k.fallback()) + } + k.grpc, k.shared = grpcKey, sharedKey + k.readAt, k.read, k.known, k.stamped = time.Now(), true, true, stamp + return k.grpc, k.shared, nil +} + +// filerClientKeyCheck refuses keys that cannot sign in this process. +var filerClientKeyCheck = util.CheckFips140HmacKeys + +// filerClientKeysFrom reads the keys a client signs with. A key too short for +// GODEBUG=fips140=only is an error, as at startup, because signing with it +// would panic; a reloaded file is checked the same way. +func filerClientKeysFrom(v interface{ GetString(string) string }) (grpcKey, sharedKey SigningKey, err error) { + settings := []string{"jwt.filer_signing.grpc_key", "jwt.filer_signing.key"} + keys := []string{v.GetString(settings[0]), v.GetString(settings[1])} + if err := filerClientKeyCheck(settings, keys); err != nil { + return nil, nil, err + } + return SigningKey(keys[0]), SigningKey(keys[1]), nil +} + +func (k *filerClientKeys) token(ctx context.Context) (EncodedJwt, error) { + grpcKey, sharedKey, err := k.get() + if err != nil { + return "", err + } + return filerAdminTokenForKeys(ctx, grpcKey, sharedKey), nil +} + +// globalFilerClientKeys follows security.toml as the process finds it now. +// When the file exists but cannot be read (for example a root-only file in a +// non-root process, or a file being replaced), it keeps the last keys read, +// else the keys loaded at startup, as FilerAdminKeys does: a process that +// could never read the file keeps its existing tokenless behavior. +var globalFilerClientKeys = &filerClientKeys{ + load: func() (interface{ GetString(string) string }, error) { + v, _, err := util.ReadConfiguration("security", "") + if err != nil { + var notFound viper.ConfigFileNotFoundError + if !errors.As(err, ¬Found) { + return nil, errFilerClientConfig + } + } + return v, nil + }, + fallback: func() interface{ GetString(string) string } { return util.GetViper() }, + stamp: func() string { + return filerClientKeyEnvStamp() + "\x00" + util.ConfigurationFileDirectory.String() + }, +} + +// FilerAdminToken resolves the current filesystem gRPC signing key and mints +// a ten-second admin token. No key means no change to existing client behavior. +// grpc_require_token is a receiver policy, not a switch for presenting a key +// the client already holds. Previous keys are for verification, not signing. +func FilerAdminToken(ctx context.Context) (EncodedJwt, error) { + return globalFilerClientKeys.token(ctx) +} + +// FilerAdminTokenFromFile selects an endpoint's existing security file instead +// of the process-wide configuration. An unreadable file fails closed without +// using another endpoint's key. WEED_ environment overrides do not apply: they +// are process-wide, so honoring them would sign every endpoint's admin token +// with one key and hand one cluster a token valid on the other. An empty path +// selects FilerAdminToken. +func FilerAdminTokenFromFile(path string) FilerTokenSource { + if path == "" { + return FilerAdminToken + } + keys := &filerClientKeys{load: func() (interface{ GetString(string) string }, error) { + v := viper.New() + v.SetConfigFile(path) + if err := v.ReadInConfig(); err != nil { + // Parser errors can contain configuration values. Do not expose them. + return nil, errFilerClientConfig + } + return v, nil + }} + return keys.token +} + +type filerSubscriptionKey struct{} + +// withFilerSubscription marks a context as opening a metadata subscription. +func withFilerSubscription(ctx context.Context) context.Context { + return context.WithValue(ctx, filerSubscriptionKey{}, true) +} + +func isFilerSubscriptionMethod(method string) bool { + return method == "/filer_pb.SeaweedFiler/SubscribeMetadata" || + method == "/filer_pb.SeaweedFiler/SubscribeLocalMetadata" +} + +// filerAdminTokenForKeys signs with the key filesystem gRPC verifies: +// grpc_key when set, else the shared key. Metadata subscriptions prefer the +// shared key, as filer peers do, because older filers verify subscription +// admin tokens only with it. +func filerAdminTokenForKeys(ctx context.Context, grpcKey, sharedKey SigningKey) EncodedJwt { + key := grpcKey + if subscription, _ := ctx.Value(filerSubscriptionKey{}).(bool); (subscription && len(sharedKey) > 0) || len(key) == 0 { + key = sharedKey + } + return GenJwtForFilerAdmin(key, 10) +} + +// WithFilerSubscriptionToken is WithFilerToken for opening a metadata +// subscription; admin token sources then prefer the shared signing key. +func WithFilerSubscriptionToken(ctx context.Context, source FilerTokenSource) (context.Context, error) { + return WithFilerToken(withFilerSubscription(ctx), source) +} + +// WithFilerToken supplies outgoing authorization only when the caller has not +// already selected an identity. In particular, it never replaces a scoped +// bearer with admin authority. It preserves deadlines, cancellation and all +// unrelated metadata, without modifying the original context's metadata. +func WithFilerToken(ctx context.Context, source FilerTokenSource) (context.Context, error) { + md, _ := metadata.FromOutgoingContext(ctx) + if _, supplied := md["authorization"]; supplied || source == nil { + return ctx, nil + } + token, err := source(ctx) + if err != nil { + return nil, err + } + if token == "" { + return ctx, nil + } + md = md.Copy() + md.Set("authorization", BearerPrefix+string(token)) + return metadata.NewOutgoingContext(ctx, md), nil +} + +// WithFilerClientAuth wraps a connection interface for one logical client, +// without changing the underlying (possibly pooled) connection. Generated +// filer clients call Invoke/NewStream on this wrapper, so sources are resolved +// for each invocation even when callers construct their own contexts. Other +// gRPC services are left unchanged. Stream messages retain the opening identity. +func WithFilerClientAuth(conn grpc.ClientConnInterface, source FilerTokenSource) grpc.ClientConnInterface { + return &filerAuthConn{ClientConnInterface: conn, source: source} +} + +type filerAuthConn struct { + grpc.ClientConnInterface + source FilerTokenSource +} + +func (c *filerAuthConn) requestContext(ctx context.Context, method string) (context.Context, error) { + if !strings.HasPrefix(method, "/filer_pb.SeaweedFiler/") { + return ctx, nil + } + if isFilerSubscriptionMethod(method) { + return WithFilerSubscriptionToken(ctx, c.source) + } + return WithFilerToken(ctx, c.source) +} + +func (c *filerAuthConn) Invoke(ctx context.Context, method string, args, reply interface{}, opts ...grpc.CallOption) error { + ctx, err := c.requestContext(ctx, method) + if err != nil { + return err + } + return c.ClientConnInterface.Invoke(ctx, method, args, reply, opts...) +} + +func (c *filerAuthConn) NewStream(ctx context.Context, desc *grpc.StreamDesc, method string, opts ...grpc.CallOption) (grpc.ClientStream, error) { + ctx, err := c.requestContext(ctx, method) + if err != nil { + return nil, err + } + return c.ClientConnInterface.NewStream(ctx, desc, method, opts...) +} diff --git a/weed/security/filer_client_auth_test.go b/weed/security/filer_client_auth_test.go new file mode 100644 index 0000000000..ea74fec145 --- /dev/null +++ b/weed/security/filer_client_auth_test.go @@ -0,0 +1,654 @@ +package security + +import ( + "context" + "crypto/rand" + "encoding/hex" + "errors" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweedfs/weed/util" + "github.com/spf13/viper" + "google.golang.org/grpc" + "google.golang.org/grpc/metadata" +) + +func testSigningKey(t *testing.T) SigningKey { + t.Helper() + bytes := make([]byte, 32) + if _, err := rand.Read(bytes); err != nil { + t.Fatal(err) + } + return SigningKey(hex.EncodeToString(bytes)) +} + +func TestWithFilerTokenPreservesContextAndMetadata(t *testing.T) { + key := testSigningKey(t) + token := GenJwtForFilerAdmin(key, 60) + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + ctx = metadata.AppendToOutgoingContext(ctx, "trace-id", "trace-value") + + var sourceContext context.Context + withToken, err := WithFilerToken(ctx, func(got context.Context) (EncodedJwt, error) { + sourceContext = got + return token, nil + }) + if err != nil { + t.Fatalf("WithFilerToken returned error: %v", err) + } + if sourceContext != ctx { + t.Fatal("token source did not receive the caller context") + } + gotDeadline, gotDeadlineOK := withToken.Deadline() + wantDeadline, wantDeadlineOK := ctx.Deadline() + if !gotDeadlineOK || !wantDeadlineOK || !gotDeadline.Equal(wantDeadline) { + t.Fatalf("deadline changed: got (%v, %v), want (%v, %v)", gotDeadline, gotDeadlineOK, wantDeadline, wantDeadlineOK) + } + + md, ok := metadata.FromOutgoingContext(withToken) + if !ok || len(md.Get("authorization")) != 1 || md.Get("authorization")[0] != BearerPrefix+string(token) { + t.Fatal("authorization metadata did not contain exactly one expected bearer token") + } + if len(md.Get("trace-id")) != 1 || md.Get("trace-id")[0] != "trace-value" { + t.Fatal("unrelated outgoing metadata was not preserved") + } + original, _ := metadata.FromOutgoingContext(ctx) + if len(original.Get("authorization")) != 0 { + t.Fatal("WithFilerToken mutated the caller metadata") + } + + cancel() + if withToken.Err() != context.Canceled { + t.Fatalf("wrapped context error = %v, want cancellation", withToken.Err()) + } +} + +func TestWithFilerTokenSkipsExplicitIdentityAndEmptySource(t *testing.T) { + tests := []struct { + name string + ctx context.Context + want string + }{ + {name: "nil source", ctx: context.Background(), want: ""}, + { + name: "empty token", + ctx: context.Background(), + want: "", + }, + { + name: "caller identity", + ctx: metadata.AppendToOutgoingContext(context.Background(), "authorization", "Bearer caller-token"), + want: "Bearer caller-token", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + calls := 0 + source := FilerTokenSource(nil) + if tt.name == "empty token" || tt.name == "caller identity" { + source = func(context.Context) (EncodedJwt, error) { + calls++ + return "", nil + } + } + got, err := WithFilerToken(tt.ctx, source) + if err != nil { + t.Fatalf("WithFilerToken returned error: %v", err) + } + md, _ := metadata.FromOutgoingContext(got) + values := md.Get("authorization") + if tt.want == "" && len(values) != 0 { + t.Fatal("unexpected authorization metadata for an anonymous call") + } + if tt.want != "" && (len(values) != 1 || values[0] != tt.want) { + t.Fatal("explicit caller authorization metadata was not preserved") + } + if tt.name == "caller identity" && calls != 0 { + t.Fatalf("source called %d times for explicit caller identity", calls) + } + }) + } +} + +func TestWithFilerTokenReturnsSourceError(t *testing.T) { + want := errors.New("token source failed") + got, err := WithFilerToken(context.Background(), func(context.Context) (EncodedJwt, error) { + return "", want + }) + if !errors.Is(err, want) { + t.Fatalf("error = %v, want %v", err, want) + } + if got != nil { + t.Fatal("failed token resolution returned a context") + } +} + +type recordingClientConn struct { + invokes int + newStream int + contexts []context.Context +} + +func (c *recordingClientConn) Invoke(ctx context.Context, _ string, _, _ interface{}, _ ...grpc.CallOption) error { + c.invokes++ + c.contexts = append(c.contexts, ctx) + return nil +} + +func (c *recordingClientConn) NewStream(ctx context.Context, _ *grpc.StreamDesc, _ string, _ ...grpc.CallOption) (grpc.ClientStream, error) { + c.newStream++ + c.contexts = append(c.contexts, ctx) + return nil, nil +} + +func TestWithFilerClientAuthProtectsServicePrefix(t *testing.T) { + key := testSigningKey(t) + token := GenJwtForFilerAdmin(key, 60) + calls := 0 + conn := &recordingClientConn{} + wrapped := WithFilerClientAuth(conn, func(context.Context) (EncodedJwt, error) { + calls++ + return token, nil + }) + + for _, method := range []string{ + "/other.Service/Call", + "/filer_pb.SeaweedFilerEvil/Call", + } { + if err := wrapped.Invoke(context.Background(), method, nil, nil); err != nil { + t.Fatalf("Invoke(%q): %v", method, err) + } + } + if calls != 0 { + t.Fatalf("token source called %d times for non-filer methods", calls) + } + + if err := wrapped.Invoke(context.Background(), "/filer_pb.SeaweedFiler/LookupDirectoryEntry", nil, nil); err != nil { + t.Fatalf("filer Invoke: %v", err) + } + if calls != 1 { + t.Fatalf("token source called %d times, want one filer call", calls) + } + md, _ := metadata.FromOutgoingContext(conn.contexts[len(conn.contexts)-1]) + if len(md.Get("authorization")) != 1 || !IsFilerAdminToken(key, EncodedJwt(md.Get("authorization")[0][len(BearerPrefix):])) { + t.Fatal("filer call did not receive a valid admin token") + } + + if _, err := wrapped.NewStream(context.Background(), &grpc.StreamDesc{}, "/other.Service/Stream"); err != nil { + t.Fatalf("non-filer NewStream: %v", err) + } + if _, err := wrapped.NewStream(context.Background(), &grpc.StreamDesc{}, "/filer_pb.SeaweedFiler/ListEntries"); err != nil { + t.Fatalf("filer NewStream: %v", err) + } + if calls != 2 { + t.Fatalf("token source called %d times after stream calls, want two", calls) + } +} + +func TestWithFilerClientAuthSourceErrorDoesNotReachConnection(t *testing.T) { + want := errors.New("token source failed") + conn := &recordingClientConn{} + wrapped := WithFilerClientAuth(conn, func(context.Context) (EncodedJwt, error) { + return "", want + }) + if err := wrapped.Invoke(context.Background(), "/filer_pb.SeaweedFiler/LookupDirectoryEntry", nil, nil); !errors.Is(err, want) { + t.Fatal("Invoke did not return the token source error") + } + if _, err := wrapped.NewStream(context.Background(), &grpc.StreamDesc{}, "/filer_pb.SeaweedFiler/ListEntries"); !errors.Is(err, want) { + t.Fatal("NewStream did not return the token source error") + } + if conn.invokes != 0 || conn.newStream != 0 { + t.Fatalf("connection received calls after token source failure: invokes=%d streams=%d", conn.invokes, conn.newStream) + } +} + +func filerAdminToken(t *testing.T, v interface{ GetString(string) string }) EncodedJwt { + t.Helper() + grpcKey, sharedKey, err := filerClientKeysFrom(v) + if err != nil { + t.Fatal(err) + } + return filerAdminTokenForKeys(context.Background(), grpcKey, sharedKey) +} + +func TestFilerAdminTokenKeyPrecedenceAndNoKey(t *testing.T) { + v := viper.New() + grpcKey := testSigningKey(t) + httpKey := testSigningKey(t) + v.Set("jwt.filer_signing.grpc_key", string(grpcKey)) + v.Set("jwt.filer_signing.key", string(httpKey)) + t.Cleanup(func() { + v.Set("jwt.filer_signing.grpc_key", "") + v.Set("jwt.filer_signing.key", "") + }) + + token := filerAdminToken(t, v) + if !IsFilerAdminToken(grpcKey, token) || IsFilerAdminToken(httpKey, token) { + t.Fatal("grpc_key did not take precedence over the HTTP signing key") + } + + v.Set("jwt.filer_signing.grpc_key", "") + token = filerAdminToken(t, v) + if !IsFilerAdminToken(httpKey, token) { + t.Fatal("HTTP signing-key fallback did not produce a valid token") + } + v.Set("jwt.filer_signing.key", "") + token = filerAdminToken(t, v) + if token != "" { + t.Fatal("no configured key produced a token") + } +} + +func TestFilerAdminTokenHasTenSecondExpiry(t *testing.T) { + v := viper.New() + key := testSigningKey(t) + v.Set("jwt.filer_signing.grpc_key", string(key)) + token := filerAdminToken(t, v) + claims := &SeaweedFilerAdminClaims{} + parsed, err := DecodeJwt(key, token, claims) + if err != nil || parsed == nil || !parsed.Valid || claims.ExpiresAt == nil { + t.Fatal("admin token did not decode with an expiry") + } + remaining := time.Until(claims.ExpiresAt.Time) + if remaining < 9*time.Second || remaining > 10*time.Second { + t.Fatal("admin token expiry was outside the ten-second window") + } +} + +func writeFilerSecurityToml(t *testing.T, path string, grpcKey, httpKey SigningKey) { + t.Helper() + contents := "[jwt.filer_signing]\n" + if len(grpcKey) > 0 { + contents += "grpc_key = \"" + string(grpcKey) + "\"\n" + } + if len(httpKey) > 0 { + contents += "key = \"" + string(httpKey) + "\"\n" + } + if err := os.WriteFile(path, []byte(contents), 0600); err != nil { + t.Fatal(err) + } +} + +// readFilerClientKeysEveryCall makes token sources re-read their +// configuration on every call, so rotation tests observe each file change. +func readFilerClientKeysEveryCall(t *testing.T) { + t.Helper() + saved := filerClientKeyTTL + filerClientKeyTTL = 0 + resetGlobalFilerClientKeys() + t.Cleanup(func() { + filerClientKeyTTL = saved + resetGlobalFilerClientKeys() + }) +} + +func resetGlobalFilerClientKeys() { + globalFilerClientKeys.mu.Lock() + globalFilerClientKeys.read = false + globalFilerClientKeys.known = false + globalFilerClientKeys.mu.Unlock() +} + +func TestFilerAdminTokenReloadsConfigurationAndKeepsLastKeysOnReadError(t *testing.T) { + readFilerClientKeysEveryCall(t) + dir := t.TempDir() + savedDirectory := util.ConfigurationFileDirectory + util.ConfigurationFileDirectory = util.DirectoryValueType(dir) + t.Cleanup(func() { util.ConfigurationFileDirectory = savedDirectory }) + path := filepath.Join(dir, "security.toml") + keyA := testSigningKey(t) + keyB := testSigningKey(t) + writeFilerSecurityToml(t, path, keyA, SigningKey("")) + + token, err := FilerAdminToken(context.Background()) + if err != nil || !IsFilerAdminToken(keyA, token) { + t.Fatal("global source did not use the configured current key") + } + writeFilerSecurityToml(t, path, keyB, SigningKey("")) + token, err = FilerAdminToken(context.Background()) + if err != nil || !IsFilerAdminToken(keyB, token) || IsFilerAdminToken(keyA, token) { + t.Fatal("global source did not reload the rotated key") + } + writeFilerSecurityToml(t, path, SigningKey(""), SigningKey("")) + token, err = FilerAdminToken(context.Background()) + if err != nil || token != "" { + t.Fatalf("keyless configuration returned token=%t err=%v", token != "", err) + } + writeFilerSecurityToml(t, path, keyA, SigningKey("")) + if token, err = FilerAdminToken(context.Background()); err != nil || !IsFilerAdminToken(keyA, token) { + t.Fatal("global source did not read the restored key") + } + if err := os.WriteFile(path, []byte("[jwt.filer_signing\n"), 0600); err != nil { + t.Fatal(err) + } + token, err = FilerAdminToken(context.Background()) + if err != nil || !IsFilerAdminToken(keyA, token) { + t.Fatalf("unreadable configuration did not keep the last keys: token=%t err=%v", token != "", err) + } + if err := os.Remove(path); err != nil { + t.Fatal(err) + } + token, err = FilerAdminToken(context.Background()) + if err != nil || token != "" { + t.Fatalf("deleted configuration returned token=%t err=%v", token != "", err) + } +} + +func writeFilerSecurityConfig(t *testing.T, path string, grpcKey, httpKey SigningKey) { + t.Helper() + contents := "jwt:\n filer_signing:\n" + if len(grpcKey) > 0 { + contents += " grpc_key: \"" + string(grpcKey) + "\"\n" + } + if len(httpKey) > 0 { + contents += " key: \"" + string(httpKey) + "\"\n" + } + if err := os.WriteFile(path, []byte(contents), 0600); err != nil { + t.Fatal(err) + } +} + +func TestFilerAdminTokenFromFileUsesIndependentRotatingSources(t *testing.T) { + readFilerClientKeysEveryCall(t) + dir := t.TempDir() + pathA := filepath.Join(dir, "endpoint-a.yaml") + pathB := filepath.Join(dir, "endpoint-b.yaml") + keyA1 := testSigningKey(t) + keyA2 := testSigningKey(t) + keyB := testSigningKey(t) + writeFilerSecurityConfig(t, pathA, keyA1, SigningKey("")) + writeFilerSecurityConfig(t, pathB, SigningKey(""), keyB) + + sourceA := FilerAdminTokenFromFile(pathA) + sourceB := FilerAdminTokenFromFile(pathB) + token, err := sourceA(context.Background()) + if err != nil || !IsFilerAdminToken(keyA1, token) || IsFilerAdminToken(keyA2, token) { + t.Fatalf("endpoint A initial token valid for expected key=%v wrong key=%v err=%v", IsFilerAdminToken(keyA1, token), IsFilerAdminToken(keyA2, token), err) + } + token, err = sourceB(context.Background()) + if err != nil || !IsFilerAdminToken(keyB, token) { + t.Fatalf("endpoint B token valid=%v err=%v", IsFilerAdminToken(keyB, token), err) + } + + writeFilerSecurityConfig(t, pathA, keyA2, SigningKey("")) + token, err = sourceA(context.Background()) + if err != nil || !IsFilerAdminToken(keyA2, token) || IsFilerAdminToken(keyA1, token) { + t.Fatalf("endpoint A rotated token valid for new key=%v old key=%v err=%v", IsFilerAdminToken(keyA2, token), IsFilerAdminToken(keyA1, token), err) + } + writeFilerSecurityConfig(t, pathA, SigningKey(""), SigningKey("")) + token, err = sourceA(context.Background()) + if err != nil || token != "" { + t.Fatalf("readable keyless endpoint A returned token=%t err=%v", token != "", err) + } + if err := os.Remove(pathA); err != nil { + t.Fatal(err) + } + token, err = sourceA(context.Background()) + if err == nil || token != "" { + t.Fatalf("removed endpoint A config returned token=%t err=%v", token != "", err) + } + // The independent endpoint remains readable after endpoint A is removed. + token, err = sourceB(context.Background()) + if err != nil || !IsFilerAdminToken(keyB, token) { + t.Fatalf("endpoint B after endpoint A removal valid=%v err=%v", IsFilerAdminToken(keyB, token), err) + } +} + +// TestFilerAdminTokenFromFileIgnoresEnvironmentOverrides covers filer.sync +// between two clusters: a process-wide WEED_ key must not replace either +// endpoint's key, or one cluster would receive a token valid on the other. +func TestFilerAdminTokenFromFileIgnoresEnvironmentOverrides(t *testing.T) { + readFilerClientKeysEveryCall(t) + dir := t.TempDir() + pathA := filepath.Join(dir, "endpoint-a.yaml") + pathB := filepath.Join(dir, "endpoint-b.yaml") + keyA := testSigningKey(t) + keyB := testSigningKey(t) + envKey := testSigningKey(t) + writeFilerSecurityConfig(t, pathA, keyA, SigningKey("")) + writeFilerSecurityConfig(t, pathB, SigningKey(""), keyB) + t.Setenv("WEED_JWT_FILER_SIGNING_GRPC_KEY", string(envKey)) + t.Setenv("WEED_JWT_FILER_SIGNING_KEY", string(envKey)) + + for _, endpoint := range []struct { + path string + key SigningKey + }{{pathA, keyA}, {pathB, keyB}} { + token, err := FilerAdminTokenFromFile(endpoint.path)(context.Background()) + if err != nil || !IsFilerAdminToken(endpoint.key, token) || IsFilerAdminToken(envKey, token) { + t.Fatalf("%s: token valid for its own key=%v, for the environment key=%v, err=%v", + filepath.Base(endpoint.path), IsFilerAdminToken(endpoint.key, token), IsFilerAdminToken(envKey, token), err) + } + } + // A file without keys stays keyless rather than adopting the environment's. + keyless := filepath.Join(dir, "keyless.yaml") + writeFilerSecurityConfig(t, keyless, SigningKey(""), SigningKey("")) + if token, err := FilerAdminTokenFromFile(keyless)(context.Background()); err != nil || token != "" { + t.Fatalf("keyless endpoint returned token=%t err=%v", token != "", err) + } +} + +func TestFilerAdminTokenFromFileFailsClosedForMissingOrMalformedConfig(t *testing.T) { + dir := t.TempDir() + missing := filepath.Join(dir, "missing.yaml") + source := FilerAdminTokenFromFile(missing) + token, err := source(context.Background()) + if err == nil || token != "" { + t.Fatalf("missing config returned token=%t err=%v", token != "", err) + } + + malformed := filepath.Join(dir, "malformed.yaml") + if err := os.WriteFile(malformed, []byte("jwt:\n filer_signing: [\n"), 0600); err != nil { + t.Fatal(err) + } + token, err = FilerAdminTokenFromFile(malformed)(context.Background()) + if err == nil || token != "" { + t.Fatalf("malformed config returned token=%t err=%v", token != "", err) + } +} + +func TestFilerAdminTokenCachesKeysWithinRefreshInterval(t *testing.T) { + saved := filerClientKeyTTL + filerClientKeyTTL = time.Hour + resetGlobalFilerClientKeys() + t.Cleanup(func() { + filerClientKeyTTL = saved + resetGlobalFilerClientKeys() + }) + dir := t.TempDir() + savedDirectory := util.ConfigurationFileDirectory + util.ConfigurationFileDirectory = util.DirectoryValueType(dir) + t.Cleanup(func() { util.ConfigurationFileDirectory = savedDirectory }) + path := filepath.Join(dir, "security.toml") + keyA := testSigningKey(t) + keyB := testSigningKey(t) + writeFilerSecurityToml(t, path, keyA, SigningKey("")) + + token, err := FilerAdminToken(context.Background()) + if err != nil || !IsFilerAdminToken(keyA, token) { + t.Fatal("global source did not use the configured key") + } + writeFilerSecurityToml(t, path, keyB, SigningKey("")) + token, err = FilerAdminToken(context.Background()) + if err != nil || !IsFilerAdminToken(keyA, token) { + t.Fatal("global source re-read its configuration within the refresh interval") + } + + globalFilerClientKeys.mu.Lock() + globalFilerClientKeys.readAt = time.Now().Add(-2 * time.Hour) + globalFilerClientKeys.mu.Unlock() + token, err = FilerAdminToken(context.Background()) + if err != nil || !IsFilerAdminToken(keyB, token) || IsFilerAdminToken(keyA, token) { + t.Fatal("global source did not pick up the rotated key after the refresh interval") + } + + // Changing an environment override takes effect at once. + envKey := testSigningKey(t) + t.Setenv("WEED_JWT_FILER_SIGNING_GRPC_KEY", string(envKey)) + if token, err = FilerAdminToken(context.Background()); err != nil || !IsFilerAdminToken(envKey, token) { + t.Fatal("global source did not follow a changed environment override") + } + os.Unsetenv("WEED_JWT_FILER_SIGNING_GRPC_KEY") + if token, err = FilerAdminToken(context.Background()); err != nil || !IsFilerAdminToken(keyB, token) { + t.Fatal("global source did not follow a removed environment override") + } + + // A failed read keeps the last keys and is not cached: the next call + // reads the repaired file without waiting for the interval. + if err := os.WriteFile(path, []byte("[jwt.filer_signing\n"), 0600); err != nil { + t.Fatal(err) + } + globalFilerClientKeys.mu.Lock() + globalFilerClientKeys.readAt = time.Now().Add(-2 * time.Hour) + globalFilerClientKeys.mu.Unlock() + if token, err = FilerAdminToken(context.Background()); err != nil || !IsFilerAdminToken(keyB, token) { + t.Fatalf("unreadable configuration did not keep the last keys: token=%t err=%v", token != "", err) + } + writeFilerSecurityToml(t, path, keyA, SigningKey("")) + if token, err = FilerAdminToken(context.Background()); err != nil || !IsFilerAdminToken(keyA, token) { + t.Fatal("global source did not recover after the configuration was repaired") + } +} + +func TestFilerAdminTokenUnreadableConfigurationKeepsStartupKeys(t *testing.T) { + readFilerClientKeysEveryCall(t) + dir := t.TempDir() + savedDirectory := util.ConfigurationFileDirectory + util.ConfigurationFileDirectory = util.DirectoryValueType(dir) + t.Cleanup(func() { util.ConfigurationFileDirectory = savedDirectory }) + if err := os.WriteFile(filepath.Join(dir, "security.toml"), []byte("[jwt.filer_signing\n"), 0600); err != nil { + t.Fatal(err) + } + startup := util.GetViper() + savedGrpc, savedShared := startup.GetString("jwt.filer_signing.grpc_key"), startup.GetString("jwt.filer_signing.key") + t.Cleanup(func() { + startup.Set("jwt.filer_signing.grpc_key", savedGrpc) + startup.Set("jwt.filer_signing.key", savedShared) + }) + + // A process that never read a key keeps its tokenless behavior. + startup.Set("jwt.filer_signing.grpc_key", "") + startup.Set("jwt.filer_signing.key", "") + if token, err := FilerAdminToken(context.Background()); err != nil || token != "" { + t.Fatalf("unreadable configuration without startup keys returned token=%t err=%v", token != "", err) + } + key := testSigningKey(t) + startup.Set("jwt.filer_signing.key", string(key)) + if token, err := FilerAdminToken(context.Background()); err != nil || !IsFilerAdminToken(key, token) { + t.Fatalf("unreadable configuration did not use the startup key: err=%v", err) + } +} + +func TestFilerSubscriptionTokensPreferSharedKey(t *testing.T) { + grpcKey := testSigningKey(t) + sharedKey := testSigningKey(t) + bearer := func(ctx context.Context) EncodedJwt { + t.Helper() + md, _ := metadata.FromOutgoingContext(ctx) + values := md.Get("authorization") + if len(values) != 1 { + t.Fatalf("got %d authorization values, want 1", len(values)) + } + return EncodedJwt(values[0][len(BearerPrefix):]) + } + + for _, tc := range []struct { + name string + grpcKey, sharedKey SigningKey + wantCall, wantStream SigningKey + }{ + {name: "both keys", grpcKey: grpcKey, sharedKey: sharedKey, wantCall: grpcKey, wantStream: sharedKey}, + {name: "grpc key only", grpcKey: grpcKey, wantCall: grpcKey, wantStream: grpcKey}, + {name: "shared key only", sharedKey: sharedKey, wantCall: sharedKey, wantStream: sharedKey}, + } { + t.Run(tc.name, func(t *testing.T) { + v := viper.New() + v.Set("jwt.filer_signing.grpc_key", string(tc.grpcKey)) + v.Set("jwt.filer_signing.key", string(tc.sharedKey)) + source := func(ctx context.Context) (EncodedJwt, error) { + return filerAdminTokenForKeys(ctx, SigningKey(v.GetString("jwt.filer_signing.grpc_key")), SigningKey(v.GetString("jwt.filer_signing.key"))), nil + } + conn := &recordingClientConn{} + wrapped := WithFilerClientAuth(conn, source) + + if err := wrapped.Invoke(context.Background(), "/filer_pb.SeaweedFiler/LookupDirectoryEntry", nil, nil); err != nil { + t.Fatal(err) + } + if !IsFilerAdminToken(tc.wantCall, bearer(conn.contexts[len(conn.contexts)-1])) { + t.Fatal("unary filer call was not signed with the filesystem gRPC key") + } + if _, err := wrapped.NewStream(context.Background(), &grpc.StreamDesc{}, "/filer_pb.SeaweedFiler/ListEntries"); err != nil { + t.Fatal(err) + } + if !IsFilerAdminToken(tc.wantCall, bearer(conn.contexts[len(conn.contexts)-1])) { + t.Fatal("non-subscription stream was not signed with the filesystem gRPC key") + } + for _, method := range []string{"/filer_pb.SeaweedFiler/SubscribeMetadata", "/filer_pb.SeaweedFiler/SubscribeLocalMetadata"} { + if _, err := wrapped.NewStream(context.Background(), &grpc.StreamDesc{}, method); err != nil { + t.Fatal(err) + } + if !IsFilerAdminToken(tc.wantStream, bearer(conn.contexts[len(conn.contexts)-1])) { + t.Fatalf("%s was not signed with the expected subscription key", method) + } + } + ctx, err := WithFilerSubscriptionToken(context.Background(), source) + if err != nil || !IsFilerAdminToken(tc.wantStream, bearer(ctx)) { + t.Fatal("WithFilerSubscriptionToken did not prefer the shared key") + } + }) + } +} + +// TestFilerClientKeysRefuseKeysTooShortToSign covers GODEBUG=fips140=only, +// where signing with a short key panics: a key read after startup is refused +// the way startup refuses it, so a source never signs with it. +func TestFilerClientKeysRefuseKeysTooShortToSign(t *testing.T) { + readFilerClientKeysEveryCall(t) + saved := filerClientKeyCheck + filerClientKeyCheck = func(settings, keys []string) error { + for i, key := range keys { + if key != "" && len(key) < util.Fips140MinHmacKeyBytes { + return errors.New(settings[i] + " is too short") + } + } + return nil + } + t.Cleanup(func() { filerClientKeyCheck = saved }) + short := SigningKey("0123456789") + + dir := t.TempDir() + endpoint := filepath.Join(dir, "endpoint.yaml") + writeFilerSecurityConfig(t, endpoint, short, testSigningKey(t)) + if token, err := FilerAdminTokenFromFile(endpoint)(context.Background()); err == nil || token != "" || !strings.Contains(err.Error(), "jwt.filer_signing.grpc_key") { + t.Fatalf("endpoint file with a short grpc_key returned token=%t err=%v", token != "", err) + } + + savedDirectory := util.ConfigurationFileDirectory + util.ConfigurationFileDirectory = util.DirectoryValueType(dir) + t.Cleanup(func() { util.ConfigurationFileDirectory = savedDirectory }) + path := filepath.Join(dir, "security.toml") + key := testSigningKey(t) + writeFilerSecurityToml(t, path, key, SigningKey("")) + if token, err := FilerAdminToken(context.Background()); err != nil || !IsFilerAdminToken(key, token) { + t.Fatalf("global source did not use the configured key: err=%v", err) + } + writeFilerSecurityToml(t, path, short, SigningKey("")) + if token, err := FilerAdminToken(context.Background()); err != nil || !IsFilerAdminToken(key, token) { + t.Fatalf("global source did not keep the last usable key over a short one: token=%t err=%v", token != "", err) + } + + // With no usable key read yet, a short startup key is refused too. + resetGlobalFilerClientKeys() + startup := util.GetViper() + savedShared := startup.GetString("jwt.filer_signing.key") + t.Cleanup(func() { startup.Set("jwt.filer_signing.key", savedShared) }) + startup.Set("jwt.filer_signing.key", string(short)) + if token, err := FilerAdminToken(context.Background()); err == nil || token != "" { + t.Fatalf("short startup key returned token=%t err=%v", token != "", err) + } +} diff --git a/weed/security/grpc_peer.go b/weed/security/grpc_peer.go index 5341606677..f7f4802d6c 100644 --- a/weed/security/grpc_peer.go +++ b/weed/security/grpc_peer.go @@ -5,6 +5,7 @@ import ( "net" "strings" "sync" + "time" "github.com/seaweedfs/seaweedfs/weed/glog" "github.com/seaweedfs/seaweedfs/weed/util" @@ -44,7 +45,7 @@ var ( func FilerAdminKeys() (signingKey, previousKey SigningKey) { filerAdminKeysMu.Lock() defer filerAdminKeysMu.Unlock() - if fresh, used := util.ReadConfiguration("security", ""); used != "" { + if fresh, used, _ := util.ReadConfiguration("security", ""); used != "" { lastFilerAdminKeys = &[2]SigningKey{SigningKey(freshKey(fresh, "jwt.filer_signing.key")), SigningKey(fresh.GetString("jwt.filer_signing.previous_key"))} return lastFilerAdminKeys[0], lastFilerAdminKeys[1] } @@ -104,6 +105,21 @@ func IsFilerAdminToken(signingKey SigningKey, token EncodedJwt, previousKeys ... return ok && claims.SessionId == "" && len(claims.AllowedPrefixes) == 0 && len(claims.AllowedMethods) == 0 && len(claims.ReadPrefixes) == 0 } +// IsFilerAdminTokenWithLeeway is IsFilerAdminToken under the filer's gRPC +// clock policy: expiry and not-before are checked with leeway, as for scoped +// tokens. Callers outside that policy keep IsFilerAdminToken's strict check. +func IsFilerAdminTokenWithLeeway(signingKey, previousKey SigningKey, token EncodedJwt, leeway time.Duration) bool { + if len(signingKey) == 0 || token == "" { + return false + } + claims := &SeaweedFilerAdminClaims{} + parsed, err := DecodeJwtWith(signingKey, previousKey, token, claims, leeway) + if err != nil || parsed == nil || !parsed.Valid { + return false + } + return claims.SessionId == "" && len(claims.AllowedPrefixes) == 0 && len(claims.AllowedMethods) == 0 && len(claims.ReadPrefixes) == 0 +} + // GrpcAdminPeerCredentials returns outgoing metadata carrying a Bearer token // for admin-plane gRPC handlers, or nil when no signing key is configured. func GrpcAdminPeerCredentials(signingKey SigningKey, expiresAfterSec int) metadata.MD { diff --git a/weed/security/guard.go b/weed/security/guard.go index 7b1dfc4263..1c074d30ea 100644 --- a/weed/security/guard.go +++ b/weed/security/guard.go @@ -200,7 +200,7 @@ func (g *Guard) UpdateSigningKeys(signingKey string, expiresAfterSec int, readSi // verifying, and a swapped pair comes from one read. A file that cannot be // read keeps the keys in effect. It reports whether the new keys are in effect. func (g *Guard) ReloadSigningKeys(section string) bool { - fresh, used := util.ReadConfiguration("security", "") + fresh, used, _ := util.ReadConfiguration("security", "") if used == "" { glog.Warningf("reload %s: security.toml cannot be read, keeping the keys in effect", section) return false diff --git a/weed/security/jwt_previous_key_test.go b/weed/security/jwt_previous_key_test.go index 9dc07b191f..eee83e21b5 100644 --- a/weed/security/jwt_previous_key_test.go +++ b/weed/security/jwt_previous_key_test.go @@ -87,9 +87,9 @@ func TestCheckGrpcAdminTokenAcceptsPreviousKey(t *testing.T) { require.NoError(t, CheckGrpcAdminToken(ctx, current, previous)) require.NoError(t, CheckGrpcAdminPeer(ctx, current, previous)) - _, err := CheckGrpcMetadataSubscription(ctx, SigningKey("subscribe-key"), current, nil, MethodSubscribeMetadata) + _, err := CheckGrpcMetadataSubscription(ctx, SigningKey("subscribe-key"), current, nil, MethodSubscribeMetadata, 0) require.Error(t, err) - scope, err := CheckGrpcMetadataSubscription(ctx, SigningKey("subscribe-key"), current, previous, MethodSubscribeMetadata) + scope, err := CheckGrpcMetadataSubscription(ctx, SigningKey("subscribe-key"), current, previous, MethodSubscribeMetadata, 0) require.NoError(t, err) require.Nil(t, scope) } diff --git a/weed/security/metadata_subscribe.go b/weed/security/metadata_subscribe.go index 1f4ba56fd5..965e6d8dd7 100644 --- a/weed/security/metadata_subscribe.go +++ b/weed/security/metadata_subscribe.go @@ -105,8 +105,9 @@ func metadataSubscriptionScope(signingKey SigningKey, token EncodedJwt, method s // Without subscribeKey every caller is unrestricted (nil scope). With it, an // mTLS-verified peer or an admin token signed by adminKey or previousAdminKey // is unrestricted, and a token signed by subscribeKey is limited to the -// returned scope. -func CheckGrpcMetadataSubscription(ctx context.Context, subscribeKey, adminKey, previousAdminKey SigningKey, method string) (scope *MetadataSubscriptionScope, err error) { +// returned scope. Admin tokens are checked with leeway, the filer's gRPC +// clock leeway, as unary filer calls check them. +func CheckGrpcMetadataSubscription(ctx context.Context, subscribeKey, adminKey, previousAdminKey SigningKey, method string, leeway time.Duration) (scope *MetadataSubscriptionScope, err error) { if len(subscribeKey) == 0 || isMtlsVerifiedPeer(ctx) { return nil, nil } @@ -121,7 +122,7 @@ func CheckGrpcMetadataSubscription(ctx context.Context, subscribeKey, adminKey, continue } token := EncodedJwt(parts[1]) - if IsFilerAdminToken(adminKey, token, previousAdminKey) { + if IsFilerAdminTokenWithLeeway(adminKey, previousAdminKey, token, leeway) { return nil, nil } if scope, ok := metadataSubscriptionScope(subscribeKey, token, method); ok { diff --git a/weed/security/metadata_subscribe_test.go b/weed/security/metadata_subscribe_test.go index 585975afd2..c789a80659 100644 --- a/weed/security/metadata_subscribe_test.go +++ b/weed/security/metadata_subscribe_test.go @@ -65,7 +65,7 @@ func TestCheckGrpcMetadataSubscription(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - scope, err := CheckGrpcMetadataSubscription(tt.ctx, tt.subKey, adminKey, nil, tt.method) + scope, err := CheckGrpcMetadataSubscription(tt.ctx, tt.subKey, adminKey, nil, tt.method, 0) if status.Code(err) != tt.wantCode { t.Fatalf("code = %v (%v), want %v", status.Code(err), err, tt.wantCode) } @@ -133,7 +133,7 @@ func TestWithMetadataSubscriptionCredentials(t *testing.T) { v.Set("jwt.filer_signing.subscribe.key", "subscribe-key") md, _ := metadata.FromOutgoingContext(WithMetadataSubscriptionCredentials(context.Background(), nil)) in := metadata.NewIncomingContext(context.Background(), md) - scope, err := CheckGrpcMetadataSubscription(in, SigningKey("subscribe-key"), SigningKey("admin-key"), nil, MethodSubscribeLocalMetadata) + scope, err := CheckGrpcMetadataSubscription(in, SigningKey("subscribe-key"), SigningKey("admin-key"), nil, MethodSubscribeLocalMetadata, 0) if err != nil || scope != nil { t.Fatalf("scope=%v err=%v, want unrestricted", scope, err) } @@ -145,8 +145,32 @@ func TestWithMetadataSubscriptionCredentials(t *testing.T) { if len(md.Get("authorization")) != 1 { t.Fatalf("want only the per-cluster token, got %v", md.Get("authorization")) } - scope, err = CheckGrpcMetadataSubscription(metadata.NewIncomingContext(context.Background(), md), SigningKey("subscribe-b"), clusterKey, nil, MethodSubscribeMetadata) + scope, err = CheckGrpcMetadataSubscription(metadata.NewIncomingContext(context.Background(), md), SigningKey("subscribe-b"), clusterKey, nil, MethodSubscribeMetadata, 0) if err != nil || scope != nil { t.Fatalf("per-cluster token: scope=%v err=%v, want unrestricted", scope, err) } } + +// A subscriber whose clock trails the filer's gets the same leeway on its +// admin token as unary filer calls do; past the leeway it is refused. +func TestCheckGrpcMetadataSubscriptionAdminTokenLeeway(t *testing.T) { + adminKey := SigningKey("admin-key-for-leeway-test") + expired := func(ago time.Duration) context.Context { + t.Helper() + claims := SeaweedFilerAdminClaims{RegisteredClaims: jwt.RegisteredClaims{ExpiresAt: jwt.NewNumericDate(time.Now().Add(-ago))}} + token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(adminKey)) + if err != nil { + t.Fatal(err) + } + return incomingBearer(token) + } + if scope, err := CheckGrpcMetadataSubscription(expired(5*time.Second), SigningKey("subscribe-key"), adminKey, nil, MethodSubscribeMetadata, 30*time.Second); err != nil || scope != nil { + t.Fatalf("admin token 5s past expiry within 30s leeway: scope=%v err=%v, want unrestricted", scope, err) + } + if _, err := CheckGrpcMetadataSubscription(expired(5*time.Second), SigningKey("subscribe-key"), adminKey, nil, MethodSubscribeMetadata, 0); status.Code(err) != codes.Unauthenticated { + t.Fatalf("admin token 5s past expiry without leeway: err=%v, want Unauthenticated", err) + } + if _, err := CheckGrpcMetadataSubscription(expired(time.Minute), SigningKey("subscribe-key"), adminKey, nil, MethodSubscribeMetadata, 30*time.Second); status.Code(err) != codes.Unauthenticated { + t.Fatalf("admin token past the leeway: err=%v, want Unauthenticated", err) + } +} diff --git a/weed/server/filer_client_auth_test.go b/weed/server/filer_client_auth_test.go new file mode 100644 index 0000000000..21e042e21b --- /dev/null +++ b/weed/server/filer_client_auth_test.go @@ -0,0 +1,186 @@ +package weed_server + +import ( + "context" + "crypto/rand" + "encoding/hex" + "fmt" + "io" + "strings" + "testing" + "time" + + jwt "github.com/golang-jwt/jwt/v5" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/security" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// Exercise the actual admission interceptors over gRPC. In optional mode a +// missing bearer is accepted, but presenting an unrelated key is a refusal. +func TestFilerClientAuthReceiverMatrix(t *testing.T) { + newKey := func() security.SigningKey { + b := make([]byte, 32) + if _, err := rand.Read(b); err != nil { + t.Fatal("generate disposable signing key") + } + return security.SigningKey(hex.EncodeToString(b)) + } + httpKey, grpcKey, otherKey := newKey(), newKey(), newKey() + for _, receiver := range []struct { + name string + http, grpc security.SigningKey + }{ + {"no_key", nil, nil}, + {"http_only", httpKey, nil}, + {"grpc_only", nil, grpcKey}, + {"both", httpKey, grpcKey}, + } { + for _, require := range []bool{false, true} { + for _, sender := range []struct { + name string + key security.SigningKey + }{ + {"no_key", nil}, + {"http_key", httpKey}, + {"grpc_key", grpcKey}, + {"different_key", otherKey}, + } { + t.Run(fmt.Sprintf("%s/require_%v/%s", receiver.name, require, sender.name), func(t *testing.T) { + h := newScopeHarness(t) + verificationKey := receiver.grpc + if len(verificationKey) == 0 { + verificationKey = receiver.http + } + h.scope.cfg.verificationKeys = func() (security.SigningKey, security.SigningKey) { return verificationKey, nil } + h.scope.cfg.adminKeys = func() (security.SigningKey, security.SigningKey) { return receiver.http, nil } + h.scope.cfg.requireToken = func() bool { return require } + source := func(context.Context) (security.EncodedJwt, error) { + return security.GenJwtForFilerAdmin(sender.key, 10), nil + } + client := filer_pb.NewSeaweedFilerClient(security.WithFilerClientAuth(h.conn(""), source)) + accepted := (!require && (len(verificationKey) == 0 || len(sender.key) == 0)) || + (len(sender.key) != 0 && (string(sender.key) == string(verificationKey) || string(sender.key) == string(receiver.http))) + want := codes.Unauthenticated + if accepted { + want = codes.OK + } + _, err := client.Ping(scopeCtx(t), &filer_pb.PingRequest{}) + if status.Code(err) != want { + t.Fatalf("unary code=%v, want %v", status.Code(err), want) + } + if !accepted && len(sender.key) != 0 && len(verificationKey) != 0 && !strings.Contains(status.Convert(err).Message(), "key does not match") { + t.Fatal("signature refusal does not explain the key mismatch") + } + if got := len(h.fake.received("Ping")); got != map[bool]int{true: 1, false: 0}[accepted] { + t.Fatalf("unary handler calls=%d, accepted=%v", got, accepted) + } + stream, err := client.ListEntries(scopeCtx(t), &filer_pb.ListEntriesRequest{Directory: "/"}) + if err == nil { + _, err = stream.Recv() + } + if err == io.EOF { + err = nil + } + if status.Code(err) != want { + t.Fatalf("stream code=%v, want %v", status.Code(err), want) + } + if got := len(h.fake.received("ListEntries")); got != map[bool]int{true: 1, false: 0}[accepted] { + t.Fatalf("stream handler calls=%d, accepted=%v", got, accepted) + } + }) + } + } + } +} + +func TestFilerClientAuthReceiverAcceptsPreviousSigningKeys(t *testing.T) { + newKey := func() security.SigningKey { + b := make([]byte, 32) + if _, err := rand.Read(b); err != nil { + t.Fatal("generate disposable signing key") + } + return security.SigningKey(hex.EncodeToString(b)) + } + dedicatedCurrent, dedicatedPrevious := newKey(), newKey() + httpCurrent, httpPrevious := newKey(), newKey() + for _, tc := range []struct { + name string + tokenKey security.SigningKey + configure func(*scopeHarness) + }{ + { + name: "dedicated previous key", + tokenKey: dedicatedPrevious, + configure: func(h *scopeHarness) { + h.scope.cfg.verificationKeys = func() (security.SigningKey, security.SigningKey) { + return dedicatedCurrent, dedicatedPrevious + } + }, + }, + { + name: "HTTP previous key through admin fallback", + tokenKey: httpPrevious, + configure: func(h *scopeHarness) { + h.scope.cfg.verificationKeys = func() (security.SigningKey, security.SigningKey) { + return dedicatedCurrent, nil + } + h.scope.cfg.adminKeys = func() (security.SigningKey, security.SigningKey) { + return httpCurrent, httpPrevious + } + }, + }, + } { + for _, expired := range []bool{false, true} { + name := tc.name + if expired { + name += " expired within clock leeway" + } + t.Run(name, func(t *testing.T) { + h := newScopeHarness(t) + h.scope.cfg.requireToken = func() bool { return true } + if expired { + h.scope.cfg.leeway = func() time.Duration { return 30 * time.Second } + } + tc.configure(h) + sourceCalls := 0 + source := func(context.Context) (security.EncodedJwt, error) { + sourceCalls++ + token := security.GenJwtForFilerAdmin(tc.tokenKey, 10) + if expired { + claims := security.SeaweedFilerAdminClaims{RegisteredClaims: jwt.RegisteredClaims{ + ExpiresAt: jwt.NewNumericDate(time.Now().Add(-10 * time.Second)), + }} + signed, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(tc.tokenKey)) + if err != nil { + t.Fatal("sign expired disposable token") + } + token = security.EncodedJwt(signed) + } + return token, nil + } + client := filer_pb.NewSeaweedFilerClient(security.WithFilerClientAuth(h.conn(""), source)) + if _, err := client.Ping(scopeCtx(t), &filer_pb.PingRequest{}); status.Code(err) != codes.OK { + t.Fatal("unary call signed with an accepted previous key was refused") + } + stream, err := client.ListEntries(scopeCtx(t), &filer_pb.ListEntriesRequest{Directory: "/"}) + if err != nil { + t.Fatal("stream call signed with an accepted previous key was refused") + } + if _, err := stream.Recv(); err != io.EOF { + t.Fatal("accepted stream did not finish normally") + } + if sourceCalls != 2 { + t.Fatalf("per-call source resolved %d times, want two", sourceCalls) + } + if got := len(h.fake.received("Ping")); got != 1 { + t.Fatalf("unary handler calls=%d, want one", got) + } + if got := len(h.fake.received("ListEntries")); got != 1 { + t.Fatalf("stream handler calls=%d, want one", got) + } + }) + } + } +} diff --git a/weed/server/filer_grpc_scope.go b/weed/server/filer_grpc_scope.go index 9c517a48e8..aad44972fd 100644 --- a/weed/server/filer_grpc_scope.go +++ b/weed/server/filer_grpc_scope.go @@ -164,22 +164,6 @@ func (s *filerGrpcScope) verificationKeys() (security.SigningKey, security.Signi return nil, nil } -// isFilerAdminTokenWithLeeway applies the scope verifier's clock policy to the -// shared filer-admin fallback. Keep the claim-shape checks here instead of -// changing security.IsFilerAdminToken, whose callers intentionally use strict -// JWT time validation. -func isFilerAdminTokenWithLeeway(signingKey, previousKey security.SigningKey, token security.EncodedJwt, leeway time.Duration) bool { - if len(signingKey) == 0 || token == "" { - return false - } - claims := &security.SeaweedFilerAdminClaims{} - parsed, err := security.DecodeJwtWith(signingKey, previousKey, token, claims, leeway) - if err != nil || parsed == nil || !parsed.Valid { - return false - } - return claims.SessionId == "" && len(claims.AllowedPrefixes) == 0 && len(claims.AllowedMethods) == 0 && len(claims.ReadPrefixes) == 0 -} - func (s *filerGrpcScope) proven(sc *scope, chunkAuth map[string]string, fid, collection string) bool { raw := chunkAuth[fid] if raw == "" { @@ -239,10 +223,13 @@ func (s *filerGrpcScope) resolve(ctx context.Context) (*scope, error) { // a dedicated gRPC key. Only an unscoped admin token can cross that boundary. if (err != nil || token == nil || !token.Valid) && s.cfg.adminKeys != nil { adminKey, previousAdminKey := s.cfg.adminKeys() - if isFilerAdminTokenWithLeeway(adminKey, previousAdminKey, security.EncodedJwt(raw), leeway) { + if security.IsFilerAdminTokenWithLeeway(adminKey, previousAdminKey, security.EncodedJwt(raw), leeway) { return nil, nil } } + if errors.Is(err, jwt.ErrTokenSignatureInvalid) { + return nil, status.Error(codes.Unauthenticated, "filer: bearer signing key does not match an accepted filer key") + } if errors.Is(err, jwt.ErrTokenExpired) { // The claims are parsed before validation, so the id names the holder. glog.V(1).Infof("filer grpc: token %s (%s) expired", claims.ID, scopePeer(ctx)) diff --git a/weed/server/filer_grpc_scope_subscription_compat_test.go b/weed/server/filer_grpc_scope_subscription_compat_test.go index d558d9904b..3e948f180b 100644 --- a/weed/server/filer_grpc_scope_subscription_compat_test.go +++ b/weed/server/filer_grpc_scope_subscription_compat_test.go @@ -46,6 +46,7 @@ func subscriptionScopeServerWithKeys(withSubscriptionVerifier bool, filerKey, pr filerKey, previousFilerKey, method, + 0, ) } } @@ -262,6 +263,7 @@ func TestScopeSubscriptionKeyOverlapCompatibilityMatrix(t *testing.T) { tc.filerKey, tc.previousKey, method, + 0, ) if dedicatedErr != nil || dedicatedScope == nil { t.Fatalf("dedicated verifier err=%v scope=%v, want a subscription scope", dedicatedErr, dedicatedScope) diff --git a/weed/server/filer_grpc_server_sub_meta_scope.go b/weed/server/filer_grpc_server_sub_meta_scope.go index 8144056605..1ccdd64786 100644 --- a/weed/server/filer_grpc_server_sub_meta_scope.go +++ b/weed/server/filer_grpc_server_sub_meta_scope.go @@ -36,11 +36,16 @@ func (fs *FilerServer) metadataSubscriptionScope(ctx context.Context, method str adminKey, previousAdminKey = fs.filerGuard.VerificationKeys(true) } subscribeKey := security.SigningKey(util.GetViper().GetString("jwt.filer_signing.subscribe.key")) - subscription, err := security.CheckGrpcMetadataSubscription(ctx, subscribeKey, adminKey, previousAdminKey, method) - if settings := fs.grpcScopeSettings.Load(); err != nil && settings != nil && len(settings.key) > 0 { + settings := fs.grpcScopeSettings.Load() + var leeway time.Duration + if settings != nil { + leeway = settings.leeway + } + subscription, err := security.CheckGrpcMetadataSubscription(ctx, subscribeKey, adminKey, previousAdminKey, method, leeway) + if err != nil && settings != nil && len(settings.key) > 0 { // An unscoped grpc_key token already has full filer gRPC access, and // peers without the shared key sign their subscriptions with it. - if grpcSubscription, grpcErr := security.CheckGrpcMetadataSubscription(ctx, subscribeKey, settings.key, settings.previousKey, method); grpcErr == nil { + if grpcSubscription, grpcErr := security.CheckGrpcMetadataSubscription(ctx, subscribeKey, settings.key, settings.previousKey, method, leeway); grpcErr == nil { return grpcSubscription, nil } } diff --git a/weed/server/filer_server.go b/weed/server/filer_server.go index e0c1a2eb16..eae4528ad7 100644 --- a/weed/server/filer_server.go +++ b/weed/server/filer_server.go @@ -786,7 +786,7 @@ func (fs *FilerServer) leaveLockRing(removalTimeout time.Duration) { // unsearchable cannot hand over a lower-priority security.toml. A non-nil // current is kept when the file cannot be read. func loadBasicAuth(current *security.BasicAuth, file string) (*security.BasicAuth, string) { - v, used := util.ReadConfiguration("security", file) + v, used, _ := util.ReadConfiguration("security", file) if used == "" { if current != nil { return current, file @@ -826,7 +826,7 @@ func (fs *FilerServer) Reload() { "", "", ) - if fresh, used := util.ReadConfiguration("security", ""); used != "" { + if fresh, used, _ := util.ReadConfiguration("security", ""); used != "" { fs.loadGrpcScopeConfig(fresh) } if key, _ := fs.grpcScopeVerificationKeys(); len(previousScopeKey) > 0 && len(key) == 0 { diff --git a/weed/server/master_server.go b/weed/server/master_server.go index 8d7cb4fc1d..3cfb4d4379 100644 --- a/weed/server/master_server.go +++ b/weed/server/master_server.go @@ -493,6 +493,7 @@ func (ms *MasterServer) startAdminScripts() { var shellOptions shell.ShellOptions shellOptions.GrpcDialOption = security.LoadClientTLS(v, "grpc.master") shellOptions.Masters = &masterAddress + shellOptions.FilerTokenSource = security.FilerAdminToken shellOptions.Directory = "/" emptyFilerGroup := "" diff --git a/weed/server/webdav_client_auth_test.go b/weed/server/webdav_client_auth_test.go new file mode 100644 index 0000000000..67d1e3edfc --- /dev/null +++ b/weed/server/webdav_client_auth_test.go @@ -0,0 +1,58 @@ +package weed_server + +import ( + "context" + "fmt" + "net" + "strconv" + "testing" + + "github.com/seaweedfs/seaweedfs/weed/pb" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" +) + +func TestWebDavStatWithFilerAuthentication(t *testing.T) { + for _, require := range []bool{false, true} { + for _, sender := range []struct{ name, key string }{ + {"matching", scopeTestKey}, + {"missing", ""}, + {"different", "webdav-disposable-unrelated-test-key"}, + } { + t.Run(fmt.Sprintf("require_%v/%s", require, sender.name), func(t *testing.T) { + t.Setenv("WEED_JWT_FILER_SIGNING_GRPC_KEY", sender.key) + t.Setenv("WEED_JWT_FILER_SIGNING_KEY", "") + h := newScopeHarness(t) + h.scope.cfg.requireToken = func() bool { return require } + h.fake.put("/file", &filer_pb.Entry{Name: "file", Attributes: &filer_pb.FuseAttributes{FileSize: 7}}) + host, portText, err := net.SplitHostPort(h.addr) + if err != nil { + t.Fatal(err) + } + port, err := strconv.Atoi(portText) + if err != nil { + t.Fatal(err) + } + fs := &WebDavFileSystem{option: &WebDavOption{ + Filer: pb.NewServerAddress(host, 1, port), + GrpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()), + }} + info, err := fs.Stat(context.Background(), "/file") + accepted := sender.name == "matching" || (!require && sender.name == "missing") + if !accepted { + if err == nil || len(h.fake.received("LookupDirectoryEntry")) != 0 { + t.Fatal("unauthorized WebDAV stat reached the filer handler") + } + return + } + if err != nil { + t.Fatalf("stat: %v", err) + } + if info.Name() != "file" || info.Size() != 7 || len(h.fake.received("LookupDirectoryEntry")) != 1 { + t.Fatal("WebDAV stat did not return the stored file metadata") + } + }) + } + } +} diff --git a/weed/server/webdav_server.go b/weed/server/webdav_server.go index 1c2d89eca6..a6a6be6abb 100644 --- a/weed/server/webdav_server.go +++ b/weed/server/webdav_server.go @@ -424,7 +424,9 @@ func NewWebDavFileSystem(option *WebDavOption) (webdav.FileSystem, error) { // a volume's locations, so a read that failed against every cached location // looks the volume up again instead of retrying a server that has moved or // died. - t.filerClient = wdclient.NewFilerClient([]pb.ServerAddress{option.Filer}, option.GrpcDialOption, "") + t.filerClient = wdclient.NewFilerClient([]pb.ServerAddress{option.Filer}, option.GrpcDialOption, "", &wdclient.FilerClientOption{ + FilerTokenSource: security.FilerAdminToken, + }) t.readerCache = filer.NewReaderCache(32, chunkCache, t.filerClient.GetLookupFileIdFunction(), t.filerClient) return t, nil } @@ -434,7 +436,7 @@ var _ = filer_pb.FilerClient(&WebDavFileSystem{}) func (fs *WebDavFileSystem) WithFilerClient(streamingMode bool, fn func(filer_pb.SeaweedFilerClient) error) error { return pb.WithGrpcClient(context.Background(), streamingMode, fs.signature, func(grpcConnection *grpc.ClientConn) error { - client := filer_pb.NewSeaweedFilerClient(grpcConnection) + client := filer_pb.NewSeaweedFilerClient(security.WithFilerClientAuth(grpcConnection, security.FilerAdminToken)) return fn(client) }, fs.option.Filer.ToGrpcAddress(), false, fs.option.GrpcDialOption) diff --git a/weed/sftpd/sftp_filer.go b/weed/sftpd/sftp_filer.go index edc40a94e6..30025f542e 100644 --- a/weed/sftpd/sftp_filer.go +++ b/weed/sftpd/sftp_filer.go @@ -96,7 +96,7 @@ func (fs *SftpServer) GetDataCenter() string { return f func (fs *SftpServer) WithFilerClient(streamingMode bool, fn func(filer_pb.SeaweedFilerClient) error) error { addr := fs.filerAddr.ToGrpcAddress() return pb.WithGrpcClient(context.Background(), streamingMode, util.RandomInt32(), func(conn *grpc.ClientConn) error { - return fn(filer_pb.NewSeaweedFilerClient(conn)) + return fn(filer_pb.NewSeaweedFilerClient(security.WithFilerClientAuth(conn, security.FilerAdminToken))) }, addr, false, fs.grpcDialOption) } func (fs *SftpServer) withTimeoutContext(fn func(ctx context.Context) error) error { diff --git a/weed/sftpd/sftp_filer_test.go b/weed/sftpd/sftp_filer_test.go index c4dd7e183e..ead1884622 100644 --- a/weed/sftpd/sftp_filer_test.go +++ b/weed/sftpd/sftp_filer_test.go @@ -2,6 +2,8 @@ package sftpd import ( "context" + "crypto/rand" + "encoding/hex" "fmt" "net" "net/http" @@ -14,10 +16,12 @@ import ( "github.com/pkg/sftp" "github.com/seaweedfs/seaweedfs/weed/pb" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/security" "github.com/seaweedfs/seaweedfs/weed/sftpd/user" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" ) @@ -52,11 +56,33 @@ func TestPutFileEscapesQueryInjection(t *testing.T) { type fakeListFiler struct { filer_pb.UnimplementedSeaweedFilerServer - names []string - failFrom int // ListEntries fails after sending this many entries, when > 0 + names []string + failFrom int // ListEntries fails after sending this many entries, when > 0 + authKey security.SigningKey + authResultChan chan bool +} + +func (f *fakeListFiler) checkAuth(ctx context.Context) error { + if len(f.authKey) == 0 { + return nil + } + md, _ := metadata.FromIncomingContext(ctx) + values := md.Get("authorization") + valid := len(values) == 1 && strings.HasPrefix(values[0], security.BearerPrefix) && + security.IsFilerAdminToken(f.authKey, security.EncodedJwt(strings.TrimPrefix(values[0], security.BearerPrefix))) + if f.authResultChan != nil { + f.authResultChan <- valid + } + if !valid { + return status.Error(codes.Unauthenticated, "missing or invalid filer authorization") + } + return nil } func (f *fakeListFiler) ListEntries(req *filer_pb.ListEntriesRequest, stream grpc.ServerStreamingServer[filer_pb.ListEntriesResponse]) error { + if err := f.checkAuth(stream.Context()); err != nil { + return err + } sent := 0 for _, name := range f.names { if name <= req.StartFromFileName || sent >= int(req.Limit) { @@ -74,9 +100,21 @@ func (f *fakeListFiler) ListEntries(req *filer_pb.ListEntriesRequest, stream grp } func (f *fakeListFiler) LookupDirectoryEntry(ctx context.Context, req *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) { + if err := f.checkAuth(ctx); err != nil { + return nil, err + } return &filer_pb.LookupDirectoryEntryResponse{Entry: &filer_pb.Entry{Name: req.Name, Attributes: &filer_pb.FuseAttributes{}}}, nil } +func sftpTestSigningKey(t *testing.T) security.SigningKey { + t.Helper() + bytes := make([]byte, 32) + if _, err := rand.Read(bytes); err != nil { + t.Fatal(err) + } + return security.SigningKey(hex.EncodeToString(bytes)) +} + func newListTestServer(t *testing.T, filer *fakeListFiler) *SftpServer { t.Helper() lis, err := net.Listen("tcp", "127.0.0.1:0") @@ -178,3 +216,27 @@ func TestListAllPagesContinuesPastFullyHiddenPage(t *testing.T) { t.Fatalf("unexpected first entry %q", names[0]) } } + +func TestWithFilerClientSendsAdminToken(t *testing.T) { + key := sftpTestSigningKey(t) + t.Setenv("WEED_JWT_FILER_SIGNING_GRPC_KEY", string(key)) + t.Setenv("WEED_JWT_FILER_SIGNING_KEY", "") + + filer := &fakeListFiler{authKey: key, authResultChan: make(chan bool, 1)} + fs := newListTestServer(t, filer) + err := fs.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error { + _, err := client.LookupDirectoryEntry(context.Background(), &filer_pb.LookupDirectoryEntryRequest{Directory: "/", Name: "entry"}) + return err + }) + if err != nil { + t.Fatalf("WithFilerClient: %v", err) + } + select { + case valid := <-filer.authResultChan: + if !valid { + t.Fatal("filer rejected the per-call admin token") + } + case <-time.After(time.Second): + t.Fatal("filer did not receive the request") + } +} diff --git a/weed/shell/command_cluster_check.go b/weed/shell/command_cluster_check.go index 42fe05e85d..aefb6dd0b5 100644 --- a/weed/shell/command_cluster_check.go +++ b/weed/shell/command_cluster_check.go @@ -179,7 +179,7 @@ func (c *commandClusterCheck) Do(args []string, commandEnv *CommandEnv, writer i for _, filer := range filers { for _, master := range masters { fmt.Fprintf(writer, "checking filer %s to master %s ... ", string(filer), string(master)) - err := pb.WithFilerClient(false, 0, filer, commandEnv.option.GrpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + err := commandEnv.WithFilerClientAt(filer, false, func(client filer_pb.SeaweedFilerClient) error { pong, err := client.Ping(context.Background(), &filer_pb.PingRequest{ Target: string(master), TargetType: cluster.MasterType, @@ -199,7 +199,7 @@ func (c *commandClusterCheck) Do(args []string, commandEnv *CommandEnv, writer i for _, filer := range filers { for _, volumeServer := range volumeServers { fmt.Fprintf(writer, "checking filer %s to volume server %s ... ", string(filer), string(volumeServer)) - err := pb.WithFilerClient(false, 0, filer, commandEnv.option.GrpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + err := commandEnv.WithFilerClientAt(filer, false, func(client filer_pb.SeaweedFilerClient) error { pong, err := client.Ping(context.Background(), &filer_pb.PingRequest{ Target: string(volumeServer), TargetType: cluster.VolumeServerType, @@ -225,7 +225,7 @@ func (c *commandClusterCheck) Do(args []string, commandEnv *CommandEnv, writer i for _, sourceFiler := range filers { for _, targetFiler := range filers { fmt.Fprintf(writer, "checking filer %s to %s ... ", string(sourceFiler), string(targetFiler)) - err := pb.WithFilerClient(false, 0, sourceFiler, commandEnv.option.GrpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + err := commandEnv.WithFilerClientAt(sourceFiler, false, func(client filer_pb.SeaweedFilerClient) error { pong, err := client.Ping(context.Background(), &filer_pb.PingRequest{ Target: string(targetFiler), TargetType: cluster.FilerType, diff --git a/weed/shell/command_cluster_ps.go b/weed/shell/command_cluster_ps.go index 58bc98700d..46bb9e0635 100644 --- a/weed/shell/command_cluster_ps.go +++ b/weed/shell/command_cluster_ps.go @@ -129,7 +129,7 @@ func (c *commandClusterPs) Do(args []string, commandEnv *CommandEnv, writer io.W if node.Rack != "" { fmt.Fprintf(writer, " Rack: %v\n", node.Rack) } - pb.WithFilerClient(false, 0, pb.ServerAddress(node.Address), commandEnv.option.GrpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + commandEnv.WithFilerClientAt(pb.ServerAddress(node.Address), false, func(client filer_pb.SeaweedFilerClient) error { resp, err := client.GetFilerConfiguration(context.Background(), &filer_pb.GetFilerConfigurationRequest{}) if err == nil { if resp.FilerGroup != "" { @@ -144,7 +144,7 @@ func (c *commandClusterPs) Do(args []string, commandEnv *CommandEnv, writer io.W }) } for _, node := range filerNodes { - pb.WithFilerClient(false, 0, pb.ServerAddress(node.Address), commandEnv.option.GrpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + commandEnv.WithFilerClientAt(pb.ServerAddress(node.Address), false, func(client filer_pb.SeaweedFilerClient) error { fmt.Fprintf(writer, "* filer %s metadata sync time\n", node.Address) selfSignature := filerSignatures[node] for peer, peerSignature := range filerSignatures { diff --git a/weed/shell/command_fs_configure.go b/weed/shell/command_fs_configure.go index 3f987b4787..2e993e392a 100644 --- a/weed/shell/command_fs_configure.go +++ b/weed/shell/command_fs_configure.go @@ -83,7 +83,7 @@ func (c *commandFsConfigure) Do(args []string, commandEnv *CommandEnv, writer io return err } - fc, err := filer.ReadFilerConf(commandEnv.FilerAddress(), commandEnv.option.GrpcDialOption, commandEnv.MasterClient) + fc, err := filer.ReadFilerConf(commandEnv.FilerAddress(), commandEnv.option.GrpcDialOption, commandEnv.MasterClient, commandEnv.option.FilerTokenSource) if err != nil { return err } diff --git a/weed/shell/command_fs_meta_token_test.go b/weed/shell/command_fs_meta_token_test.go index 69c7679511..6ce5068b9b 100644 --- a/weed/shell/command_fs_meta_token_test.go +++ b/weed/shell/command_fs_meta_token_test.go @@ -32,7 +32,7 @@ func TestFsMetaToken(t *testing.T) { t.Fatal(err) } ctx := metadata.NewIncomingContext(context.Background(), metadata.Pairs("authorization", "Bearer "+strings.TrimSpace(out.String()))) - scope, err := security.CheckGrpcMetadataSubscription(ctx, security.SigningKey("sub-key"), nil, nil, security.MethodSubscribeMetadata) + scope, err := security.CheckGrpcMetadataSubscription(ctx, security.SigningKey("sub-key"), nil, nil, security.MethodSubscribeMetadata, 0) if err != nil || strings.Join(scope.Prefixes, ",") != "/buckets/a,/buckets/b" || time.Until(scope.ExpiresAt) < 59*time.Minute { t.Fatalf("scope=%v err=%v", scope, err) } diff --git a/weed/shell/command_fs_verify.go b/weed/shell/command_fs_verify.go index 980fceee49..9fe8e92acc 100644 --- a/weed/shell/command_fs_verify.go +++ b/weed/shell/command_fs_verify.go @@ -252,6 +252,7 @@ func (c *commandFsVerify) verifyProcessMetadata(path string, wg *sync.WaitGroup) StartTsNs: time.Now().Add(-1 * time.Second * time.Duration(c.modifyTimeAgoAtSec)).UnixNano(), StopTsNs: time.Now().UnixNano(), EventErrorType: pb.DontLogError, + FilerTokenSource: c.env.option.FilerTokenSource, } err = pb.FollowMetadata(c.env.FilerAddress(), c.env.option.GrpcDialOption, metadataFollowOption, processEventFn) return fileCount, errCount, prunedCount, err diff --git a/weed/shell/command_mq_topic_compact.go b/weed/shell/command_mq_topic_compact.go index 8171144b1f..f170275857 100644 --- a/weed/shell/command_mq_topic_compact.go +++ b/weed/shell/command_mq_topic_compact.go @@ -76,6 +76,7 @@ func (c *commandMqTopicCompact) Do(args []string, commandEnv *CommandEnv, writer []pb.ServerAddress{commandEnv.FilerAddress()}, commandEnv.option.GrpcDialOption, ) + fca.TokenSource = commandEnv.option.FilerTokenSource t := topic.NewTopic(*namespace, *topicName) topicConf, err := fca.ReadTopicConfFromFiler(t) if err != nil { diff --git a/weed/shell/command_remote_meta_sync.go b/weed/shell/command_remote_meta_sync.go index 0715e82532..cf1a8962c1 100644 --- a/weed/shell/command_remote_meta_sync.go +++ b/weed/shell/command_remote_meta_sync.go @@ -85,7 +85,7 @@ func (c *commandRemoteMetaSync) Do(args []string, commandEnv *CommandEnv, writer } func detectMountInfo(commandEnv *CommandEnv, writer io.Writer, dir string) (*remote_pb.RemoteStorageMapping, string, *remote_pb.RemoteStorageLocation, *remote_pb.RemoteConf, error) { - return filer.DetectMountInfo(commandEnv.option.GrpcDialOption, commandEnv.FilerAddress(), dir) + return filer.DetectMountInfo(commandEnv.option.GrpcDialOption, commandEnv.FilerAddress(), dir, commandEnv.option.FilerTokenSource) } /* diff --git a/weed/shell/command_remote_mount.go b/weed/shell/command_remote_mount.go index e9879dddf4..58a1baf7e7 100644 --- a/weed/shell/command_remote_mount.go +++ b/weed/shell/command_remote_mount.go @@ -85,7 +85,7 @@ func (c *commandRemoteMount) Do(args []string, commandEnv *CommandEnv, writer io } // find configuration for remote storage - remoteConf, err := filer.ReadRemoteStorageConf(commandEnv.option.GrpcDialOption, commandEnv.FilerAddress(), remote_storage.ParseLocationName(*remote)) + remoteConf, err := filer.ReadRemoteStorageConf(commandEnv.option.GrpcDialOption, commandEnv.FilerAddress(), remote_storage.ParseLocationName(*remote), commandEnv.option.FilerTokenSource) if err != nil { return fmt.Errorf("find configuration for %s: %v", *remote, err) } @@ -139,7 +139,7 @@ func (c *commandRemoteMount) Do(args []string, commandEnv *CommandEnv, writer io // filer.remote.sync starts it from the same creation time after its wait. func saveMountSyncOffset(commandEnv *CommandEnv, writer io.Writer, dir string) { err := saveMountSyncOffsetWith(func() (int64, error) { - return remote_storage.GetSyncOffset(commandEnv.option.GrpcDialOption, commandEnv.FilerAddress(), dir) + return remote_storage.GetSyncOffset(commandEnv.option.GrpcDialOption, commandEnv.FilerAddress(), dir, commandEnv.option.FilerTokenSource) }, func() (int64, error) { entry, _, _, err := filer_pb.GetEntry(context.Background(), commandEnv, util.FullPath(dir)) if err != nil { @@ -147,7 +147,7 @@ func saveMountSyncOffset(commandEnv *CommandEnv, writer io.Writer, dir string) { } return entry.GetAttributes().GetCrtime(), nil }, func(ts int64) error { - return remote_storage.SetSyncOffset(commandEnv.option.GrpcDialOption, commandEnv.FilerAddress(), dir, ts) + return remote_storage.SetSyncOffset(commandEnv.option.GrpcDialOption, commandEnv.FilerAddress(), dir, ts, commandEnv.option.FilerTokenSource) }, dir) if err != nil { fmt.Fprintf(writer, "warning: mounted %s, but %v\n", dir, err) @@ -178,7 +178,7 @@ func saveMountSyncOffsetWith(read func() (int64, error), crtime func() (int64, e func listExistingRemoteStorageMounts(commandEnv *CommandEnv, writer io.Writer) (mappings *remote_pb.RemoteStorageMapping, err error) { // read current mapping - mappings, err = filer.ReadMountMappings(commandEnv.option.GrpcDialOption, commandEnv.FilerAddress()) + mappings, err = filer.ReadMountMappings(commandEnv.option.GrpcDialOption, commandEnv.FilerAddress(), commandEnv.option.FilerTokenSource) if err != nil { return mappings, err } diff --git a/weed/shell/command_remote_mount_buckets.go b/weed/shell/command_remote_mount_buckets.go index e226e3d15d..53c07630b6 100644 --- a/weed/shell/command_remote_mount_buckets.go +++ b/weed/shell/command_remote_mount_buckets.go @@ -62,7 +62,7 @@ func (c *commandRemoteMountBuckets) Do(args []string, commandEnv *CommandEnv, wr } // find configuration for remote storage - remoteConf, err := filer.ReadRemoteStorageConf(commandEnv.option.GrpcDialOption, commandEnv.FilerAddress(), *remote) + remoteConf, err := filer.ReadRemoteStorageConf(commandEnv.option.GrpcDialOption, commandEnv.FilerAddress(), *remote, commandEnv.option.FilerTokenSource) if err != nil { return fmt.Errorf("find configuration for %s: %v", *remote, err) } diff --git a/weed/shell/command_remote_uncache.go b/weed/shell/command_remote_uncache.go index cd4850ab17..151f3aba93 100644 --- a/weed/shell/command_remote_uncache.go +++ b/weed/shell/command_remote_uncache.go @@ -58,7 +58,7 @@ func (c *commandRemoteUncache) Do(args []string, commandEnv *CommandEnv, writer return err } - mappings, listErr := filer.ReadMountMappings(commandEnv.option.GrpcDialOption, commandEnv.FilerAddress()) + mappings, listErr := filer.ReadMountMappings(commandEnv.option.GrpcDialOption, commandEnv.FilerAddress(), commandEnv.option.FilerTokenSource) if listErr != nil { return listErr } diff --git a/weed/shell/command_remote_unmount.go b/weed/shell/command_remote_unmount.go index 6a36b2cd8c..2620b9c796 100644 --- a/weed/shell/command_remote_unmount.go +++ b/weed/shell/command_remote_unmount.go @@ -52,7 +52,7 @@ func (c *commandRemoteUnmount) Do(args []string, commandEnv *CommandEnv, writer return err } - mappings, listErr := filer.ReadMountMappings(commandEnv.option.GrpcDialOption, commandEnv.FilerAddress()) + mappings, listErr := filer.ReadMountMappings(commandEnv.option.GrpcDialOption, commandEnv.FilerAddress(), commandEnv.option.FilerTokenSource) if listErr != nil { return listErr } @@ -79,7 +79,7 @@ func (c *commandRemoteUnmount) Do(args []string, commandEnv *CommandEnv, writer } // reset remote sync offset in case the folder is mounted again - if err = remote_storage.SetSyncOffset(commandEnv.option.GrpcDialOption, commandEnv.FilerAddress(), *dir, time.Now().UnixNano()); err != nil { + if err = remote_storage.SetSyncOffset(commandEnv.option.GrpcDialOption, commandEnv.FilerAddress(), *dir, time.Now().UnixNano(), commandEnv.option.FilerTokenSource); err != nil { return fmt.Errorf("reset remote.sync offset for %s: %v", *dir, err) } diff --git a/weed/shell/command_s3_bucket_quota_check.go b/weed/shell/command_s3_bucket_quota_check.go index fb5b2ac781..c102937b73 100644 --- a/weed/shell/command_s3_bucket_quota_check.go +++ b/weed/shell/command_s3_bucket_quota_check.go @@ -60,7 +60,7 @@ func (c *commandS3BucketQuotaEnforce) Do(args []string, commandEnv *CommandEnv, } // read existing filer configuration - fc, err := filer.ReadFilerConf(commandEnv.FilerAddress(), commandEnv.option.GrpcDialOption, commandEnv.MasterClient) + fc, err := filer.ReadFilerConf(commandEnv.FilerAddress(), commandEnv.option.GrpcDialOption, commandEnv.MasterClient, commandEnv.option.FilerTokenSource) if err != nil { return err } diff --git a/weed/shell/command_s3_clean_uploads.go b/weed/shell/command_s3_clean_uploads.go index 1be89813fc..3601da59c5 100644 --- a/weed/shell/command_s3_clean_uploads.go +++ b/weed/shell/command_s3_clean_uploads.go @@ -115,6 +115,7 @@ type objectWriteLock func(objectPath string) (held func() bool, release func(), func newObjectWriteLock(commandEnv *CommandEnv) objectWriteLock { lockClient := cluster.NewLockClient(commandEnv.option.GrpcDialOption, commandEnv.FilerAddress()) + lockClient.TokenSource = commandEnv.option.FilerTokenSource owner := fmt.Sprintf("s3.clean.uploads-%d", util.RandomInt32()) return func(objectPath string) (func() bool, func(), error) { if objectPath == "" { diff --git a/weed/shell/commands.go b/weed/shell/commands.go index fa59f6039c..0087165351 100644 --- a/weed/shell/commands.go +++ b/weed/shell/commands.go @@ -20,6 +20,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/pb" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/security" "github.com/seaweedfs/seaweedfs/weed/util" "github.com/seaweedfs/seaweedfs/weed/wdclient" "github.com/seaweedfs/seaweedfs/weed/wdclient/exclusive_locks" @@ -29,13 +30,14 @@ type ShellOptions struct { Masters *string GrpcDialOption grpc.DialOption // shell transient context - FilerHost string - FilerPort int64 - FilerGroup *string - FilerAddress pb.ServerAddress - Directory string - Debug bool - ConnectTimeout time.Duration + FilerHost string + FilerPort int64 + FilerGroup *string + FilerAddress pb.ServerAddress + Directory string + Debug bool + ConnectTimeout time.Duration + FilerTokenSource security.FilerTokenSource } type CommandEnv struct { @@ -154,9 +156,14 @@ func (ce *CommandEnv) GrpcDialOption() grpc.DialOption { } func (ce *CommandEnv) WithFilerClient(streamingMode bool, fn func(filer_pb.SeaweedFilerClient) error) error { + return ce.WithFilerClientAt(ce.FilerAddress(), streamingMode, fn) +} - return pb.WithGrpcFilerClient(streamingMode, 0, ce.FilerAddress(), ce.option.GrpcDialOption, fn) - +// WithFilerClientAt invokes a filer RPC against a specific discovered address. +// The token source is attached to the logical client, so pooled connections +// remain shared while each RPC resolves current credentials independently. +func (ce *CommandEnv) WithFilerClientAt(address pb.ServerAddress, streamingMode bool, fn func(filer_pb.SeaweedFilerClient) error) error { + return pb.WithGrpcFilerClient(streamingMode, 0, address, ce.option.GrpcDialOption, ce.option.FilerTokenSource, fn) } // FilerAddress returns the discovered or configured filer, running discovery diff --git a/weed/shell/filer_client_auth_test.go b/weed/shell/filer_client_auth_test.go new file mode 100644 index 0000000000..a3521a9a17 --- /dev/null +++ b/weed/shell/filer_client_auth_test.go @@ -0,0 +1,181 @@ +package shell + +import ( + "context" + "crypto/rand" + "encoding/hex" + "net" + "strconv" + "sync" + "testing" + + "github.com/seaweedfs/seaweedfs/weed/filer" + "github.com/seaweedfs/seaweedfs/weed/pb" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/security" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" +) + +type shellAuthFiler struct { + filer_pb.UnimplementedSeaweedFilerServer + + mu sync.Mutex + updates []*filer_pb.UpdateEntryRequest +} + +func (s *shellAuthFiler) LookupDirectoryEntry(context.Context, *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) { + return &filer_pb.LookupDirectoryEntryResponse{Entry: &filer_pb.Entry{ + Name: filer.FilerConfName, + Attributes: &filer_pb.FuseAttributes{}, + }}, nil +} + +func (s *shellAuthFiler) UpdateEntry(_ context.Context, req *filer_pb.UpdateEntryRequest) (*filer_pb.UpdateEntryResponse, error) { + s.mu.Lock() + s.updates = append(s.updates, req) + s.mu.Unlock() + return &filer_pb.UpdateEntryResponse{}, nil +} + +func shellAuthCheck(ctx context.Context, key security.SigningKey, require bool) error { + md, _ := metadata.FromIncomingContext(ctx) + values := md.Get("authorization") + if len(key) == 0 { + if require && len(values) == 0 { + return status.Error(codes.Unauthenticated, "authentication required") + } + if len(values) == 0 { + return nil + } + } + if len(values) != 1 { + return status.Error(codes.Unauthenticated, "authentication required") + } + const prefix = "Bearer " + if len(values[0]) <= len(prefix) || values[0][:len(prefix)] != prefix || !security.IsFilerAdminToken(key, security.EncodedJwt(values[0][len(prefix):])) { + return status.Error(codes.Unauthenticated, "invalid authentication") + } + return nil +} + +func startShellAuthFiler(t *testing.T, key security.SigningKey, require bool) (*shellAuthFiler, pb.ServerAddress) { + t.Helper() + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal("listen") + } + filerServer := &shellAuthFiler{} + server := grpc.NewServer( + grpc.UnaryInterceptor(func(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { + if err := shellAuthCheck(ctx, key, require); err != nil { + return nil, err + } + return handler(ctx, req) + }), + grpc.StreamInterceptor(func(srv any, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { + if err := shellAuthCheck(stream.Context(), key, require); err != nil { + return err + } + return handler(srv, stream) + }), + ) + filer_pb.RegisterSeaweedFilerServer(server, filerServer) + go func() { _ = server.Serve(listener) }() + t.Cleanup(func() { + server.Stop() + _ = listener.Close() + pb.InvalidateGrpcConnection(shellAuthAddress(listener.Addr().String()).ToGrpcAddress()) + }) + return filerServer, shellAuthAddress(listener.Addr().String()) +} + +func shellAuthAddress(address string) pb.ServerAddress { + _, portText, err := net.SplitHostPort(address) + if err != nil { + return pb.ServerAddress(address) + } + port, err := strconv.Atoi(portText) + if err != nil { + return pb.ServerAddress(address) + } + return pb.NewServerAddressWithGrpcPort(address, port) +} + +func shellTestKey(t *testing.T) security.SigningKey { + t.Helper() + bytes := make([]byte, 32) + if _, err := rand.Read(bytes); err != nil { + t.Fatal("generate disposable signing key") + } + return security.SigningKey(hex.EncodeToString(bytes)) +} + +func TestShellProtectedNamespaceOperationUsesPerCallAdminToken(t *testing.T) { + key := shellTestKey(t) + otherKey := shellTestKey(t) + for _, tc := range []struct { + name string + require bool + source security.FilerTokenSource + want codes.Code + }{ + { + name: "valid token", + require: true, + source: func(context.Context) (security.EncodedJwt, error) { + return security.GenJwtForFilerAdmin(key, 10), nil + }, + want: codes.OK, + }, + { + name: "wrong key", + require: true, + source: func(context.Context) (security.EncodedJwt, error) { + return security.GenJwtForFilerAdmin(otherKey, 10), nil + }, + want: codes.Unauthenticated, + }, + { + name: "missing token", + require: true, + want: codes.Unauthenticated, + }, + { + name: "optional no key", + require: false, + want: codes.OK, + }, + } { + t.Run(tc.name, func(t *testing.T) { + serverKey := key + if tc.name == "optional no key" { + serverKey = nil + } + server, address := startShellAuthFiler(t, serverKey, tc.require) + env := &CommandEnv{option: &ShellOptions{ + FilerAddress: address, + GrpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()), + FilerTokenSource: tc.source, + }} + err := env.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error { + return filer.SaveInsideFiler(context.Background(), client, filer.DirectoryEtcSeaweedFS, filer.FilerConfName, []byte("protected shell config")) + }) + if status.Code(err) != tc.want { + t.Fatalf("protected shell operation code=%v, want %v", status.Code(err), tc.want) + } + server.mu.Lock() + updates := len(server.updates) + server.mu.Unlock() + if tc.want == codes.OK && updates != 1 { + t.Fatalf("protected shell operation updates=%d, want one", updates) + } + if tc.want != codes.OK && updates != 0 { + t.Fatalf("refused protected shell operation reached handler") + } + }) + } +} diff --git a/weed/shell/s3tables_helpers.go b/weed/shell/s3tables_helpers.go index 18c5f90a72..8715555ee7 100644 --- a/weed/shell/s3tables_helpers.go +++ b/weed/shell/s3tables_helpers.go @@ -7,20 +7,15 @@ import ( "strings" "time" - "github.com/seaweedfs/seaweedfs/weed/pb" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/s3api/s3tables" - "google.golang.org/grpc" ) const s3TablesDefaultRegion = "" const timeFormat = "2006-01-02T15:04:05Z07:00" func withFilerClient(commandEnv *CommandEnv, fn func(client filer_pb.SeaweedFilerClient) error) error { - return pb.WithGrpcClient(context.Background(), false, 0, func(conn *grpc.ClientConn) error { - client := filer_pb.NewSeaweedFilerClient(conn) - return fn(client) - }, commandEnv.FilerAddress().ToGrpcAddress(), false, commandEnv.option.GrpcDialOption) + return commandEnv.WithFilerClient(false, fn) } func executeS3Tables(commandEnv *CommandEnv, operation string, req interface{}, resp interface{}, accountID string) error { diff --git a/weed/util/config.go b/weed/util/config.go index 2f0b726e7c..1f8bec4c24 100644 --- a/weed/util/config.go +++ b/weed/util/config.go @@ -1,8 +1,13 @@ package util import ( + "errors" + "io/fs" + "os" + "path/filepath" "strings" "sync" + "syscall" "time" "github.com/spf13/viper" @@ -57,6 +62,45 @@ func LoadSecurityConfiguration() { }) } +// errSecurityConfigUnreadable leaves out the parser error, which can quote +// configuration values. +var errSecurityConfigUnreadable = errors.New("security.toml exists but cannot be read or parsed; fix it or remove it, since running without its TLS settings would send credentials in plaintext") + +// LoadSecurityConfigurationOrError is LoadConfiguration("security", false) for +// clients that must not start without the settings a present security.toml +// holds: a missing file is fine, an unreadable or malformed one is an error. +// The file is read once, and its parser error is not logged because it can +// quote configuration values. +func LoadSecurityConfigurationOrError() error { + vp.Lock() + defer vp.Unlock() + setConfigurationPaths(viper.GetViper(), "security") + err := viper.MergeInConfig() + var notFound viper.ConfigFileNotFoundError + if err == nil || (errors.As(err, ¬Found) && !configurationSearchDenied("security")) { + return nil + } + return errSecurityConfigUnreadable +} + +// configurationSearchDenied reports whether a candidate configFileName file +// could not be confirmed absent: its check failed for a reason other than the +// file, or a directory on its path, not existing (lack of permission, a symlink +// loop). Viper's search treats any such failure as absence, which would hide a +// file the process cannot read. +func configurationSearchDenied(configFileName string) bool { + for _, dir := range configurationPaths() { + dir = os.ExpandEnv(dir) + for _, ext := range viper.SupportedExts { + _, err := os.Stat(filepath.Join(dir, configFileName+"."+ext)) + if err != nil && !errors.Is(err, fs.ErrNotExist) && !errors.Is(err, syscall.ENOTDIR) { + return true + } + } + } + return false +} + func LoadConfiguration(configFileName string, required bool) (loaded bool) { // MergeInConfig mutates the shared viper that ViperProxy serializes; // take the same lock so a merge cannot race a reader or SetDefault. @@ -92,8 +136,9 @@ func LoadConfiguration(configFileName string, required bool) (loaded bool) { // environment overrides. Unlike LoadConfiguration it does not merge, so a key // the file no longer sets reads as unset. A non-empty configFile is read in // place of searching the configuration directories. used is the file read, or -// empty when none could be; the environment still applies then. -func ReadConfiguration(configFileName, configFile string) (v *ViperProxy, used string) { +// empty when none could be; the environment still applies then. The read +// error is returned rather than logged: parser errors can quote values. +func ReadConfiguration(configFileName, configFile string) (v *ViperProxy, used string, readErr error) { fresh := viper.New() setEnvOverrides(fresh) if configFile != "" { @@ -102,19 +147,22 @@ func ReadConfiguration(configFileName, configFile string) (v *ViperProxy, used s setConfigurationPaths(fresh, configFileName) } if err := fresh.ReadInConfig(); err != nil { - glog.V(1).Infof("Reading %s: %v", configFileName, err) - return NewViperProxy(fresh), "" + return NewViperProxy(fresh), "", err } - return NewViperProxy(fresh), fresh.ConfigFileUsed() + return NewViperProxy(fresh), fresh.ConfigFileUsed(), nil +} + +// configurationPaths are the directories searched for configuration files, +// in order. +func configurationPaths() []string { + return []string{ResolvePath(ConfigurationFileDirectory.String()), ".", "$HOME/.seaweedfs", "/usr/local/etc/seaweedfs/", "/etc/seaweedfs/"} } func setConfigurationPaths(v *viper.Viper, configFileName string) { v.SetConfigName(configFileName) - v.AddConfigPath(ResolvePath(ConfigurationFileDirectory.String())) - v.AddConfigPath(".") - v.AddConfigPath("$HOME/.seaweedfs") - v.AddConfigPath("/usr/local/etc/seaweedfs/") - v.AddConfigPath("/etc/seaweedfs/") + for _, dir := range configurationPaths() { + v.AddConfigPath(dir) + } } func setEnvOverrides(v *viper.Viper) { diff --git a/weed/util/config_test.go b/weed/util/config_test.go index ae34e58125..dbf303f51c 100644 --- a/weed/util/config_test.go +++ b/weed/util/config_test.go @@ -4,6 +4,7 @@ import ( "fmt" "os" "path/filepath" + "strings" "sync" "testing" @@ -66,23 +67,23 @@ func TestReadConfigurationDropsKeysTheFileNoLongerSets(t *testing.T) { } } - v, used := ReadConfiguration("readconf_test", "") + v, used, _ := ReadConfiguration("readconf_test", "") assert.Empty(t, used, "missing file") assert.Equal(t, "from-env", v.GetString("readconf.env")) write("[readconf]\nkey = \"v1\"\n") - v, used = ReadConfiguration("readconf_test", "") + v, used, _ = ReadConfiguration("readconf_test", "") assert.Equal(t, filepath.Join(dir, "readconf_test.toml"), used) assert.Equal(t, "v1", v.GetString("readconf.key")) write("[readconf]\n") - v, used = ReadConfiguration("readconf_test", "") + v, used, _ = ReadConfiguration("readconf_test", "") assert.NotEmpty(t, used) assert.Empty(t, v.GetString("readconf.key")) assert.Equal(t, "from-env", v.GetString("readconf.env")) write("[readconf\n") - v, used = ReadConfiguration("readconf_test", "") + v, used, _ = ReadConfiguration("readconf_test", "") assert.Empty(t, used, "unparsable file") assert.Equal(t, "from-env", v.GetString("readconf.env")) } @@ -96,13 +97,96 @@ func TestReadConfigurationReadsTheGivenFile(t *testing.T) { t.Fatal(err) } - _, used := ReadConfiguration("readconf_test", given) + _, used, _ := ReadConfiguration("readconf_test", given) assert.Empty(t, used, "missing given file must not fall back to a search") if err := os.WriteFile(given, []byte("[readconf]\nkey = \"given\"\n"), 0o600); err != nil { t.Fatal(err) } - v, used := ReadConfiguration("readconf_test", given) + v, used, _ := ReadConfiguration("readconf_test", given) assert.Equal(t, given, used) assert.Equal(t, "given", v.GetString("readconf.key")) } + +func TestLoadSecurityConfigurationOrErrorRefusesAnUnreadableFile(t *testing.T) { + dir := t.TempDir() + t.Setenv("HOME", t.TempDir()) + saved := ConfigurationFileDirectory + ConfigurationFileDirectory = DirectoryValueType(dir) + t.Cleanup(func() { ConfigurationFileDirectory = saved }) + + if err := LoadSecurityConfigurationOrError(); err != nil { + t.Fatalf("missing security.toml: %v", err) + } + const secret = "parser-must-not-echo-this" + if err := os.WriteFile(filepath.Join(dir, "security.toml"), []byte("[grpc.client\nkey = \""+secret+"\"\n"), 0600); err != nil { + t.Fatal(err) + } + err := LoadSecurityConfigurationOrError() + if err == nil { + t.Fatal("malformed security.toml was accepted") + } + if strings.Contains(err.Error(), secret) { + t.Fatal("the error quotes the configuration") + } + + // A readable file is merged by the same, single read. + if err := os.WriteFile(filepath.Join(dir, "security.toml"), []byte("[load_security_test]\nmarker = \"merged\"\n"), 0600); err != nil { + t.Fatal(err) + } + if err := LoadSecurityConfigurationOrError(); err != nil { + t.Fatalf("readable security.toml: %v", err) + } + if got := GetViper().GetString("load_security_test.marker"); got != "merged" { + t.Fatalf("settings of the checked file were not merged: %q", got) + } +} + +func TestLoadSecurityConfigurationOrErrorRefusesADirectoryItCannotSearch(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("root can search any directory") + } + dir := t.TempDir() + t.Setenv("HOME", t.TempDir()) + saved := ConfigurationFileDirectory + ConfigurationFileDirectory = DirectoryValueType(dir) + t.Cleanup(func() { ConfigurationFileDirectory = saved }) + if err := os.WriteFile(filepath.Join(dir, "security.toml"), []byte("[grpc]\n"), 0600); err != nil { + t.Fatal(err) + } + if err := os.Chmod(dir, 0); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.Chmod(dir, 0700) }) + if err := LoadSecurityConfigurationOrError(); err == nil { + t.Fatal("a security.toml in a directory the process cannot search was treated as absent") + } +} + +func TestLoadSecurityConfigurationOrErrorRefusesACandidateItCannotCheck(t *testing.T) { + dir := t.TempDir() + t.Setenv("HOME", t.TempDir()) + saved := ConfigurationFileDirectory + ConfigurationFileDirectory = DirectoryValueType(dir) + t.Cleanup(func() { ConfigurationFileDirectory = saved }) + // A symlink loop: stat fails with ELOOP, which is not absence. + loop := filepath.Join(dir, "security.toml") + if err := os.Symlink(loop, loop); err != nil { + t.Skipf("symlinks unavailable: %v", err) + } + if err := LoadSecurityConfigurationOrError(); err == nil { + t.Fatal("a security.toml that cannot be checked was treated as absent") + } + // A plain file where a configuration directory is expected is absence. + if err := os.Remove(loop); err != nil { + t.Fatal(err) + } + notDir := filepath.Join(dir, "not-a-directory") + if err := os.WriteFile(notDir, nil, 0600); err != nil { + t.Fatal(err) + } + ConfigurationFileDirectory = DirectoryValueType(notDir) + if err := LoadSecurityConfigurationOrError(); err != nil { + t.Fatalf("configuration directory that is a file: %v", err) + } +} diff --git a/weed/util/fips140_keys.go b/weed/util/fips140_keys.go index bddb0bbc8a..86d71f4f28 100644 --- a/weed/util/fips140_keys.go +++ b/weed/util/fips140_keys.go @@ -25,6 +25,8 @@ var jwtSigningKeySettings = []string{ "jwt.filer_signing.previous_key", "jwt.filer_signing.read.key", "jwt.filer_signing.read.previous_key", + "jwt.filer_signing.grpc_key", + "jwt.filer_signing.grpc_previous_key", "jwt.filer_signing.subscribe.key", } diff --git a/weed/wdclient/filer_client.go b/weed/wdclient/filer_client.go index fd9f917240..82ee3e531b 100644 --- a/weed/wdclient/filer_client.go +++ b/weed/wdclient/filer_client.go @@ -19,6 +19,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/pb" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/pb/master_pb" + "github.com/seaweedfs/seaweedfs/weed/security" "github.com/seaweedfs/seaweedfs/weed/util" ) @@ -50,6 +51,7 @@ type FilerClient struct { peerUpdates uint64 // pushed filer updates applied; protected by filerAddressesMu deferredLeaves map[pb.ServerAddress]struct{} // leaves suppressed while the filer was the last known; protected by filerAddressesMu grpcDialOption grpc.DialOption + tokenSource security.FilerTokenSource urlPreference UrlPreference grpcTimeout time.Duration cacheSize int // Number of historical vidMap snapshots to keep @@ -109,6 +111,9 @@ type FilerClientOption struct { // the client returns to it once its circuit breaker resets, backing off if it // keeps failing. Embedded S3 gateways set it to their local filer. HomeFiler pb.ServerAddress + // FilerTokenSource supplies per-call authorization for filer RPCs. A nil + // value preserves the existing anonymous behavior. + FilerTokenSource security.FilerTokenSource } // NewFilerClient creates a new client that queries filer(s) for volume locations @@ -131,6 +136,7 @@ func NewFilerClient(filerAddresses []pb.ServerAddress, grpcDialOption grpc.DialO var masterClient *MasterClient var filerGroup string var homeFiler pb.ServerAddress + var tokenSource security.FilerTokenSource discoveryInterval := 5 * time.Minute // Default: refresh every 5 minutes // Override with provided options @@ -161,6 +167,9 @@ func NewFilerClient(filerAddresses []pb.ServerAddress, grpcDialOption grpc.DialO retryBackoffFactor = opt.RetryBackoffFactor } homeFiler = opt.HomeFiler + if opt.FilerTokenSource != nil { + tokenSource = opt.FilerTokenSource + } if opt.MasterClient != nil { masterClient = opt.MasterClient filerGroup = opt.FilerGroup @@ -181,6 +190,7 @@ func NewFilerClient(filerAddresses []pb.ServerAddress, grpcDialOption grpc.DialO filerIndex: 0, filerHealth: health, grpcDialOption: grpcDialOption, + tokenSource: tokenSource, urlPreference: urlPref, grpcTimeout: grpcTimeout, cacheSize: cacheSize, @@ -1027,7 +1037,7 @@ func (p *filerVolumeProvider) LookupVolumeIds(ctx context.Context, volumeIds []s timeoutCtx, cancel := context.WithTimeout(ctx, fc.grpcTimeout) defer cancel() // Always clean up context, even on panic or early return - return pb.WithGrpcFilerClient(false, fc.clientId, filerAddress, fc.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + return pb.WithGrpcFilerClient(false, fc.clientId, filerAddress, fc.grpcDialOption, fc.tokenSource, func(client filer_pb.SeaweedFilerClient) error { resp, err := client.LookupVolume(timeoutCtx, &filer_pb.LookupVolumeRequest{ VolumeIds: volumeIds, }) diff --git a/weed/worker/tasks/iceberg/handler.go b/weed/worker/tasks/iceberg/handler.go index 9f8412bb9d..d80f9f849b 100644 --- a/weed/worker/tasks/iceberg/handler.go +++ b/weed/worker/tasks/iceberg/handler.go @@ -13,6 +13,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb" pluginworker "github.com/seaweedfs/seaweedfs/weed/plugin/worker" + "github.com/seaweedfs/seaweedfs/weed/security" "google.golang.org/grpc" "google.golang.org/protobuf/types/known/timestamppb" ) @@ -433,7 +434,7 @@ func (h *Handler) Detect(ctx context.Context, request *plugin_pb.RunDetectionReq return fmt.Errorf("connect to filer: %w", err) } defer conn.Close() - filerClient := filer_pb.NewSeaweedFilerClient(conn) + filerClient := filer_pb.NewSeaweedFilerClient(security.WithFilerClientAuth(conn, security.FilerAdminToken)) maxResults := int(request.MaxResults) scanLimit := maxResults @@ -546,7 +547,7 @@ func (h *Handler) Execute(ctx context.Context, request *plugin_pb.ExecuteJobRequ return fmt.Errorf("connect to filer %s: %w", filerGrpcAddress, err) } defer conn.Close() - filerClient := filer_pb.NewSeaweedFilerClient(conn) + filerClient := filer_pb.NewSeaweedFilerClient(security.WithFilerClientAuth(conn, security.FilerAdminToken)) // Resolve once for the whole job: compaction commits new metadata as it // runs, and a job should not change settings halfway through. Both reads @@ -717,7 +718,7 @@ func (h *Handler) dialFiler(ctx context.Context, grpcAddress string) (*grpc.Clie return nil, err } - client := filer_pb.NewSeaweedFilerClient(conn) + client := filer_pb.NewSeaweedFilerClient(security.WithFilerClientAuth(conn, security.FilerAdminToken)) if _, err := client.Ping(opCtx, &filer_pb.PingRequest{}); err != nil { _ = conn.Close() return nil, err diff --git a/weed/worker/tasks/iceberg/handler_filer_auth_test.go b/weed/worker/tasks/iceberg/handler_filer_auth_test.go new file mode 100644 index 0000000000..3308f3759e --- /dev/null +++ b/weed/worker/tasks/iceberg/handler_filer_auth_test.go @@ -0,0 +1,94 @@ +package iceberg + +import ( + "context" + "crypto/rand" + "encoding/hex" + "net" + "testing" + "time" + + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/security" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" +) + +type icebergAuthFiler struct { + filer_pb.UnimplementedSeaweedFilerServer + key security.SigningKey + authResults chan bool +} + +func (f *icebergAuthFiler) Ping(ctx context.Context, _ *filer_pb.PingRequest) (*filer_pb.PingResponse, error) { + err := security.CheckGrpcAdminToken(ctx, f.key) + f.authResults <- err == nil + if err != nil { + return nil, err + } + return &filer_pb.PingResponse{}, nil +} + +func icebergTestSigningKey(t *testing.T) security.SigningKey { + t.Helper() + bytes := make([]byte, 32) + if _, err := rand.Read(bytes); err != nil { + t.Fatal(err) + } + return security.SigningKey(hex.EncodeToString(bytes)) +} + +func TestDialFilerUsesPerCallAdminToken(t *testing.T) { + key := icebergTestSigningKey(t) + wrongKey := icebergTestSigningKey(t) + cases := []struct { + name string + workerKey string + wantErr bool + }{ + {name: "accepted key", workerKey: string(key)}, + {name: "missing key", workerKey: "", wantErr: true}, + {name: "wrong key", workerKey: string(wrongKey), wantErr: true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Setenv("WEED_JWT_FILER_SIGNING_GRPC_KEY", tc.workerKey) + t.Setenv("WEED_JWT_FILER_SIGNING_KEY", "") + + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + filer := &icebergAuthFiler{key: key, authResults: make(chan bool, 1)} + server := grpc.NewServer() + filer_pb.RegisterSeaweedFilerServer(server, filer) + go server.Serve(listener) + t.Cleanup(func() { + server.Stop() + _ = listener.Close() + }) + + conn, err := NewHandler(grpc.WithTransportCredentials(insecure.NewCredentials())).dialFiler(context.Background(), listener.Addr().String()) + if tc.wantErr { + if status.Code(err) != codes.Unauthenticated { + t.Fatalf("dialFiler error code = %s, want Unauthenticated", status.Code(err)) + } + } else { + if err != nil { + t.Fatalf("dialFiler: %v", err) + } + t.Cleanup(func() { _ = conn.Close() }) + } + select { + case valid := <-filer.authResults: + if valid != !tc.wantErr { + t.Fatalf("filer authentication result did not match case") + } + case <-time.After(time.Second): + t.Fatal("filer did not receive the Ping request") + } + }) + } +} diff --git a/weed/worker/tasks/s3_lifecycle/handler.go b/weed/worker/tasks/s3_lifecycle/handler.go index 8a80fef9a0..eb4403fe7a 100644 --- a/weed/worker/tasks/s3_lifecycle/handler.go +++ b/weed/worker/tasks/s3_lifecycle/handler.go @@ -20,6 +20,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/dispatcher" "github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/engine" "github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/scheduler" + "github.com/seaweedfs/seaweedfs/weed/security" "github.com/seaweedfs/seaweedfs/weed/stats" "golang.org/x/time/rate" "google.golang.org/grpc" @@ -246,13 +247,13 @@ func (h *Handler) Execute(ctx context.Context, request *plugin_pb.ExecuteJobRequ }) dialCtx, dialCancel := context.WithTimeout(runCtx, 30*time.Second) - filerConn, err := pb.GrpcDial(dialCtx, filerAddress, false, h.grpcDialOption) - dialCancel() + filerConn, filerClient, err := h.dialFiler(dialCtx, filerAddress) if err != nil { + dialCancel() return fmt.Errorf("dial filer %s: %w", filerAddress, err) } + dialCancel() defer filerConn.Close() - filerClient := filer_pb.NewSeaweedFilerClient(filerConn) bucketsPath, err := lookupBucketsPath(runCtx, filerClient) if err != nil { @@ -306,6 +307,17 @@ func sendCompletion(request *plugin_pb.ExecuteJobRequest, sender pluginworker.Ex }) } +// dialFiler connects a lifecycle worker to a filer and attaches the current +// admin token per filer RPC. The connection is returned separately so callers +// can close it after the lifecycle pass completes. +func (h *Handler) dialFiler(ctx context.Context, filerAddress string) (*grpc.ClientConn, filer_pb.SeaweedFilerClient, error) { + conn, err := pb.GrpcDial(ctx, filerAddress, false, h.grpcDialOption) + if err != nil { + return nil, nil, err + } + return conn, filer_pb.NewSeaweedFilerClient(security.WithFilerClientAuth(conn, security.FilerAdminToken)), nil +} + // executeDailyReplay runs one bounded daily-replay pass via // dailyrun.Run. The walker fires inside runShard on rule-content edits // and against the steady-state walk view; all rule kinds are serviced. diff --git a/weed/worker/tasks/s3_lifecycle/handler_filer_auth_test.go b/weed/worker/tasks/s3_lifecycle/handler_filer_auth_test.go new file mode 100644 index 0000000000..79ffda3df6 --- /dev/null +++ b/weed/worker/tasks/s3_lifecycle/handler_filer_auth_test.go @@ -0,0 +1,92 @@ +package s3_lifecycle + +import ( + "context" + "crypto/rand" + "encoding/hex" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/security" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +type lifecycleAuthFiler struct { + filer_pb.UnimplementedSeaweedFilerServer + key security.SigningKey + authResults chan bool + configCalls atomic.Int32 +} + +func (f *lifecycleAuthFiler) GetFilerConfiguration(ctx context.Context, _ *filer_pb.GetFilerConfigurationRequest) (*filer_pb.GetFilerConfigurationResponse, error) { + f.configCalls.Add(1) + err := security.CheckGrpcAdminToken(ctx, f.key) + f.authResults <- err == nil + if err != nil { + return nil, err + } + return &filer_pb.GetFilerConfigurationResponse{DirBuckets: "/buckets"}, nil +} + +func lifecycleTestSigningKey(t *testing.T) security.SigningKey { + t.Helper() + bytes := make([]byte, 32) + if _, err := rand.Read(bytes); err != nil { + t.Fatal(err) + } + return security.SigningKey(hex.EncodeToString(bytes)) +} + +func TestDialFilerUsesPerCallAdminToken(t *testing.T) { + key := lifecycleTestSigningKey(t) + wrongKey := lifecycleTestSigningKey(t) + cases := []struct { + name string + workerKey string + wantErr bool + }{ + {name: "accepted key", workerKey: string(key)}, + {name: "missing key", workerKey: "", wantErr: true}, + {name: "wrong key", workerKey: string(wrongKey), wantErr: true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Setenv("WEED_JWT_FILER_SIGNING_GRPC_KEY", tc.workerKey) + t.Setenv("WEED_JWT_FILER_SIGNING_KEY", "") + + filer := &lifecycleAuthFiler{key: key, authResults: make(chan bool, 1)} + address := serveGrpc(t, func(server *grpc.Server) { + filer_pb.RegisterSeaweedFilerServer(server, filer) + }) + h := newTestHandler() + conn, client, err := h.dialFiler(context.Background(), address) + if err != nil { + t.Fatalf("dialFiler: %v", err) + } + t.Cleanup(func() { _ = conn.Close() }) + _, lookupErr := lookupBucketsPath(context.Background(), client) + if tc.wantErr { + if status.Code(lookupErr) != codes.Unauthenticated { + t.Fatalf("lookupBucketsPath error code = %s, want Unauthenticated", status.Code(lookupErr)) + } + } else if lookupErr != nil { + t.Fatalf("lookupBucketsPath: %v", lookupErr) + } + select { + case valid := <-filer.authResults: + if valid != !tc.wantErr { + t.Fatalf("filer authentication result did not match case") + } + case <-time.After(time.Second): + t.Fatal("filer did not receive the configuration request") + } + if got := filer.configCalls.Load(); got != 1 { + t.Fatalf("configuration RPC count = %d, want 1", got) + } + }) + } +}