Files
seaweedfs/weed/server/filer_server_handlers_proxy.go
T
Chris Lu a0b1272cc3 filer: authorize the chunk proxy and the root listing like the rest of the filer port (#11152)
* filer: require a read token for the root listing

maybeCheckJwtAuthorization waved through every GET/HEAD on "/", so a filer
with jwt.filer_signing.read.key set still served its root directory listing --
entry names, sizes and chunks[].file_id -- to a caller holding no token at
all, and served the same listing to a token restricted by allowed_prefixes.

The exemption was added for health checks before the filer had /healthz and
/readyz. Both are registered on the default and read-only muxes ahead of the
"/" handler and answer without a token, so drop it.

Point the mTLS harness at /healthz, which is what it was probing for.

* filer: keep the jwt query parameter out of a proxied chunk request

The proxy stripped "jwt" from the forwarded query on reads only, on the
grounds that a writer's own credential travels there. It does not: an
uploader carries its AssignVolume token in the Authorization header, and the
query parameter on this path holds a filer credential.

Strip it for every method. A volume server has no business seeing a filer
token, and because security.GetJwt reads the query before the header,
relaying one would hide the writer's own token behind it.

* filer: dispatch the chunk proxy after the JWT gate

The ?proxyChunkId= branch returned before maybeCheckJwtAuthorization ran, so
GET, PUT, POST and DELETE against any needle in the cluster were reachable on
the filer's HTTP port with no filer credential, on a filer where every other
request answered 401. An anonymous caller read a stored object, replaced its
bytes, or deleted the needle, which the master's next vacuum makes permanent.

#10434 stopped the filer from minting a volume write token for that caller,
which closes the write half only where the volume server has a jwt.signing.key
of its own -- not the shipped default, and not what scaffold/security.toml
recommends for a filer deployment. The read half stayed open in every
configuration, because the filer mints the read token itself.

Move the dispatch below the gate. A file id carries no path, so a token
restricted by allowed_prefixes cannot be scoped against one and is refused
here; every consumer of this endpoint holds an unrestricted token.

* filer: mint the volume credential for a proxied write too

The proxy minted a volume token on reads and forwarded whatever the caller
sent on writes. #10434 made it that way because the branch ran ahead of the
JWT gate, so a token minted here would have been signed for an unauthenticated
caller; the branch now runs behind the gate, and the credential the caller
presents there is a filer one, which a volume server cannot validate and has
no business seeing.

Mint at the access level the request needs, and drop the caller's
Authorization when there is no key to mint from. A proxied uploader then needs
only the filer credential, instead of holding one for each hop with a single
header to put them in.

* mount, mq, filer.sync: send the filer credential for a proxied chunk

Every in-tree consumer of ?proxyChunkId= reached the filer anonymously: mount
and the broker put the AssignVolume token in the Authorization header, which
is a volume credential, and filer.sync sent nothing at all. That was enough
only while the branch ran ahead of the filer's JWT gate.

Build the URL through one helper, and pick the credential from the URL it
returns: a chunk proxied through a filer is a request to the filer, which
authorizes it and attaches the volume credential itself, so the token there is
a filer one at the access level the request needs.

* filer: honor -exposeDirectoryData

The flag was declared on all three commands that start a filer and read by
none of them: FilerOption.ExposeDirectoryData was only ever assigned from
filer.expose_directory_metadata in security.toml, so -exposeDirectoryData=false
silently left the listing exposed. Only the TOML key had any effect.

Plumb the flag through and let either switch turn the listing off.

* filer: count a proxied chunk request once

Moving the dispatch below the gate put it after the deferred request
observation, so every proxied chunk now landed in FilerRequestHistogram twice,
once under its HTTP method and once under chunkProxy. Name the deferred one
after the proxy instead, the way the unsupported-method branch already does,
which also gives the endpoint the status codes FilerRequestCounter records.
2026-09-04 16:39:36 -07:00

204 lines
6.8 KiB
Go

package weed_server
import (
"context"
"sync"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/security"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
"github.com/seaweedfs/seaweedfs/weed/util/mem"
"github.com/seaweedfs/seaweedfs/weed/util/request_id"
"io"
"math/rand/v2"
"net/http"
"strings"
)
// proxyReadConcurrencyPerVolumeServer limits how many concurrent proxy read
// requests the filer will issue to any single volume server. Without this,
// replication bursts can open hundreds of connections to one volume server,
// causing it to drop connections with "unexpected EOF".
const proxyReadConcurrencyPerVolumeServer = 16
var (
proxySemaphores sync.Map // host -> chan struct{}
)
func acquireProxySemaphore(ctx context.Context, host string) error {
v, _ := proxySemaphores.LoadOrStore(host, make(chan struct{}, proxyReadConcurrencyPerVolumeServer))
sem := v.(chan struct{})
select {
case sem <- struct{}{}:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func releaseProxySemaphore(host string) {
v, ok := proxySemaphores.Load(host)
if !ok {
return
}
select {
case <-v.(chan struct{}):
default:
glog.Warningf("proxy semaphore for %s was already empty on release", host)
}
}
// isProxyReadMethod reports whether a proxied request only reads. Everything
// else is treated as a write for both credential and concurrency purposes.
func isProxyReadMethod(method string) bool {
return method == http.MethodGet || method == http.MethodHead
}
// baseFileId strips the trailing _N delta suffix that batch assigns append to a
// fid, and only that: the suffix must be a non-empty run of digits, otherwise
// the fid is returned whole for the caller to reject. The volume server compares
// a JWT's fid claim against the stripped form (see
// VolumeServer.maybeCheckJwtAuthorization), so anything minting or parsing a fid
// on this side has to agree with it.
//
// That server strips at the last "_" unconditionally, which is safe there
// because its fid already came out of a path the mux parsed and so cannot hold
// a "/". Here the value is raw query input, and an unguarded strip would reduce
// "3,01637037d6_1/../../status" to a valid fid and wave the traversal through.
func baseFileId(fileId string) string {
sepIndex := strings.LastIndex(fileId, "_")
if sepIndex <= 0 {
return fileId
}
delta := fileId[sepIndex+1:]
if delta == "" {
return fileId
}
for _, c := range delta {
if c < '0' || c > '9' {
return fileId
}
}
return fileId[:sepIndex]
}
// validateProxyChunkId rejects a proxyChunkId that is not a well-formed fid.
// LookupFileId only requires a single comma, and the value is pasted into the
// volume server URL path, so "3,x/../../status" resolves to a volume the caller
// never named -- the volume server's mux cleans the dot segments and redirects
// to /status, which the filer follows and relays.
func validateProxyChunkId(fileId string) error {
_, err := needle.ParseFileIdFromString(baseFileId(fileId))
return err
}
func (fs *FilerServer) proxyToVolumeServer(w http.ResponseWriter, r *http.Request, fileId string) {
ctx := r.Context()
if err := validateProxyChunkId(fileId); err != nil {
glog.V(1).InfofCtx(ctx, "reject proxyChunkId %q: %v", fileId, err)
w.WriteHeader(http.StatusBadRequest)
return
}
urlStrings, err := fs.filer.MasterClient.GetLookupFileIdFunction()(ctx, fileId)
if err != nil {
glog.ErrorfCtx(ctx, "locate %s: %v", fileId, err)
w.WriteHeader(http.StatusInternalServerError)
return
}
if len(urlStrings) == 0 {
w.WriteHeader(http.StatusNotFound)
return
}
fs.proxyToVolumeServerURL(w, r, fileId, urlStrings[rand.IntN(len(urlStrings))])
}
// proxyToVolumeServerURL forwards the request to one already-resolved volume
// server URL.
func (fs *FilerServer) proxyToVolumeServerURL(w http.ResponseWriter, r *http.Request, fileId, targetURL string) {
ctx := r.Context()
// targetURL from LookupFileId already contains the fileId in the path
// (e.g. http://server:8080/6,08136bdce4). Forward the caller's query params
// (e.g. readDeleted=true from weed mount) but drop the internal proxyChunkId.
query := r.URL.Query()
query.Del(util_http.ProxyChunkIdParam)
// "jwt" here is the filer credential that got the caller past the gate, and
// a volume server has no business seeing one. security.GetJwt reads that
// parameter before the Authorization header, so relaying it would also
// hide the volume credential the filer attaches below.
query.Del("jwt")
if encoded := query.Encode(); encoded != "" {
targetURL += "?" + encoded
}
proxyReq, err := http.NewRequest(r.Method, targetURL, r.Body)
if err != nil {
glog.ErrorfCtx(ctx, "NewRequest %s: %v", targetURL, err)
w.WriteHeader(http.StatusInternalServerError)
return
}
// Limit concurrent reads per volume server to prevent overload. Writes are
// deliberately exempt: the bursts this exists to contain are replication
// reads, and an upload queued behind them stalls a caller that is holding a
// volume assignment open.
if isProxyReadMethod(r.Method) {
volumeHost := proxyReq.URL.Host
if err := acquireProxySemaphore(ctx, volumeHost); err != nil {
glog.V(0).InfofCtx(ctx, "proxy to %s cancelled while waiting: %v", volumeHost, err)
w.WriteHeader(http.StatusServiceUnavailable)
return
}
defer releaseProxySemaphore(volumeHost)
}
proxyReq.Header.Set("Host", r.Host)
proxyReq.Header.Set("X-Forwarded-For", r.RemoteAddr)
request_id.InjectToRequest(ctx, proxyReq)
for header, values := range r.Header {
for _, value := range values {
proxyReq.Header.Add(header, value)
}
}
// Decide the volume credential explicitly rather than letting the copied
// header stand. The caller's Authorization is the filer credential that got
// them past the gate: a volume server has no business seeing one, and it
// would not honour it anyway. Mint the credential the volume server does
// ask for, at the access level this request needs, and drop the caller's
// when there is nothing to mint.
if jwt := fs.maybeGetVolumeJwtAuthorizationToken(fileId, !isProxyReadMethod(r.Method)); jwt != "" {
proxyReq.Header.Set("Authorization", security.BearerPrefix+jwt)
} else {
proxyReq.Header.Del("Authorization")
}
proxyResponse, postErr := util_http.GetGlobalHttpClient().Do(proxyReq)
if postErr != nil {
glog.ErrorfCtx(ctx, "post to filer: %v", postErr)
w.WriteHeader(http.StatusInternalServerError)
return
}
defer util_http.CloseResponse(proxyResponse)
for k, v := range proxyResponse.Header {
w.Header()[k] = v
}
w.WriteHeader(proxyResponse.StatusCode)
buf := mem.Allocate(128 * 1024)
defer mem.Free(buf)
if _, copyErr := io.CopyBuffer(w, proxyResponse.Body, buf); copyErr != nil {
glog.V(0).InfofCtx(ctx, "proxy copy %s: %v", fileId, copyErr)
}
}