Files
seaweedfs/weed/mount/sse_s3_reader.go
T
bcd678271e mount: authorize filer calls with a pre-issued token file (#13118)
* security: filer token source read from a file

FilerTokenFile is the token source of a client that holds a pre-issued
filer token rather than a signing key. It reads the file on every call,
so an atomic replacement that keeps size and mtime takes effect on the
next attempt, and trims surrounding whitespace. A missing, unreadable,
empty or malformed file fails the call: there is no fallback to anonymous
or admin authority, and errors name the path but not the contents.

FilerTokenClaims decodes a token's claims without a key, and
FilerTokenGrantCovers compares two grants, so a client can plan
reconnects before expiry and know when a replacement narrows what it
may see.

* mount: -filer.tokenFile authorizes filer calls with a pre-issued token

A mount that should not hold a filer signing key can now present a
token issued for it. -filer.tokenFile (or -o filer.tokenFile=) names the
file; it is read for every filer gRPC attempt, so a replaced file takes
effect on the next call or retry without a restart, and a missing or
empty file fails the call locally.

The source reaches every filer client the mount builds: the startup
handshake, each attempt of WithFilerClient, the volume location client,
the SSE-S3 reader's configuration call, the peer registrar dial and the
lock client. It is attached per call, never to the cached channel, and
never to master, volume or peer mount RPCs.

The filer refuses MountRegister, MountList and distributed locks to
scoped tokens, so the mount refuses to start when -filer.tokenFile is
combined with -peer.enable or -dlm instead of failing at run time.
Server-side copy_file_range signs its filer HTTP request with the HTTP
key, not this token, and is unsupported with it.

Without the flag the mount behaves as before.

* mount: resubscribe metadata with a replaced filer token

A metadata subscription keeps the authority it opened with, so a mount
reading -filer.tokenFile would follow with the old token until the filer
ended the stream at expiry, and every such end took the gap path that
distrusts all cached listings.

SubscribeMetaEvents now takes the credentials of each attempt. The mount
opens each subscription with the token current at that moment and
watches the file; once it holds a different token the attempt ends and
the follow resubscribes at once from its checkpoint. This planned
resubscribe is not a gap: cached listings stay, unless the new grant may
show less than the old one or either token cannot be decoded, in which
case they are read again so nothing the old grant showed outlives it.

The filer walk treats a resubscribe like a stopped follow, so the same
attempt is not replayed on the next filer. Without a token file nothing
changes.

* mount: hand the mutation stream over to a replaced filer token

The mutation stream keeps the token it opened with, and a filer refuses
to send on a scoped stream once that token has expired. A mutation
applied at that moment loses its reply, the mount reads that as a
transport failure, and the unary fallback sends it again.

The stream now opens with a snapshot of the token source. Before
admitting a request it checks the source: when the file holds another
token, or the stream's token would expire before a reply could come
back, the stream is retired. New requests wait while the admitted ones
are answered, the stream is half-closed so the filer finishes it, and a
successor opens with the new token. The waits give up only after
filerRPCWait without a response, so a rename that keeps answering is not
cut short. A request is never resent by the handover: one still
unanswered when the wait gives up fails as on any lost stream, as
before.

A token too close to expiry to open a stream with is refused before
anything is sent, so the request goes out once as a unary call, which
the filer checks when it starts. Without a token file nothing changes.

* mount: review fixes for the filer token file

- A distrust of cached listings now also discards the directory builds in
  flight, in the meta cache's apply loop: such a build publishes nothing,
  its entries are wiped and the visit lists the directory again, so a
  listing read under a grant that has since narrowed is never cached after
  the distrust. The cached flags are reset again in the loop, after any
  build that completed before it.
- Retiring the mutation stream runs in the background, and a request that
  waits for the retirement gives up on its own context, unadmitted.
- With a token file and no filer signing key, server-side whole-file copy
  is not tried: its filer HTTP request would go out unsigned and fail as
  ambiguous. The copy streams through the chunk path instead.
- On Windows the token file is opened with delete sharing, so a renewer
  can replace it by rename while a read holds it open; the missing-file
  test checks os.ErrNotExist instead of Unix wording.

* mount: review fixes for the mutation stream handover

A request admitted to the mutation stream with just over one RPC wait
left on its token could wait behind a slow send until that margin was
gone; its reply could then be refused at expiry and the request was
resent over unary. The send loop now checks the margin again right
before sending and holds back a request that no longer has it, which is
safe to send over unary because the filer never saw it. A sent request
whose reply is lost while the token has one RPC wait or less left now
fails with EIO instead of a transport error: the filer may have applied
it, so it is not resent. Losses with the margin intact fall back to
unary as before.

A newly opened stream now admits its first request through the same
checks as an open one, so a token file replaced, or a token that neared
expiry, while the stream opened is caught before anything is sent.

A retirement keeps a cancel handle for its stream. Close uses it, so
unmount no longer waits for admitted requests to be answered, and a
waiter that gives up on a retiring stream stops it as it would stop an
open one, so a request still queued there is never sent after that
waiter fell back to unary. An ordinary rotation still drains admitted
requests.

* mount: drop kernel listings when the filer token's grant narrows

A replacement token whose grant may not cover the old one already
distrusts the mount's own cached listings. The kernel kept its own copy:
OpenDir sets FOPEN_CACHE_DIR | FOPEN_KEEP_CACHE, so a directory still
reachable under the new grant was listed again from the page cache with
names the new grant may hide, until something else invalidated it.

On a narrowed or undecodable grant the mount now also notifies the
kernel for every directory inode it holds, from the subscription
goroutine as the metadata apply path already does, so the next readdir
reaches the mount. A readdir already under way on an open handle still
finishes from what it read.

* mount: drop kernel listings after a subscription gap too

distrustCachedListings serves both the narrowed-grant path and the gap
path. A gap can lose the very events that would have dropped the kernel's
cached listings one directory at a time, and with FOPEN_KEEP_CACHE on
OpenDir the kernel then serves those listings on every reopen. Move the
kernel drop into distrustCachedListings so both paths get it.

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

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 13:02:28 -08:00

240 lines
8.0 KiB
Go

package mount
import (
"context"
"errors"
"fmt"
"io"
"math/rand/v2"
"net/url"
"path"
"slices"
"strings"
"sync"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/s3/types"
smithyhttp "github.com/aws/smithy-go/transport/http"
"google.golang.org/grpc"
"github.com/seaweedfs/seaweedfs/weed/cluster"
"github.com/seaweedfs/seaweedfs/weed/filer"
"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/pb/master_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/security"
)
var (
errSSES3Permission = errors.New("S3 gateway denied object read")
errNoS3Gateway = errors.New("no S3 gateway is registered with the masters")
)
// SSES3Reader makes signed range requests for one mounted bucket. The S3
// gateway owns the encryption keys and applies its normal GetObject policy.
type SSES3Reader struct {
cfg aws.Config
endpoints func(context.Context) ([]string, error)
root string
bucket string
clientLock sync.Mutex
client *s3.Client
endpoint string
}
// NewSSES3Reader reads through the S3 gateways the filer's masters list for
// its filer group.
func NewSSES3Reader(ctx context.Context, bucketPath string, filers []pb.ServerAddress, grpcDialOption grpc.DialOption, filerTokenSource security.FilerTokenSource) (*SSES3Reader, error) {
cfg, err := config.LoadDefaultConfig(ctx, config.WithDefaultRegion("us-east-1"))
if err != nil {
return nil, err
}
return &SSES3Reader{
cfg: cfg,
endpoints: func(ctx context.Context) ([]string, error) {
return listS3Endpoints(ctx, filers, grpcDialOption, filerTokenSource)
},
root: bucketPath + "/",
bucket: path.Base(bucketPath),
}, nil
}
// listS3Endpoints asks a filer for its masters with the mount's filer token,
// then the masters for the gateways; the master calls carry no filer token.
func listS3Endpoints(ctx context.Context, filers []pb.ServerAddress, grpcDialOption grpc.DialOption, filerTokenSource security.FilerTokenSource) ([]string, error) {
var masters []string
var filerGroup string
if err := pb.WithOneOfGrpcFilerClients(false, filers, grpcDialOption, filerTokenSource, func(client filer_pb.SeaweedFilerClient) error {
resp, err := client.GetFilerConfiguration(ctx, &filer_pb.GetFilerConfigurationRequest{})
if err != nil {
return err
}
masters, filerGroup = resp.Masters, resp.FilerGroup
return nil
}); err != nil {
return nil, err
}
var endpoints []string
var err error
// Only the leader lists the gateways, so a follower answers with none.
for _, master := range masters {
err = pb.WithMasterClient(ctx, false, pb.ServerAddress(master), grpcDialOption, false, func(client master_pb.SeaweedClient) error {
resp, err := client.ListClusterNodes(ctx, &master_pb.ListClusterNodesRequest{ClientType: cluster.S3Type, FilerGroup: filerGroup})
if err != nil {
return err
}
for _, node := range resp.ClusterNodes {
if node.S3Endpoint != "" {
endpoints = append(endpoints, node.S3Endpoint)
}
}
return nil
})
if len(endpoints) > 0 {
return endpoints, nil
}
}
if err != nil {
return nil, err
}
return nil, errNoS3Gateway
}
// gatewayClient picks one of the registered gateways other than failed, using
// HTTPS whenever an HTTPS gateway is registered, and keeps it until a request
// cannot reach it.
func (r *SSES3Reader) gatewayClient(ctx context.Context, failed string) (*s3.Client, string, error) {
r.clientLock.Lock()
defer r.clientLock.Unlock()
if r.client != nil && r.endpoint != failed {
return r.client, r.endpoint, nil
}
endpoints, err := r.endpoints(ctx)
if err != nil {
return nil, "", err
}
endpoints = slices.DeleteFunc(endpoints, func(endpoint string) bool {
u, err := url.Parse(endpoint)
return err != nil || u.Scheme != "https" && u.Scheme != "http" || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.Fragment != ""
})
isHTTPS := func(endpoint string) bool {
u, err := url.Parse(endpoint)
return err == nil && u.Scheme == "https"
}
if https := slices.DeleteFunc(slices.Clone(endpoints), func(endpoint string) bool { return !isHTTPS(endpoint) }); len(https) > 0 {
endpoints = https
}
endpoints = slices.DeleteFunc(endpoints, func(endpoint string) bool { return endpoint == failed })
if len(endpoints) == 0 {
return nil, "", errNoS3Gateway
}
endpoint := endpoints[rand.IntN(len(endpoints))]
if !isHTTPS(endpoint) {
glog.Warningf("-sseS3Read: no HTTPS S3 gateway is registered, reading %s over plain HTTP", endpoint)
}
r.client = s3.NewFromConfig(r.cfg, func(o *s3.Options) {
o.BaseEndpoint = aws.String(endpoint)
o.UsePathStyle = true
})
r.endpoint = endpoint
return r.client, endpoint, nil
}
// getObject retries once on another gateway when the current one cannot be
// reached.
func (r *SSES3Reader) getObject(ctx context.Context, req *s3.GetObjectInput) (*s3.GetObjectOutput, error) {
client, endpoint, err := r.gatewayClient(ctx, "")
if err != nil {
return nil, err
}
obj, err := client.GetObject(ctx, req)
var sendErr *smithyhttp.RequestSendError
if !errors.As(err, &sendErr) || ctx.Err() != nil {
return obj, err
}
r.clientLock.Lock()
if r.client == client {
r.client = nil
}
r.clientLock.Unlock()
retry, _, pickErr := r.gatewayClient(ctx, endpoint)
if pickErr != nil {
return nil, err
}
return retry.GetObject(ctx, req)
}
func sseObjectETag(entry *filer_pb.Entry) string {
if stored := string(entry.GetExtended()[s3_constants.ExtETagKey]); stored != "" {
return `"` + strings.Trim(stored, `"`) + `"`
}
return `"` + filer.ETag(entry) + `"`
}
func (r *SSES3Reader) readAt(ctx context.Context, fullPath, etag, version string, size int64, buf []byte, offset int64) (int64, error) {
key, ok := strings.CutPrefix(fullPath, r.root)
if !ok || key == "" || key == "." || key == ".." || path.IsAbs(key) || path.Clean(key) != key || strings.HasPrefix(key, "../") {
return 0, errNativeSSERead
}
versionFile := false
if dir, name := path.Split(key); version != "" && name == "v_"+version {
if object, found := strings.CutSuffix(strings.TrimSuffix(dir, "/"), s3_constants.VersionsFolder); found && object != "" {
key, versionFile = object, true
}
}
if offset < 0 || size < 0 {
return 0, errors.New("invalid S3 object range")
}
if len(buf) == 0 {
return 0, nil
}
if offset >= size {
return 0, io.EOF
}
n := min(int64(len(buf)), size-offset)
last := offset + n - 1
req := &s3.GetObjectInput{
Bucket: aws.String(r.bucket), Key: aws.String(key),
IfMatch: aws.String(etag), Range: aws.String(fmt.Sprintf("bytes=%d-%d", offset, last)),
}
currentNull := version == "null" && !versionFile
if version != "" && !currentNull {
req.VersionId = aws.String(version)
}
obj, err := r.getObject(ctx, req)
if currentNull && (err == nil && aws.ToString(obj.VersionId) != "" && aws.ToString(obj.VersionId) != version || err != nil && !isS3PermissionError(err)) {
if err == nil {
obj.Body.Close()
}
req.VersionId = aws.String(version)
obj, err = r.getObject(ctx, req)
}
if err != nil {
if isS3PermissionError(err) {
return 0, errSSES3Permission
}
return 0, err
}
defer obj.Body.Close()
wantRange := fmt.Sprintf("bytes %d-%d/%d", offset, last, size)
if aws.ToString(obj.ContentRange) != wantRange || aws.ToInt64(obj.ContentLength) != n ||
aws.ToString(obj.ETag) != etag || obj.ServerSideEncryption != types.ServerSideEncryptionAes256 ||
(version != "" && aws.ToString(obj.VersionId) != version && (req.VersionId != nil || aws.ToString(obj.VersionId) != "")) {
return 0, errors.New("S3 response did not match the encrypted object range")
}
if _, err := io.ReadFull(obj.Body, buf[:n]); err != nil {
return 0, err
}
return n, nil
}
func isS3PermissionError(err error) bool {
var respErr *smithyhttp.ResponseError
return errors.As(err, &respErr) && (respErr.HTTPStatusCode() == 403 || respErr.HTTPStatusCode() == 401)
}