Files
seaweedfs/weed/server/filer_grpc_scope_rules.go
T
430ca2b585 filer: path- and method-scoped gRPC tokens (scope enforcement, fail closed) (#12904)
* filer: path- and method-scoped tokens on the filesystem gRPC service

* filer: close scoped admission and compatibility gaps

* filer: test subscription key ambiguity and retained write success

* filer: assert verified peer chains survive subscription fallback

* filer: keep a hard link's count and chunks together under a scoped token

A scoped write may keep a hard link the target already has, but the link
count it sends was stored as is, and its chunks could stay on the name
with the link dropped. Either let a scoped token delete its own name and
take the chunks of a name outside its grants with it: the forged count
reaches zero, or the detached name owns the shared chunks.

The handler recheck now refuses a scoped write that changes a stored
link's count or keeps its chunks without the link. Dropping the link
together with the data, and appending to a linked file, are unchanged.

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

* filer: leave subscriptions with a non-scope bearer to the existing verifier

The stream interceptor refused a SubscribeMetadata or SubscribeLocalMetadata
call whose bearer does not verify under the filer key unless the bearer was
a subscription token, and it checked that token with the peer stripped. With
no subscription key, or on an mTLS peer, the existing verifier admits such a
call, so filer.sync sending another cluster's admin token stopped.

When the bearer is no filer scope, the subscription verifier now decides on
the original context, as before scoped tokens. A scoped token still reaches
the refusal for scoped subscriptions, and malformed metadata is still refused.

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

* filer: refuse scoped writes that would make ancestors outside the grant

A scoped create, append or rename checked only its target. The filer then
creates the target's missing ancestors up to the first one it finds, and
turns that one into a directory if it is a file, dropping its ttl. A token
granted /data/proj/ws could so promote the file /data/proj, or create /q and
/q/r for a grant /q/r/ws.

The scope now walks the same ancestors before admitting the write and
refuses one outside the write grants that is missing or not a directory. A
create with skip_check_parent_directory makes no ancestors and is not
walked.

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

* filer: require write grants for scoped lock mutations

* filer: document scoped signatures and read-only token upgrades

* filer: enforce WORM retention for scoped mutations

* filer: refuse scoped writes through shared hard links

* filer: drop series notes from scope comments

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

* filer: refuse scoped subtree mutations across WORM rules

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 08:45:34 -08:00

167 lines
6.0 KiB
Go

package weed_server
// Rules applied to a scoped filer token on the filesystem gRPC service: which
// paths the token may use, and which chunk file ids and hard-link ids an entry
// it sends may reference. See filer_grpc_scope.go for how they are applied.
import (
"errors"
"fmt"
"path"
"reflect"
"strings"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
)
// scopeGrant is one path prefix a token may use, read-only or read-write.
type scopeGrant struct {
path string
readWrite bool
}
// scopeGrantsFromClaims turns the token's prefix lists into grants. Every
// prefix must be a clean absolute path: the filer stores the directory string
// it receives without cleaning, so an unclean grant could never match a stored
// path exactly and would only invite confusion about what it covers.
func scopeGrantsFromClaims(allowedPrefixes, readPrefixes []string) ([]scopeGrant, error) {
grants := make([]scopeGrant, 0, len(allowedPrefixes)+len(readPrefixes))
add := func(p string, readWrite bool) error {
if p == "" || p[0] != '/' || path.Clean(p) != p {
return fmt.Errorf("prefix %q is not a clean absolute path", p)
}
grants = append(grants, scopeGrant{path: p, readWrite: readWrite})
return nil
}
for _, p := range allowedPrefixes {
if err := add(p, true); err != nil {
return nil, err
}
}
for _, p := range readPrefixes {
if err := add(p, false); err != nil {
return nil, err
}
}
return grants, nil
}
var errScopePathNotCanonical = errors.New("path is not canonical")
// scopeFullPath joins a filer directory and entry name as the rules check
// them. The directory must be absolute and already clean, the name one clean
// segment or empty (the directory itself). Anything else is refused rather
// than normalised, because the filer would store it as received.
func scopeFullPath(dir, name string) (string, error) {
if dir == "" || dir[0] != '/' || path.Clean(dir) != dir {
return "", fmt.Errorf("%w: directory %q", errScopePathNotCanonical, dir)
}
switch {
case name == "":
return dir, nil
case name == "." || name == ".." || strings.Contains(name, "/"):
return "", fmt.Errorf("%w: name %q", errScopePathNotCanonical, name)
}
if dir == "/" {
return "/" + name, nil
}
return dir + "/" + name, nil
}
// scopePathAllowed reports whether the canonical path p equals a grant or lies
// under it; a mutation needs a read-write grant covering p.
func scopePathAllowed(grants []scopeGrant, p string, write bool) bool {
if p == "" || p[0] != '/' {
return false
}
for _, g := range grants {
under := g.path == "/" || p == g.path || strings.HasPrefix(p, g.path+"/")
if !under {
continue
}
if write && !g.readWrite {
continue
}
return true
}
return false
}
func scopeSplitPath(p string) (dir, name string) {
i := strings.LastIndex(p, "/")
if i <= 0 {
return "/", strings.TrimPrefix(p, "/")
}
return p[:i], p[i+1:]
}
// scopeProtectedPath reports whether a mutation can change the filer's shared
// storage configuration. Entry writes cannot replace or promote filer.conf to
// a directory; a rename or delete also cannot move or remove an ancestor.
func scopeProtectedPath(p string, descendants bool) bool {
config := scopeFilerConfDir + "/" + scopeFilerConfName
return p == config || strings.HasPrefix(p, config+"/") ||
(descendants && (p == "/" || strings.HasPrefix(config, p+"/")))
}
// scopeCheckEntryShape refuses indirect or missing chunk identities. Manifests
// contain additional file ids that cannot be checked against the target entry.
func scopeCheckEntryShape(e *filer_pb.Entry) error {
if e == nil {
return errors.New("an entry is required")
}
if e.RemoteEntry != nil {
return errors.New("remote entries are not allowed")
}
for _, c := range e.GetChunks() {
if c == nil {
return errors.New("nil chunks are not allowed")
}
if c.GetSourceFileId() != "" || c.GetSourceFid() != nil {
return fmt.Errorf("chunk %s: source file ids are not allowed", c.GetFileIdString())
}
if c.GetFileIdString() == "" {
return errors.New("chunk without a file id")
}
if c.GetIsChunkManifest() {
return fmt.Errorf("chunk %s: manifest chunks are not allowed", c.GetFileIdString())
}
}
return nil
}
// scopeHardLinkMarker terminates every id filer.NewHardLinkId produces (16
// random bytes plus the marker), the only shape a client may introduce as a
// new id.
const scopeHardLinkMarker = '\x01'
func scopeLooksLikeNewHardLinkId(id []byte) bool {
return len(id) == 17 && id[16] == scopeHardLinkMarker
}
// scopeUnaryMethods binds each admitted RPC name to its request type. The path
// rules in unaryScoped are selected by that type; a new RPC reusing a request
// type cannot inherit permission accidentally. All absent methods are refused.
var scopeUnaryMethods = map[string]reflect.Type{
"LookupDirectoryEntry": reflect.TypeOf((*filer_pb.LookupDirectoryEntryRequest)(nil)),
"LookupDirectoryEntries": reflect.TypeOf((*filer_pb.LookupDirectoryEntriesRequest)(nil)),
"TouchAccessTime": reflect.TypeOf((*filer_pb.TouchAccessTimeRequest)(nil)),
"CreateEntry": reflect.TypeOf((*filer_pb.CreateEntryRequest)(nil)),
"UpdateEntry": reflect.TypeOf((*filer_pb.UpdateEntryRequest)(nil)),
"AppendToEntry": reflect.TypeOf((*filer_pb.AppendToEntryRequest)(nil)),
"DeleteEntry": reflect.TypeOf((*filer_pb.DeleteEntryRequest)(nil)),
"AtomicRenameEntry": reflect.TypeOf((*filer_pb.AtomicRenameEntryRequest)(nil)),
"PosixLock": reflect.TypeOf((*filer_pb.PosixLockRequest)(nil)),
"Ping": reflect.TypeOf((*filer_pb.PingRequest)(nil)),
"LookupVolume": reflect.TypeOf((*filer_pb.LookupVolumeRequest)(nil)),
"GetFilerConfiguration": reflect.TypeOf((*filer_pb.GetFilerConfigurationRequest)(nil)),
"Statistics": reflect.TypeOf((*filer_pb.StatisticsRequest)(nil)),
}
// Each admitted stream has a request/response rule in the stream interceptor.
var scopeStreamMethods = map[string]bool{
"ListEntries": true,
"StreamRenameEntry": true,
"StreamMutateEntry": true,
}