Files
seaweedfs/weed/shell/command_s3_clean_uploads.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

303 lines
11 KiB
Go

package shell
import (
"context"
"errors"
"flag"
"fmt"
"io"
"math"
"path"
"strings"
"time"
"github.com/google/uuid"
"github.com/seaweedfs/seaweedfs/weed/cluster"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/util"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
)
func init() {
Commands = append(Commands, &commandS3CleanUploads{})
}
type commandS3CleanUploads struct{}
func (c *commandS3CleanUploads) Name() string {
return "s3.clean.uploads"
}
func (c *commandS3CleanUploads) Help() string {
return `clean up stale multipart uploads
Example:
s3.clean.uploads -timeAgo 1.5h
`
}
func (c *commandS3CleanUploads) HasTag(CommandTag) bool {
return false
}
func (c *commandS3CleanUploads) Do(args []string, commandEnv *CommandEnv, writer io.Writer) (err error) {
bucketCommand := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
uploadedTimeAgo := bucketCommand.Duration("timeAgo", 24*time.Hour, "created time before now. \"1.5h\" or \"2h45m\". Valid time units are \"m\", \"h\"")
if err = bucketCommand.Parse(args); err != nil {
return err
}
var filerBucketsPath string
filerBucketsPath, err = readFilerBucketsPath(commandEnv)
if err != nil {
return fmt.Errorf("read buckets: %w", err)
}
var buckets []*filer_pb.Entry
err = filer_pb.List(context.Background(), commandEnv, filerBucketsPath, "", func(entry *filer_pb.Entry, isLast bool) error {
buckets = append(buckets, entry)
return nil
}, "", false, math.MaxUint32)
if err != nil {
return fmt.Errorf("list buckets under %v: %w", filerBucketsPath, err)
}
lock := newObjectWriteLock(commandEnv)
for _, bucket := range buckets {
if err := c.cleanupUploads(commandEnv, writer, filerBucketsPath, bucket.Name, *uploadedTimeAgo, lock); err != nil {
fmt.Fprintf(writer, "failed cleanup uploads for bucket %s: %v\n", bucket.Name, err)
}
}
return err
}
func (c *commandS3CleanUploads) cleanupUploads(commandEnv *CommandEnv, writer io.Writer, filerBucketsPath string, bucket string, timeAgo time.Duration, lock objectWriteLock) error {
bucketDir := filerBucketsPath + "/" + bucket
uploadsDir := bucketDir + "/" + s3_constants.MultipartUploadsFolder
var staleUploads []*filer_pb.Entry
now := time.Now()
err := filer_pb.List(context.Background(), commandEnv, uploadsDir, "", func(entry *filer_pb.Entry, isLast bool) error {
ctime := time.Unix(entry.Attributes.Crtime, 0)
if ctime.Add(timeAgo).Before(now) {
staleUploads = append(staleUploads, entry)
}
return nil
}, "", false, math.MaxUint32)
if err != nil {
return fmt.Errorf("list uploads under %v: %w", uploadsDir, err)
}
for _, staleUpload := range staleUploads {
held, release, lockErr := lock(uploadObjectPath(bucketDir, staleUpload))
if lockErr != nil {
fmt.Fprintf(writer, "skip %s: %v\n", staleUpload.Name, lockErr)
continue
}
err := c.removeUploadDir(commandEnv, writer, bucketDir, uploadsDir, staleUpload, held)
release()
if err != nil {
return err
}
}
return nil
}
// objectWriteLock takes the distributed lock the S3 gateway commits a
// completion under when it is not routed to the object's owner filer, and
// renews it until release. It gives up after a minute of contention.
type objectWriteLock func(objectPath string) (held func() bool, release func(), err error)
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 == "" {
return func() bool { return true }, func() {}, nil
}
key := objectRouteKey(objectPath)
lock, err := lockClient.NewBlockingLongLivedLockWithin(key, owner, 15*time.Second, time.Minute)
if err != nil {
return nil, nil, fmt.Errorf("lock %s: %w", key, err)
}
return lock.IsLocked, func() {
if err := lock.Stop(); err != nil {
glog.Warningf("release lock %s: %v", key, err)
}
}, nil
}
}
// removeUploadDir mirrors the S3 gateway's abort, under the object write lock.
// A completed upload's part entries share chunks with the finished object, so
// only the metadata goes; an open upload's chunks are freed by
// routedUploadDirDelete. An undecidable lookup, or a lost lock, is left for
// the next run.
func (c *commandS3CleanUploads) removeUploadDir(filerClient filer_pb.FilerClient, writer io.Writer, bucketDir, uploadsDir string, upload *filer_pb.Entry, lockHeld func() bool) error {
completed, err := c.uploadCompleted(filerClient, bucketDir, upload)
if err != nil {
fmt.Fprintf(writer, "skip %s: %v\n", upload.Name, err)
return nil
}
var commitPath string
if !completed {
if commitPath, err = uploadCommitPath(filerClient, bucketDir, upload); err != nil {
fmt.Fprintf(writer, "skip %s: %v\n", upload.Name, err)
return nil
}
}
if !lockHeld() {
fmt.Fprintf(writer, "skip %s: lost the object write lock\n", upload.Name)
return nil
}
if !completed {
freed, err := routedUploadDirDelete(filerClient, uploadObjectPath(bucketDir, upload), commitPath, uploadsDir, upload.Name)
if err != nil {
return fmt.Errorf("purge %s/%s: %v", uploadsDir, upload.Name, err)
}
if freed {
fmt.Fprintf(writer, "purge %s/%s\n", uploadsDir, upload.Name)
return nil
}
}
fmt.Fprintf(writer, "purge %s/%s metadata only\n", uploadsDir, upload.Name)
if err := filer_pb.Remove(context.Background(), filerClient, uploadsDir, upload.Name, false, true, true, false, nil); err != nil {
return fmt.Errorf("purge %s/%s: %v", uploadsDir, upload.Name, err)
}
return nil
}
// routedUploadDirDelete frees an open upload's chunks in an ObjectTransaction
// on the object's owner filer, under the path lock a routed completion
// commits under. It deletes nothing and reports false when the object
// already carries the upload.
func routedUploadDirDelete(filerClient filer_pb.FilerClient, objectPath, commitPath, uploadsDir, uploadId string) (bool, error) {
if objectPath == "" {
return true, filer_pb.Remove(context.Background(), filerClient, uploadsDir, uploadId, true, true, true, false, nil)
}
var resp *filer_pb.ObjectTransactionResponse
err := filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
var txnErr error
resp, txnErr = client.ObjectTransaction(context.Background(), &filer_pb.ObjectTransactionRequest{
LockKey: commitPath,
RouteKey: objectRouteKey(objectPath),
ConditionKey: commitPath,
Condition: &filer_pb.WriteCondition{Clauses: []*filer_pb.WriteCondition_Clause{{
Kind: filer_pb.WriteCondition_IF_EXTENDED_NOT_EQUAL,
ExtKey: s3_constants.SeaweedFSUploadId,
ExtValue: uploadId,
}}},
Mutations: []*filer_pb.ObjectMutation{{
Type: filer_pb.ObjectMutation_DELETE,
Directory: uploadsDir,
Name: uploadId,
IsDeleteData: true,
IsRecursive: true,
}},
RequestId: uuid.NewString(),
})
return txnErr
})
if err != nil {
return false, err
}
if resp.ErrorCode == filer_pb.FilerError_PRECONDITION_FAILED {
return false, nil
}
if resp.Error != "" {
return false, errors.New(resp.Error)
}
return true, nil
}
// uploadObjectPath is the filer path of the object the upload completes into, as
// the gateway's toFilerPath derives it, or "" when the upload names none.
func uploadObjectPath(bucketDir string, upload *filer_pb.Entry) string {
objectKey := string(upload.Extended[s3_constants.ExtMultipartObjectKey])
if objectKey == "" {
return ""
}
return bucketDir + "/" + s3_constants.NormalizeObjectKey(objectKey)
}
// uploadCommitPath is the path a routed completion of the upload locks: the
// object path in a versioned bucket, else the entry it writes, which for a
// trailing-slash key lies inside the directory the key names. Like the
// gateway's, it reads the bucket's versioning state just before the delete.
func uploadCommitPath(filerClient filer_pb.FilerClient, bucketDir string, upload *filer_pb.Entry) (string, error) {
objectKey := string(upload.Extended[s3_constants.ExtMultipartObjectKey])
if objectKey == "" {
return "", nil
}
bucket, _, _, err := filer_pb.GetEntry(context.Background(), filerClient, util.FullPath(bucketDir))
if err != nil {
return "", fmt.Errorf("read bucket %s: %w", bucketDir, err)
}
if versioning, lockEnabled := getBucketVersioningState(bucket); versioning == s3_constants.VersioningEnabled || lockEnabled {
return uploadObjectPath(bucketDir, upload), nil
}
dir := path.Dir(objectKey)
if dir == "." {
dir = ""
}
return path.Join(bucketDir, dir, path.Base(objectKey)), nil
}
func objectRouteKey(objectPath string) string {
return s3_constants.ObjectWriteRouteKeyPrefix + strings.TrimSuffix(objectPath, "/")
}
// uploadCompleted reports whether the upload assembled into an object: the
// object entry, or any version file under <key>.versions, still carries the
// upload id completion stamps on it.
func (c *commandS3CleanUploads) uploadCompleted(filerClient filer_pb.FilerClient, bucketDir string, upload *filer_pb.Entry) (bool, error) {
objectKey := string(upload.Extended[s3_constants.ExtMultipartObjectKey])
if objectKey == "" {
return false, nil
}
// Derive the object location the same way completion's getEntryNameAndDir
// does: a trailing-slash key stores the object inside the directory it
// names, so FullPath+DirAndName would look one level too high.
name := path.Base(objectKey)
dir := path.Dir(objectKey)
if dir == "." {
dir = ""
}
objectDir := util.FullPath(path.Join(bucketDir, dir))
completed := false
err := filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
resp, err := filer_pb.LookupEntry(context.Background(), client, &filer_pb.LookupDirectoryEntryRequest{Directory: string(objectDir), Name: name})
if errors.Is(err, filer_pb.ErrNotFound) {
return nil
}
if err != nil {
return err
}
if resp.Entry != nil && string(resp.Entry.Extended[s3_constants.SeaweedFSUploadId]) == upload.Name {
completed = true
}
return nil
})
if err != nil || completed {
return completed, err
}
err = filer_pb.List(context.Background(), filerClient, string(objectDir)+"/"+name+s3_constants.VersionsFolder, "", func(entry *filer_pb.Entry, isLast bool) error {
if string(entry.Extended[s3_constants.SeaweedFSUploadId]) == upload.Name {
completed = true
}
return nil
}, "", false, math.MaxUint32)
if err != nil && (errors.Is(err, filer_pb.ErrNotFound) || strings.Contains(err.Error(), filer_pb.ErrNotFound.Error())) {
return false, nil
}
return completed, err
}