diff --git a/weed/s3api/auth_credentials.go b/weed/s3api/auth_credentials.go index 1b5362b67f..752ef2f098 100644 --- a/weed/s3api/auth_credentials.go +++ b/weed/s3api/auth_credentials.go @@ -124,6 +124,10 @@ type IdentityAccessManagement struct { // snapshot through commit) so an older snapshot cannot overwrite a newer // one reloadMu sync.Mutex + + // inFlight tracks the authorized requests being served, so a change that + // revokes their access aborts them. + inFlight *inFlightRequests } type Identity struct { @@ -377,6 +381,8 @@ func NewIdentityAccessManagementWithStore(option *S3ApiServerOption, filerClient iam.stopChan = make(chan struct{}) iam.reloadCh = make(chan struct{}, 1) go iam.reloadRetryLoop() + iam.inFlight = newInFlightRequests() + go iam.revalidateLoop() iam.grpcDialOption = option.GrpcDialOption // First, try to load configurations from file or filer @@ -1016,6 +1022,7 @@ func (iam *IdentityAccessManagement) ReplaceS3ApiConfiguration(config *iam_pb.S3 iam.m.RUnlock() } + iam.revalidateInFlight() return nil } @@ -1333,11 +1340,13 @@ func (iam *IdentityAccessManagement) MergeS3ApiConfiguration(config *iam_pb.S3Ap } } + iam.revalidateInFlight() return nil } func (iam *IdentityAccessManagement) RemoveIdentity(name string) { glog.V(1).Infof("IAM: remove identity %s", name) + defer iam.revalidateInFlight() iam.m.Lock() defer iam.m.Unlock() @@ -1765,13 +1774,14 @@ func (iam *IdentityAccessManagement) Auth(f http.HandlerFunc, action Action) htt // authRequestWithAuthType keeps the resolved identity when authN // succeeds but authZ denies, so the denied request still audits its // requester; a failed authN resolves no identity at all. + since := iam.inFlightGeneration() identity, errCode, _ := iam.authRequestWithAuthType(r, action) errCode = refineDenialForBucketName(r, identity, errCode) if errCode != s3err.ErrNone { glog.V(3).Infof("auth error: %v", errCode) } - iam.handleAuthResult(w, r, identity, errCode, f) + iam.handleAuthResult(w, r, identity, errCode, iam.abortWhenRevoked(f, identity, action, since)) } } @@ -2048,14 +2058,21 @@ func (iam *IdentityAccessManagement) authRequestWithAuthType(r *http.Request, ac if s3Err != s3err.ErrNone { return identity, s3Err, reqAuthType } + return identity, iam.authorizeRequest(r, identity, action), reqAuthType +} +// authorizeRequest decides whether an authenticated identity may perform action +// on the request's bucket and object. A request in flight is checked with it +// again when its access changes. +func (iam *IdentityAccessManagement) authorizeRequest(r *http.Request, identity *Identity, action Action) s3err.ErrorCode { bucket, object := s3_constants.GetBucketAndObject(r) - // Verify the original signature first, then evaluate policies against the - // effective PUT ACL, including signed query parameters hoisted by presigners. + // The signature was verified on the original request; evaluate policies + // against the effective PUT ACL, including signed query parameters hoisted + // by presigners. originalRequest := r - r, s3Err = putObjectACLPolicyRequest(r, action, bucket, object) + r, s3Err := putObjectACLPolicyRequest(r, action, bucket, object) if s3Err != s3err.ErrNone { - return identity, s3Err, reqAuthType + return s3Err } prefix := s3_constants.GetPrefix(r) @@ -2075,7 +2092,7 @@ func (iam *IdentityAccessManagement) authRequestWithAuthType(r *http.Request, ac if action == s3_constants.ACTION_WRITE && r.Method == http.MethodPost && object == "" && r.URL.Query().Has("delete") { r.Header.Set(s3_constants.AmzAccountId, identity.Account.Id) - return identity, s3err.ErrNone, reqAuthType + return s3err.ErrNone } // For ListBuckets, authorization is performed in the handler by iterating @@ -2119,7 +2136,7 @@ func (iam *IdentityAccessManagement) authRequestWithAuthType(r *http.Request, ac // SECURITY: Fail-close on policy evaluation errors // If we can't evaluate the policy, deny access rather than falling through to IAM glog.Errorf("Error evaluating bucket policy for %s/%s: %v - denying access", bucket, object, err) - return identity, s3err.ErrAccessDenied, reqAuthType + return s3err.ErrAccessDenied } else if evaluated { // A bucket policy exists and was evaluated with a matching statement if allowed { @@ -2129,7 +2146,7 @@ func (iam *IdentityAccessManagement) authRequestWithAuthType(r *http.Request, ac // group, or session policy. if iam.isActionExplicitlyDeniedByApplicablePolicies(r, identity, action, bucket, object) { glog.V(3).Infof("identity policy explicitly denies %s to %s on %s/%s despite bucket policy allow", identity.Name, action, bucket, object) - return identity, s3err.ErrAccessDenied, reqAuthType + return s3err.ErrAccessDenied } glog.V(3).Infof("Bucket policy allows %s to %s on %s/%s (bypassing IAM)", identity.Name, action, bucket, object) policyAllows = true @@ -2137,7 +2154,7 @@ func (iam *IdentityAccessManagement) authRequestWithAuthType(r *http.Request, ac // Policy explicitly denies this action - deny access immediately // Note: Explicit Deny in bucket policy overrides all other permissions glog.V(3).Infof("Bucket policy explicitly denies %s to %s on %s/%s", identity.Name, action, bucket, object) - return identity, s3err.ErrAccessDenied, reqAuthType + return s3err.ErrAccessDenied } } // If not evaluated (no policy or no matching statements), fall through to IAM/identity checks @@ -2147,14 +2164,14 @@ func (iam *IdentityAccessManagement) authRequestWithAuthType(r *http.Request, ac if !policyAllows { // Use centralized permission check if errCode := iam.VerifyActionPermission(r, identity, action, bucket, object); errCode != s3err.ErrNone { - return identity, errCode, reqAuthType + return errCode } } } originalRequest.Header.Set(s3_constants.AmzAccountId, identity.Account.Id) - return identity, s3err.ErrNone, reqAuthType + return s3err.ErrNone } @@ -2537,6 +2554,7 @@ func (iam *IdentityAccessManagement) resyncIAMManagerPolicies() { if err := iam.syncRuntimePoliciesToIAMManager(context.Background(), policies); err != nil { glog.Warningf("Failed to sync runtime policies to IAM Manager: %v", err) } + iam.revalidateInFlight() } // PruneBucketFromConfiguration removes any identity actions scoped to the given @@ -3500,12 +3518,14 @@ func (iam *IdentityAccessManagement) PutGroup(group *iam_pb.Group) error { if len(inlinePolicies) > 0 { iam.resyncIAMManagerPolicies() } + iam.revalidateInFlight() return nil } func (iam *IdentityAccessManagement) RemoveGroup(groupName string) { glog.V(1).Infof("IAM: remove group %s", groupName) + defer iam.revalidateInFlight() iam.m.Lock() defer iam.m.Unlock() diff --git a/weed/s3api/auth_credentials_subscribe.go b/weed/s3api/auth_credentials_subscribe.go index 69334a5fa2..9bc332ae3e 100644 --- a/weed/s3api/auth_credentials_subscribe.go +++ b/weed/s3api/auth_credentials_subscribe.go @@ -222,6 +222,10 @@ func (s3a *S3ApiServer) onBucketMetadataChange(dir string, oldEntry *filer_pb.En // Remove from bucket configuration cache s3a.invalidateBucketConfigCache(oldEntry.Name) } + // A bucket policy change can deny requests already being served. + removeName, updateName, _ := bucketPolicyMirrorOps(oldEntry, newEntry) + s3a.iam.revalidateBucketInFlight(removeName) + s3a.iam.revalidateBucketInFlight(updateName) } return nil } diff --git a/weed/s3api/auth_revoked_requests.go b/weed/s3api/auth_revoked_requests.go new file mode 100644 index 0000000000..a9116af9c3 --- /dev/null +++ b/weed/s3api/auth_revoked_requests.go @@ -0,0 +1,298 @@ +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 +} diff --git a/weed/s3api/auth_revoked_requests_test.go b/weed/s3api/auth_revoked_requests_test.go new file mode 100644 index 0000000000..7f40206d9d --- /dev/null +++ b/weed/s3api/auth_revoked_requests_test.go @@ -0,0 +1,422 @@ +package s3api + +import ( + "fmt" + "io" + "net" + "net/http" + "net/http/httptest" + "sync" + "testing" + "time" + + "github.com/gorilla/mux" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/seaweedfs/seaweedfs/weed/pb/iam_pb" + "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants" + "github.com/seaweedfs/seaweedfs/weed/s3api/s3err" + "github.com/seaweedfs/seaweedfs/weed/util" +) + +const ( + revokeKeyA = "AKIAREVOKEALICE00000" + revokeSecretA = "alice-secret-for-loopback-tests-only" + revokeKeyB = "AKIAREVOKEBOB0000000" + revokeSecretB = "bob-secret-for-loopback-tests-only00" + revokeKeyC = "AKIAREVOKECAROL00000" + revokeSecretC = "carol-secret-for-loopback-tests-only" +) + +func revokeIdentity(name, key, secret string, actions ...string) *iam_pb.Identity { + identity := &iam_pb.Identity{Name: name, Actions: actions} + if key != "" { + identity.Credentials = []*iam_pb.Credential{{AccessKey: key, SecretKey: secret}} + } + return identity +} + +// newRevokeIAM loads the identities into an IAM that aborts revoked requests. +func newRevokeIAM(t *testing.T, identities ...*iam_pb.Identity) *IdentityAccessManagement { + t.Helper() + iam := &IdentityAccessManagement{ + hashes: make(map[string]*sync.Pool), + hashCounters: make(map[string]*int32), + stopChan: make(chan struct{}), + inFlight: newInFlightRequests(), + } + go iam.revalidateLoop() + t.Cleanup(iam.Shutdown) + require.NoError(t, iam.ReplaceS3ApiConfiguration(&iam_pb.S3ApiConfiguration{Identities: identities})) + return iam +} + +// streamBody answers with a body streamed for three seconds, and reports on +// started once it streams. +func streamBody(started chan<- struct{}) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + started <- struct{}{} + chunk := make([]byte, 1024) + for i := 0; i < 300; i++ { + if _, err := w.Write(chunk); err != nil { + return + } + w.(http.Flusher).Flush() + select { + case <-r.Context().Done(): + return + case <-time.After(10 * time.Millisecond): + } + } + } +} + +// serveRevokeS3 serves GET /{bucket}/{object} through auth on a listener like +// the gateway's, answering with streamBody. +func serveRevokeS3(t *testing.T, started chan<- struct{}, auth func(http.HandlerFunc) http.HandlerFunc) string { + t.Helper() + stream := streamBody(started) + router := mux.NewRouter() + router.Methods(http.MethodGet).Path("/{bucket}/{object:.+}").HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + auth(stream)(w, s3_constants.EnsureIdentityHolder(r)) + }) + listener, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + server := &http.Server{Handler: router, ConnContext: util.ConnContext} + go func() { _ = server.Serve(&util.Listener{Listener: listener}) }() + t.Cleanup(func() { _ = server.Close() }) + return "http://" + listener.Addr().String() +} + +func authRead(iam *IdentityAccessManagement) func(http.HandlerFunc) http.HandlerFunc { + return func(f http.HandlerFunc) http.HandlerFunc { return iam.Auth(f, s3_constants.ACTION_READ) } +} + +// download reads an object to its end, signed with key unless it is empty, +// and reports how the read ended. +func download(t *testing.T, url, key, secret string) <-chan error { + t.Helper() + req, err := newTestRequest(http.MethodGet, url, 0, nil) + require.NoError(t, err) + if key != "" { + require.NoError(t, signRequestV4(req, key, secret)) + } + return fetch(req) +} + +// fetch reads the response to req to its end, and reports how the read ended. +func fetch(req *http.Request) <-chan error { + return fetchWith(&http.Transport{}, req) +} + +func fetchWith(transport http.RoundTripper, req *http.Request) <-chan error { + done := make(chan error, 1) + go func() { + resp, err := transport.RoundTrip(req) + if err != nil { + done <- err + return + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + done <- fmt.Errorf("status %d", resp.StatusCode) + return + } + _, err = io.Copy(io.Discard, resp.Body) + done <- err + }() + return done +} + +func waitStarted(t *testing.T, started <-chan struct{}, n int) { + t.Helper() + for range n { + select { + case <-started: + case <-time.After(5 * time.Second): + t.Fatal("download did not start") + } + } +} + +func downloadResult(t *testing.T, done <-chan error, within time.Duration) error { + t.Helper() + select { + case err := <-done: + return err + case <-time.After(within): + t.Fatalf("download still running after %v", within) + return nil + } +} + +// Revoking access aborts the downloads it denies: signed with an access key +// that lost its grant or was deactivated, or anonymous. A download whose +// access stays runs to its end, also when its key's secret is rotated. +func TestAbortRevokedRequests(t *testing.T) { + const revokeKeyD, revokeSecretD = "AKIAREVOKEDAVE000000", "dave-secret-for-loopback-tests-only0" + iam := newRevokeIAM(t, + revokeIdentity("alice", revokeKeyA, revokeSecretA, "Read:bkt"), + revokeIdentity("bob", revokeKeyB, revokeSecretB, "Read:bkt"), + revokeIdentity("carol", revokeKeyC, revokeSecretC, "Read:bkt"), + revokeIdentity("dave", revokeKeyD, revokeSecretD, "Read:bkt"), + revokeIdentity(s3_constants.AccountAnonymousId, "", "", "Read:bkt"), + ) + started := make(chan struct{}, 5) + url := serveRevokeS3(t, started, authRead(iam)) + "/bkt/object" + alice := download(t, url, revokeKeyA, revokeSecretA) + bob := download(t, url, revokeKeyB, revokeSecretB) + carol := download(t, url, revokeKeyC, revokeSecretC) + dave := download(t, url, revokeKeyD, revokeSecretD) + anonymous := download(t, url, "", "") + waitStarted(t, started, 5) + + deactivated := revokeIdentity("dave", revokeKeyD, revokeSecretD, "Read:bkt") + deactivated.Credentials[0].Status = iamAccessKeyStatusInactive + require.NoError(t, iam.ReplaceS3ApiConfiguration(&iam_pb.S3ApiConfiguration{Identities: []*iam_pb.Identity{ + revokeIdentity("alice", revokeKeyA, revokeSecretA, "Read:bkt", "Write:bkt"), + revokeIdentity("bob", revokeKeyB, revokeSecretB), + revokeIdentity("carol", revokeKeyC, "carol-rotated-secret-for-loopback-only", "Read:bkt"), + deactivated, + revokeIdentity(s3_constants.AccountAnonymousId, "", ""), + }})) + + assert.Error(t, downloadResult(t, bob, time.Second), "bob lost Read") + assert.Error(t, downloadResult(t, dave, time.Second), "dave's key was deactivated") + assert.Error(t, downloadResult(t, anonymous, time.Second), "anonymous lost Read") + assert.NoError(t, downloadResult(t, alice, 5*time.Second), "alice kept Read") + assert.NoError(t, downloadResult(t, carol, 5*time.Second), "carol's secret was rotated") +} + +// A session token sent with a configured key does not keep the request from +// being checked again: SigV4 ignores it for such a key, SigV2 never reads one. +func TestAbortRevokedRequestsCarryingSessionToken(t *testing.T) { + iam := newRevokeIAM(t, revokeIdentity("bob", revokeKeyB, revokeSecretB, "Read:bkt")) + started := make(chan struct{}, 2) + url := serveRevokeS3(t, started, authRead(iam)) + "/bkt/object" + + v4, err := newTestRequest(http.MethodGet, url, 0, nil) + require.NoError(t, err) + v4.Header.Set("X-Amz-Security-Token", "not-a-session-token") + require.NoError(t, signRequestV4(v4, revokeKeyB, revokeSecretB)) + + v2, err := http.NewRequest(http.MethodGet, url, nil) + require.NoError(t, err) + v2.Header.Set("Date", time.Now().UTC().Format(http.TimeFormat)) + v2.Header.Set("X-Amz-Security-Token", "not-a-session-token") + resource, code := iam.encodedResourceV2(v2) + require.Equal(t, s3err.ErrNone, code) + v2.Header.Set("Authorization", signatureV2(&Credential{AccessKey: revokeKeyB, SecretKey: revokeSecretB}, v2.Method, resource, v2.URL.Query().Encode(), v2.Header)) + + sigV4, sigV2 := fetch(v4), fetch(v2) + waitStarted(t, started, 2) + + require.NoError(t, iam.ReplaceS3ApiConfiguration(&iam_pb.S3ApiConfiguration{Identities: []*iam_pb.Identity{ + revokeIdentity("bob", revokeKeyB, revokeSecretB), + }})) + + assert.Error(t, downloadResult(t, sigV4, time.Second), "SigV4: bob lost Read") + assert.Error(t, downloadResult(t, sigV2, time.Second), "SigV2: bob lost Read") +} + +// A request whose access is revoked after it authenticated, but before it is +// tracked, is still aborted. +func TestAbortRequestRevokedBeforeItIsTracked(t *testing.T) { + iam := newRevokeIAM(t, revokeIdentity("bob", revokeKeyB, revokeSecretB, "Read:bkt")) + bob := iam.lookupByIdentityName("bob") + since := iam.inFlightGeneration() + started := make(chan struct{}, 1) + // As if Auth had admitted bob just before the change below. + url := serveRevokeS3(t, started, func(f http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + r.Header.Set(s3_constants.AmzAuthType, "SigV4") + r = r.WithContext(s3_constants.SetAccessKeyIdInContext(r.Context(), revokeKeyB)) + iam.abortWhenRevoked(f, bob, s3_constants.ACTION_READ, since)(w, r) + } + }) + "/bkt/object" + require.NoError(t, iam.ReplaceS3ApiConfiguration(&iam_pb.S3ApiConfiguration{Identities: []*iam_pb.Identity{ + revokeIdentity("bob", revokeKeyB, revokeSecretB), + }})) + // Let the re-check the change scheduled pass before bob is tracked, so only + // the generation check can catch him. + require.Eventually(t, func() bool { + iam.inFlight.mu.Lock() + defer iam.inFlight.mu.Unlock() + return !iam.inFlight.all + }, 5*time.Second, time.Millisecond) + + done := download(t, url, "", "") + waitStarted(t, started, 1) + assert.Error(t, downloadResult(t, done, time.Second)) +} + +// A catch-up re-check of a request that authenticated before a change is not +// a change itself, so it leaves the generation as it is. +func TestCatchUpRecheckKeepsTheGeneration(t *testing.T) { + iam := newRevokeIAM(t, revokeIdentity("bob", revokeKeyB, revokeSecretB, "Read:bkt")) + bob := iam.lookupByIdentityName("bob") + since := iam.inFlightGeneration() + iam.revalidateInFlight() + changed := iam.inFlightGeneration() + require.NotEqual(t, since, changed) + + r := httptest.NewRequest(http.MethodGet, "/bkt/object", nil) + r.Header.Set(s3_constants.AmzAuthType, "SigV4") + r = r.WithContext(s3_constants.SetAccessKeyIdInContext(r.Context(), revokeKeyB)) + iam.abortWhenRevoked(func(http.ResponseWriter, *http.Request) {}, bob, s3_constants.ACTION_READ, since)(httptest.NewRecorder(), r) + assert.Equal(t, changed, iam.inFlightGeneration()) +} + +// A bucket policy that starts denying aborts the requests on its bucket only. +func TestAbortRequestsDeniedByBucketPolicy(t *testing.T) { + iam := newRevokeIAM(t, revokeIdentity("bob", revokeKeyB, revokeSecretB, "Read")) + iam.policyEngine = NewBucketPolicyEngine() + started := make(chan struct{}, 2) + base := serveRevokeS3(t, started, authRead(iam)) + denied := download(t, base+"/bkt/object", revokeKeyB, revokeSecretB) + other := download(t, base+"/other/object", revokeKeyB, revokeSecretB) + waitStarted(t, started, 2) + + require.NoError(t, iam.policyEngine.engine.SetBucketPolicy("bkt", + `{"Version":"2012-10-17","Statement":[{"Effect":"Deny","Principal":"*","Action":"s3:GetObject","Resource":"arn:aws:s3:::bkt/*"}]}`)) + iam.revalidateBucketInFlight("bkt") + + assert.Error(t, downloadResult(t, denied, time.Second), "the bucket policy denies bkt") + assert.NoError(t, downloadResult(t, other, 5*time.Second), "no policy covers other") +} + +// A re-check judges time conditions as of when the request was admitted, so a +// grant that expires while the request runs does not abort it. +func TestAbortRevokedRequestsJudgesTimeAsOfAdmission(t *testing.T) { + iam := newRevokeIAM(t, revokeIdentity("dave", revokeKeyB, revokeSecretB)) + iam.policyEngine = NewBucketPolicyEngine() + until := time.Now().Add(time.Second).Truncate(time.Second).Add(time.Second) + require.NoError(t, iam.policyEngine.engine.SetBucketPolicy("bkt", fmt.Sprintf( + `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":"*","Action":"s3:GetObject","Resource":"arn:aws:s3:::bkt/*","Condition":{"DateLessThan":{"aws:CurrentTime":%q}}}]}`, + until.UTC().Format(time.RFC3339)))) + started := make(chan struct{}, 1) + done := download(t, serveRevokeS3(t, started, authRead(iam))+"/bkt/object", revokeKeyB, revokeSecretB) + waitStarted(t, started, 1) + + time.Sleep(time.Until(until) + 100*time.Millisecond) + iam.revalidateInFlight() + + assert.NoError(t, downloadResult(t, done, 5*time.Second), "the grant held when the download was admitted") +} + +// A revoked HTTP/2 upload is released from its blocked body read, while a +// download on another stream of the same connection runs to its end. +func TestAbortRevokedHTTP2Upload(t *testing.T) { + iam := newRevokeIAM(t, + revokeIdentity("alice", revokeKeyA, revokeSecretA, "Read:bkt"), + revokeIdentity("bob", revokeKeyB, revokeSecretB, "Write:bkt"), + ) + started := make(chan struct{}, 2) + connections := make(chan string, 2) + uploadRead := make(chan error, 1) + upload := func(w http.ResponseWriter, r *http.Request) { + started <- struct{}{} + _, err := io.Copy(io.Discard, r.Body) + uploadRead <- err + } + route := func(f http.HandlerFunc, action Action) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + connections <- r.Proto + " " + r.RemoteAddr + iam.Auth(f, action)(w, s3_constants.EnsureIdentityHolder(r)) + } + } + router := mux.NewRouter() + router.Methods(http.MethodGet).Path("/{bucket}/{object:.+}").HandlerFunc(route(streamBody(started), s3_constants.ACTION_READ)) + router.Methods(http.MethodPut).Path("/{bucket}/{object:.+}").HandlerFunc(route(upload, s3_constants.ACTION_WRITE)) + server := httptest.NewUnstartedServer(router) + server.EnableHTTP2 = true + server.Config.ConnContext = util.ConnContext + server.StartTLS() + t.Cleanup(server.Close) + transport := server.Client().Transport + + body, bodyWriter := io.Pipe() + t.Cleanup(func() { _ = bodyWriter.Close() }) + put, err := http.NewRequest(http.MethodPut, server.URL+"/bkt/upload", body) + require.NoError(t, err) + put.Header.Set("X-Amz-Content-Sha256", "UNSIGNED-PAYLOAD") + require.NoError(t, signRequestV4(put, revokeKeyB, revokeSecretB)) + go func() { + if resp, err := transport.RoundTrip(put); err == nil { + _ = resp.Body.Close() + } + }() + go func() { _, _ = bodyWriter.Write(make([]byte, 1024)) }() + get, err := newTestRequest(http.MethodGet, server.URL+"/bkt/object", 0, nil) + require.NoError(t, err) + require.NoError(t, signRequestV4(get, revokeKeyA, revokeSecretA)) + alice := fetchWith(transport, get) + waitStarted(t, started, 2) + first, second := <-connections, <-connections + require.Equal(t, first, second, "both streams share one connection") + require.Contains(t, first, "HTTP/2") + + require.NoError(t, iam.ReplaceS3ApiConfiguration(&iam_pb.S3ApiConfiguration{Identities: []*iam_pb.Identity{ + revokeIdentity("alice", revokeKeyA, revokeSecretA, "Read:bkt"), + revokeIdentity("bob", revokeKeyB, revokeSecretB), + }})) + + select { + case err := <-uploadRead: + assert.Error(t, err, "bob lost Write") + case <-time.After(time.Second): + t.Fatal("bob's upload is still reading its body") + } + assert.NoError(t, downloadResult(t, alice, 5*time.Second), "alice's stream on the same connection") +} + +// A revoked HTTP/2 download blocked writing to a client that stopped reading +// has its stream reset, also behind the gateway's request tracking. +func TestAbortRevokedHTTP2DownloadBlockedWriting(t *testing.T) { + iam := newRevokeIAM(t, revokeIdentity("bob", revokeKeyB, revokeSecretB, "Read:bkt")) + started := make(chan struct{}, 1) + written := make(chan error, 1) + writeUntilError := func(w http.ResponseWriter, r *http.Request) { + started <- struct{}{} + chunk := make([]byte, 64*1024) + for { + if _, err := w.Write(chunk); err != nil { + written <- err + return + } + } + } + router := mux.NewRouter() + router.Methods(http.MethodGet).Path("/{bucket}/{object:.+}").HandlerFunc(track(iam.Auth(writeUntilError, s3_constants.ACTION_READ), "GET")) + server := httptest.NewUnstartedServer(router) + server.EnableHTTP2 = true + server.Config.ConnContext = util.ConnContext + server.StartTLS() + t.Cleanup(server.Close) + + get, err := newTestRequest(http.MethodGet, server.URL+"/bkt/object", 0, nil) + require.NoError(t, err) + require.NoError(t, signRequestV4(get, revokeKeyB, revokeSecretB)) + resp, err := server.Client().Transport.RoundTrip(get) + require.NoError(t, err) + t.Cleanup(func() { _ = resp.Body.Close() }) + require.Equal(t, "HTTP/2.0", resp.Proto) + waitStarted(t, started, 1) + select { + case err := <-written: + t.Fatalf("the download stopped writing before the revoke: %v", err) + case <-time.After(500 * time.Millisecond): + } + + require.NoError(t, iam.ReplaceS3ApiConfiguration(&iam_pb.S3ApiConfiguration{Identities: []*iam_pb.Identity{ + revokeIdentity("bob", revokeKeyB, revokeSecretB), + }})) + + select { + case err := <-written: + assert.Error(t, err, "bob lost Read") + case <-time.After(time.Second): + t.Fatal("bob's download is still blocked writing") + } +} diff --git a/weed/s3api/policy_engine/engine.go b/weed/s3api/policy_engine/engine.go index 39c64dad57..9c35726ec9 100644 --- a/weed/s3api/policy_engine/engine.go +++ b/weed/s3api/policy_engine/engine.go @@ -1,6 +1,7 @@ package policy_engine import ( + "context" "fmt" "maps" "net/http" @@ -436,18 +437,31 @@ func (engine *PolicyEngine) ExtractConditionValuesFromRequest(r *http.Request) m return values } +type requestTimeKey struct{} + +// WithRequestTime makes aws:CurrentTime and aws:RequestTime read t instead of +// the current time, so a request checked again while it runs is judged as of +// when it was admitted. +func WithRequestTime(ctx context.Context, t time.Time) context.Context { + return context.WithValue(ctx, requestTimeKey{}, t) +} + // RequestConditionValues returns the condition keys read from the request // itself, leaving out aws:SourceIp and the bucket-listing keys, which depend // on the caller's proxy and listing handling. func RequestConditionValues(r *http.Request) map[string][]string { values := make(map[string][]string) + now := time.Now() + if t, ok := r.Context().Value(requestTimeKey{}).(time.Time); ok { + now = t + } // AWS condition keys values["aws:SecureTransport"] = []string{fmt.Sprintf("%t", r.TLS != nil)} // Use AWS standard condition key for current time - values["aws:CurrentTime"] = []string{time.Now().Format(time.RFC3339)} + values["aws:CurrentTime"] = []string{now.Format(time.RFC3339)} // Keep RequestTime for backward compatibility - values["aws:RequestTime"] = []string{time.Now().Format(time.RFC3339)} + values["aws:RequestTime"] = []string{now.Format(time.RFC3339)} // S3 specific condition keys if userAgent := r.Header.Get("User-Agent"); userAgent != "" { diff --git a/weed/stats/http_status_recorder.go b/weed/stats/http_status_recorder.go index 19467ecf2c..16b46a13aa 100644 --- a/weed/stats/http_status_recorder.go +++ b/weed/stats/http_status_recorder.go @@ -19,3 +19,7 @@ func (r *StatusRecorder) WriteHeader(status int) { func (r *StatusRecorder) Flush() { r.ResponseWriter.(http.Flusher).Flush() } + +func (r *StatusRecorder) Unwrap() http.ResponseWriter { + return r.ResponseWriter +} diff --git a/weed/util/net_timeout.go b/weed/util/net_timeout.go index e02e1a7cdd..04fe5cf70f 100644 --- a/weed/util/net_timeout.go +++ b/weed/util/net_timeout.go @@ -168,6 +168,15 @@ func ClientGone(ctx context.Context) bool { return tc != nil && ctx.Err() == context.Canceled && !tc.readEndedByServer.Load() } +// ConnFromContext returns the connection serving a request, as ConnContext +// recorded it, or nil. +func ConnFromContext(ctx context.Context) net.Conn { + if tc, ok := ctx.Value(connContextKey{}).(*Conn); ok { + return tc + } + return nil +} + func NewListener(addr string, timeout time.Duration) (ipListener net.Listener, err error) { listener, err := net.Listen("tcp", addr) if err != nil {