Files
seaweedfs/weed/s3api/s3api_directory_marker.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

192 lines
8.7 KiB
Go

package s3api
import (
"errors"
"net/http"
"strings"
"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/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
"github.com/seaweedfs/seaweedfs/weed/security"
"github.com/seaweedfs/seaweedfs/weed/util"
)
// An explicit directory marker - the key "dir/" created by PutObject on a
// trailing-slash key - is stored as the filer directory itself rather than as an
// object beside it. That makes it a poor fit for versioning: a delete marker would
// have to replace an entry that other keys live under, and the history would have to
// sit inside the directory it describes, where a listing keeps meeting it.
//
// So the key is not versioned. Deleting it does what deleting it in an unversioned
// bucket already does: the directory is removed when nothing is left under it, and
// demoted to a plain directory when children remain. Listings need no version lookup
// to tell what a directory stands for, and a bucket made of directory markers costs
// the same to list versioned as unversioned.
// deleteDirectoryMarker removes the key "<dir>/". Callers hold the object write lock,
// so the entry this decides about cannot change between the read and the delete.
func (s3a *S3ApiServer) deleteDirectoryMarker(r *http.Request, bucket, object string) s3err.ErrorCode {
governanceBypassAllowed := s3a.evaluateGovernanceBypassRequest(r, bucket, object)
trimmedObject := strings.TrimSuffix(strings.TrimPrefix(object, "/"), "/")
markerDir := s3a.bucketDir(bucket) + "/" + trimmedObject
entry, err := s3a.getObjectEntryRoutedByKey(bucket, trimmedObject)
switch {
case errors.Is(err, filer_pb.ErrNotFound):
case err != nil:
// The entry may be a file a child write promoted to a directory, whose data
// belongs to the key without the trailing slash. Deleting without knowing
// would destroy it, so fail and leave the retry to the client.
glog.Errorf("deleteDirectoryMarker: cannot read %s/%s: %v", bucket, object, err)
return s3err.ErrInternalError
default:
if remove, code := s3a.checkDirectoryMarker(entry, bucket, object, governanceBypassAllowed); !remove {
return code
}
}
found := err == nil
// During a ring change the key's prior owner may hold an entry the new owner
// has not received yet, so it is checked and deleted on that filer as well.
owner := s3a.routableWriteOwner(bucket, trimmedObject)
dir, name := util.FullPath(markerDir).DirAndName()
var priorOwner pb.ServerAddress
if prior := s3a.priorWriteOwner(bucket, trimmedObject); prior != "" && prior != owner {
probeCtx, cancel := s3a.routedProbeContext(prior)
priorEntry, priorErr := s3a.lookupEntryOnFiler(probeCtx, prior, dir, name)
cancel()
switch {
case errors.Is(priorErr, filer_pb.ErrNotFound):
case priorErr != nil:
glog.Errorf("deleteDirectoryMarker: cannot read %s/%s on prior owner %s: %v", bucket, object, prior, priorErr)
return s3err.ErrInternalError
default:
remove, code := s3a.checkDirectoryMarker(priorEntry, bucket, object, governanceBypassAllowed)
if code != s3err.ErrNone {
return code
}
if remove {
priorOwner = prior
}
}
}
if !found && priorOwner == "" {
return s3err.ErrNone // deleting a key that is not there is a success
}
// Drop a history an older build recorded for this key. Nothing writes one now, and
// leaving it behind keeps reporting the key in ListObjectVersions, so a history we
// cannot read or remove fails the delete rather than half finishing it.
switch _, historyErr := s3a.getObjectScopedEntryRoutedByKey(bucket, trimmedObject, markerDir, s3_constants.VersionsFolder); {
case historyErr == nil:
// The removal below takes every entry under the key, so each has to be clear
// of a lock of its own.
versionsDir := markerDir + "/" + s3_constants.VersionsFolder
for startFrom := ""; ; {
entries, isLast, listErr := s3a.listObjectScopedEntriesRoutedByKey(bucket, trimmedObject, versionsDir, "", startFrom, false, 1000)
if listErr != nil {
glog.Errorf("deleteDirectoryMarker: cannot list history of %s/%s: %v", bucket, object, listErr)
return s3err.ErrInternalError
}
for _, entry := range entries {
startFrom = entry.Name
versionId, named := entry.Extended[s3_constants.ExtVersionIdKey]
if !named {
// An entry an older build left without a version id is what this
// removal is here to clear, but one still under a lock cannot be
// named to check it, so judge it on what it carries itself.
if err := s3a.enforceObjectLockOnEntry(entry, bucket, object, "", governanceBypassAllowed); err != nil {
glog.V(2).Infof("deleteDirectoryMarker: unnamed history entry %s of %s/%s is locked: %v", entry.Name, bucket, object, err)
return s3err.ErrAccessDenied
}
continue
}
if err := s3a.enforceObjectLockProtections(r, bucket, object, string(versionId), governanceBypassAllowed); err != nil {
glog.V(2).Infof("deleteDirectoryMarker: version %s of %s/%s is locked: %v", versionId, bucket, object, err)
return s3err.ErrAccessDenied
}
}
if isLast || len(entries) == 0 {
break
}
}
if rmErr := s3a.rm(r.Context(), markerDir, s3_constants.VersionsFolder, true, true); rmErr != nil {
glog.Errorf("deleteDirectoryMarker: failed to remove stale history of %s/%s: %v", bucket, object, rmErr)
return s3err.ErrInternalError
}
case !errors.Is(historyErr, filer_pb.ErrNotFound):
glog.Errorf("deleteDirectoryMarker: cannot read stale history of %s/%s: %v", bucket, object, historyErr)
return s3err.ErrInternalError
}
// Each delete checks the entry of the filer it runs on, which a failover can
// make another filer than the one read above. A nonempty marker is demoted by
// a read and an update that must find it there too. A filer that misses is
// not sent the delete: it would pass it on to the key's write owner, which
// applies it without these checks.
refused := s3err.ErrNone
missed := false
deleteMarker := func(client filer_pb.SeaweedFilerClient) error {
resp, lookupErr := filer_pb.LookupEntry(r.Context(), client, &filer_pb.LookupDirectoryEntryRequest{Directory: dir, Name: name})
switch {
case errors.Is(lookupErr, filer_pb.ErrNotFound):
missed = true
return nil
case lookupErr != nil:
return lookupErr
}
if remove, code := s3a.checkDirectoryMarker(resp.Entry, bucket, object, governanceBypassAllowed); !remove {
refused = code
return nil
}
return s3a.deleteUnversionedObjectWithClient(r.Context(), client, bucket, object, false)
}
if err := s3a.withWriteOwnerFilerClient(owner, deleteMarker); err != nil {
glog.Errorf("deleteDirectoryMarker: failed to delete %s/%s: %v", bucket, object, err)
return s3err.ErrInternalError
}
if refused != s3err.ErrNone {
return refused
}
if priorOwner == "" {
if missed {
// The entry read above is on a filer this delete did not reach.
glog.Errorf("deleteDirectoryMarker: %s/%s is not on the filer the delete reached", bucket, object)
return s3err.ErrInternalError
}
return s3err.ErrNone
}
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
}
return refused
}
// checkDirectoryMarker reports whether entry is a "<dir>/" marker the delete may
// remove, and otherwise the code the delete answers with.
func (s3a *S3ApiServer) checkDirectoryMarker(entry *filer_pb.Entry, bucket, object string, governanceBypassAllowed bool) (bool, s3err.ErrorCode) {
switch {
case s3a.isVersionFileKey(strings.TrimSuffix(strings.TrimPrefix(object, "/"), "/"), entry.Extended):
return false, s3err.ErrAccessDenied
case !entry.IsDirectory || entry.IsPrefixObject() || len(entry.GetChunks()) > 0 || entry.IsInRemoteOnly():
// The object "dir", or a file promoted to a directory: "dir/" does not name its data.
glog.V(2).Infof("deleteDirectoryMarker: %s/%s holds uploaded data, leaving it alone", bucket, object)
return false, s3err.ErrNone
}
// The key is deleted the unversioned way, but Object Lock still covers it: the
// gateway lists it as an object and serves retention set on it. The lock that
// matters is the one on this entry, since that is what is removed -- looking the
// key up instead would answer with a version once the key has a history.
if err := s3a.enforceObjectLockOnEntry(entry, bucket, object, "", governanceBypassAllowed); err != nil {
glog.V(2).Infof("deleteDirectoryMarker: %s/%s is locked: %v", bucket, object, err)
return false, s3err.ErrAccessDenied
}
return true, s3err.ErrNone
}