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

* Authenticate gateway filer calls with per-call admin tokens

* Authenticate shell admin and synchronization filer calls

* Authenticate workers MQ and remaining filer client paths

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* util: return the read error from ReadConfiguration

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

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

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

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

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

* util: read security.toml once in LoadSecurityConfigurationOrError

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

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

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

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

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

---------

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

322 lines
12 KiB
Go

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)
}
}
}