Files
seaweedfs/weed/s3api/auth_revoked_requests.go
T
8abfdf1e21 s3: abort in-flight requests whose access is revoked (#12986)
* s3: abort in-flight requests whose access is revoked

S3 checks access when a request starts, so a download or upload that
started before an identity, policy or bucket policy change runs to its
end. With -s3.abortRevokedRequests the gateway re-checks the requests it
is serving after such a change and aborts the ones now denied: an
HTTP/1.x request has its connection closed, an HTTP/2 request is
canceled.

The re-check looks the identity up again and repeats only authorization,
not the signature check, so clock skew or an expiring presigned URL never
cuts a long transfer. Off by default.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* s3: check revoked requests against whole reloads and configured identities

- A re-check pass holds reloadMu, so it never sees identities installed
  before their policies are synced.
- STS and JWT sessions are not tracked: re-validating their token checks
  its expiry, which a re-check cannot tell from a revocation.
- A request whose access changed while it was being admitted is checked
  again once it is tracked.
- The identity source comes from how the request authenticated, and a
  rotated secret revokes the requests signed with the old one.
- An aborted HTTP/2 request also has its body closed.
- Browser form uploads, which their handler authorizes, are not tracked.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* s3: track SigV2 requests that carry a session token

SigV2 never reads a session token, so a configured key that sent one was
classified as a session and skipped the re-checks. Only SigV4 resolves a
token, and it marks one it tolerated for a configured key ignored.

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

* s3: let the admission-race test pass only through the generation check

The re-check that the change schedules could run after the request was
tracked and abort it, so the test passed without the generation check.
Wait for that pass to take its snapshot before the request starts.

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

* s3: drop the executable bit from the revocation test file

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

* s3: bump the re-check generation before its scope can be taken

scheduleRevalidation released t.mu before bumping the generation. A
pass already kicked could take the new scope in between, before a
request was tracked, and that request then saw the old generation and
was never checked again.

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

* s3: judge a re-checked request as of when it was admitted

A re-check evaluated aws:CurrentTime and a key's expiration at the time of
the pass, so an unrelated change aborted a transfer whose time-bounded
grant expired after it started. The re-check's copy of the request now
carries its admission time, which RequestConditionValues uses for
aws:CurrentTime and aws:RequestTime, and a key's expiration is compared
with it too.

A test covers a revoked HTTP/2 upload: closing its body releases the
blocked read, and a download on another stream of the same connection
runs to its end.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* stats: let http.ResponseController reach the writer under StatusRecorder

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

* s3: reset a revoked HTTP/2 request's stream

A deadline in the past resets only that stream, so a download blocked
writing to a client that stopped reading is released too.

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

* s3: keep in-flight requests when their key's secret is rotated

A new secret for the same access key is a rotation, not a revocation.
Removing or deactivating the key, or losing the grant, still aborts.

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

* s3: always abort in-flight requests whose access is revoked

Drop -s3.abortRevokedRequests: the gateway tracks the requests it admits
and re-checks them on every change that can revoke access, so a revoked
client's transfers stop without a restart.

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

* s3: a catch-up re-check does not advance the revocation generation

A request tracked after an access change scheduled its bucket's re-check
through the same path as the change, which advanced the generation again.
A request that began authenticating before that advance then scheduled
another bucket-wide re-check, so overlapping admissions could keep the
re-check loop busy, holding reloadMu, with no access change.

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

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 17:27:04 -08:00

299 lines
9.2 KiB
Go

package s3api
import (
"context"
"io"
"net"
"net/http"
"sync"
"sync/atomic"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/s3api/policy_engine"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
"github.com/seaweedfs/seaweedfs/weed/util"
)
// inFlightRequests holds the requests the S3 auth middleware admitted for a
// configured identity, so a change to identities, policies or a bucket policy
// that revokes their access aborts them, rather than letting a download or
// upload that started before the change run to its end.
//
// Only the middleware's decision is checked again, and as of when the request
// was admitted: time conditions such as aws:CurrentTime, and a key's
// expiration, are evaluated at that time, so expiry alone never aborts a
// request. STS and JWT sessions are not tracked, so their requests run to
// their end: re-validating a session token also checks its expiry. Nor is what a handler authorizes itself: anonymous reads a
// public ACL or bucket policy allows, browser form uploads, the source of a
// copy, and conditions on object tags.
type inFlightRequests struct {
mu sync.Mutex
requests map[*inFlightRequest]struct{}
// Re-checks waiting for revalidateLoop: of every request, or of those on
// these buckets.
all bool
buckets map[string]struct{}
kick chan struct{}
// generation counts scheduled re-checks, so a request whose access changed
// while it was being admitted is checked again once it is tracked.
generation atomic.Uint64
}
// identitySource is how a re-check finds a request's identity again.
type identitySource int
const (
// A session (JWT, STS), which is not tracked.
fromSession identitySource = iota
// Signed with a configured access key.
fromAccessKey
// No signature or token: anonymous, or a client certificate.
fromUnsigned
// A configured identity whose signing key the request did not record.
fromName
)
type inFlightRequest struct {
// req is a copy taken before the handler ran, which may change the
// original, and judged as of admitted. Only revalidateLoop uses it.
req *http.Request
admitted time.Time
identity *Identity
action Action
bucket string
source identitySource
// The key the request was signed with. Removing or deactivating it revokes
// the request; giving it a new secret is a rotation, which does not.
accessKey string
cancel context.CancelFunc
// An HTTP/1.x request is aborted by closing its connection. An HTTP/2
// connection carries other streams, so such a request has its context
// canceled, its body closed and its stream reset instead.
conn net.Conn
body io.Closer
stream *http.ResponseController
}
func newInFlightRequests() *inFlightRequests {
return &inFlightRequests{
requests: make(map[*inFlightRequest]struct{}),
kick: make(chan struct{}, 1),
}
}
// inFlightGeneration is taken before a request authenticates and handed to
// abortWhenRevoked.
func (iam *IdentityAccessManagement) inFlightGeneration() uint64 {
if iam.inFlight == nil {
return 0
}
return iam.inFlight.generation.Load()
}
// abortWhenRevoked wraps the handler of an authorized request, so the request
// is checked again whenever its access may have changed, and aborted once it
// is denied. since is the generation from before the request authenticated.
func (iam *IdentityAccessManagement) abortWhenRevoked(f http.HandlerFunc, identity *Identity, action Action, since uint64) http.HandlerFunc {
tracked := iam.inFlight
if tracked == nil || identity == nil {
return f
}
return func(w http.ResponseWriter, r *http.Request) {
source, cred := iam.identitySource(r, identity)
if source == fromSession {
f(w, r)
return
}
ctx, cancel := context.WithCancel(r.Context())
defer cancel()
r = r.WithContext(ctx)
bucket, _ := s3_constants.GetBucketAndObject(r)
admitted := time.Now()
req := &inFlightRequest{req: r.Clone(policy_engine.WithRequestTime(ctx, admitted)), admitted: admitted, identity: identity, action: action, bucket: bucket, source: source, cancel: cancel}
if cred != nil {
req.accessKey = cred.AccessKey
}
if r.ProtoMajor == 1 {
req.conn = util.ConnFromContext(ctx)
} else {
req.body = r.Body
req.stream = http.NewResponseController(w)
}
tracked.add(req)
defer tracked.remove(req)
if tracked.generation.Load() != since {
iam.scheduleRevalidation(bucket, false)
}
f(w, r)
}
}
// identitySource tells from how the request authenticated how a re-check finds
// its identity again, and the credential it was signed with.
func (iam *IdentityAccessManagement) identitySource(r *http.Request, identity *Identity) (identitySource, *Credential) {
switch r.Header.Get(s3_constants.AmzAuthType) {
case "Anonymous", "Certificate":
return fromUnsigned, nil
case "Jwt":
return fromSession, nil
case "SigV4":
// SigV4 marks a token it tolerated for a configured key ignored; SigV2
// never reads one, so a token there does not make a session.
if extractSessionToken(r) != "" {
return fromSession, nil
}
}
key := s3_constants.GetAccessKeyIdFromContext(r)
iam.m.RLock()
defer iam.m.RUnlock()
for _, cred := range identity.Credentials {
if key != "" && cred.AccessKey == key {
return fromAccessKey, cred
}
}
return fromName, nil
}
// currentIdentity returns the request's identity as the configuration has it
// now, or nil when it no longer authenticates the request.
func (iam *IdentityAccessManagement) currentIdentity(req *inFlightRequest) *Identity {
var identity *Identity
switch req.source {
case fromAccessKey:
var cred *Credential
var found bool
if identity, cred, found = iam.lookupByAccessKey(req.accessKey); !found || cred.Expiration > 0 && cred.Expiration < req.admitted.Unix() {
return nil
}
case fromUnsigned:
identity, _, _ = iam.authenticateUnsigned(req.req)
default:
if identity = iam.lookupByIdentityName(req.identity.Name); identity != nil && identity.Disabled {
return nil
}
}
if identity == nil || identity.Name != req.identity.Name {
return nil
}
return identity
}
// revalidateInFlight schedules a re-check of every request in flight.
func (iam *IdentityAccessManagement) revalidateInFlight() {
iam.scheduleRevalidation("", true)
}
// revalidateBucketInFlight schedules a re-check of the requests on bucket.
func (iam *IdentityAccessManagement) revalidateBucketInFlight(bucket string) {
if bucket != "" {
iam.scheduleRevalidation(bucket, true)
}
}
// scheduleRevalidation re-checks the requests on bucket, or all of them. Only
// an access change advances the generation: a catch-up for a request tracked
// late must not, or overlapping admissions would keep scheduling each other.
func (iam *IdentityAccessManagement) scheduleRevalidation(bucket string, changed bool) {
if iam == nil || iam.inFlight == nil {
return
}
t := iam.inFlight
t.mu.Lock()
if bucket == "" {
t.all = true
} else {
if t.buckets == nil {
t.buckets = make(map[string]struct{})
}
t.buckets[bucket] = struct{}{}
}
// Bumped before pending can take this scope, so a request tracked after
// that pass sees the change.
if changed {
t.generation.Add(1)
}
t.mu.Unlock()
select {
case t.kick <- struct{}{}:
default:
}
}
// revalidateLoop runs the re-checks outside their callers, which can hold
// locks that authorization takes itself. It holds reloadMu, so it never sees a
// reload halfway, with identities installed but their policies not yet synced.
func (iam *IdentityAccessManagement) revalidateLoop() {
t := iam.inFlight
for {
select {
case <-iam.stopChan:
return
case <-t.kick:
}
iam.reloadMu.Lock()
for _, req := range t.pending() {
if identity := iam.currentIdentity(req); identity != nil && iam.authorizeRequest(req.req, identity, req.action) == s3err.ErrNone {
continue
}
if t.abort(req) {
glog.V(0).Infof("aborted %s %s of %s: its access was revoked", req.req.Method, req.req.URL.Path, req.identity.Name)
}
}
iam.reloadMu.Unlock()
}
}
func (t *inFlightRequests) add(req *inFlightRequest) {
t.mu.Lock()
t.requests[req] = struct{}{}
t.mu.Unlock()
}
func (t *inFlightRequests) remove(req *inFlightRequest) {
t.mu.Lock()
delete(t.requests, req)
t.mu.Unlock()
}
// pending takes the requests waiting for a re-check.
func (t *inFlightRequests) pending() []*inFlightRequest {
t.mu.Lock()
defer t.mu.Unlock()
var requests []*inFlightRequest
for req := range t.requests {
if _, onBucket := t.buckets[req.bucket]; t.all || onBucket {
requests = append(requests, req)
}
}
t.all, t.buckets = false, nil
return requests
}
// abort ends a request that is still in flight. It holds mu, which remove
// takes before the handler returns, so the connection it closes is still
// serving this request and not a later one on the same keep-alive connection.
func (t *inFlightRequests) abort(req *inFlightRequest) bool {
t.mu.Lock()
defer t.mu.Unlock()
if _, ok := t.requests[req]; !ok {
return false
}
delete(t.requests, req)
req.cancel()
if req.conn != nil {
_ = req.conn.Close()
return true
}
if req.body != nil {
_ = req.body.Close()
}
if req.stream != nil {
// A deadline in the past resets the stream, releasing a write blocked
// on a client that stopped reading.
_ = req.stream.SetWriteDeadline(time.Now())
}
return true
}