mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 02:27:26 +01:00
s3api: decide existing-object-tag denies on the object's tags (#13038)
* s3api: report a bucket policy Deny on existing object tags HasExistingObjectTagDeny tells whether a bucket policy has a Deny statement conditioned on s3:ExistingObjectTag/<key>, so the auth layer knows when a deny may turn on tags it has not read yet. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: decide existing-object-tag denies on the object's tags The auth layer evaluates the bucket policy before the handler reads the object, so s3:ExistingObjectTag/<key> resolves to a missing tag. A Deny with a negated condition (StringNotEquals, StringNotLike, StringNotEqualsIgnoreCase, Null true) then matched every object and was final, even one whose tag satisfies it, as in the deny-until-scanned-clean pattern. When that early evaluation denies and the policy has such a Deny, look up the object's entry and evaluate again with its tags. A missing object or a failed lookup keeps the deny. Copy sources and per-key checks that go through authorizeObjectKeyAction get the same treatment. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: give identity checks the object tags a Deny was decided on With IAM integration, VerifyActionPermission evaluates the mirrored bucket policy again alongside the identity's policies, from a condition context built from the request alone. The negated existing-tag Deny matched there once more and denied an object tagged to pass it. evaluateBucketPolicy now returns the request carrying the tags it read, and RequestConditionValues reports them as s3:ExistingObjectTag/<key>. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: recheck in-flight tag conditions on the version served An in-flight request is authorized again when access changes. The entry lookup read the version current by then, so a newer version tagged to pass the Deny could keep a download of an older, denied version running. The handler's entry recheck now records the entry it authorized on the tracked request, and the re-check decides on that entry. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: load the bucket before deciding an object request on its policy On a bucket whose policy was not loaded yet, the early bucket policy check found no policy and skipped the object-tag lookup, so the identity checks saw the request without the object's tags. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: keep an owned copy of the entry a tracked request served Handlers change the entry's metadata after the check, for example when storing new tags, so revalidation read a map the handler was writing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
aaca5c8c0a
commit
8053e77813
8 files changed
+388
-4
No files matched your search
@@ -0,0 +1,57 @@
|
||||
package integration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/policy"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/sts"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// The mirrored bucket policy decides a negated s3:ExistingObjectTag Deny on
|
||||
// the tags the request context carries.
|
||||
func TestMirroredBucketPolicyReadsExistingObjectTags(t *testing.T) {
|
||||
manager := NewIAMManager()
|
||||
require.NoError(t, manager.Initialize(&IAMConfig{
|
||||
STS: &sts.STSConfig{
|
||||
TokenDuration: sts.FlexibleDuration{Duration: time.Hour},
|
||||
MaxSessionLength: sts.FlexibleDuration{Duration: 12 * time.Hour},
|
||||
Issuer: "test-sts",
|
||||
SigningKey: []byte("test-signing-key-32-characters-long"),
|
||||
},
|
||||
Policy: &policy.PolicyEngineConfig{DefaultEffect: string(policy.EffectDeny), StoreType: sts.StoreTypeMemory},
|
||||
Roles: &RoleStoreConfig{StoreType: sts.StoreTypeMemory},
|
||||
}, func() string { return "localhost:8888" }))
|
||||
|
||||
ctx := context.Background()
|
||||
require.NoError(t, manager.CreatePolicy(ctx, "", "ReadAll", &policy.PolicyDocument{
|
||||
Version: "2012-10-17",
|
||||
Statement: []policy.Statement{{Effect: "Allow", Action: []string{"s3:GetObject"}, Resource: []string{"arn:aws:s3:::*"}}},
|
||||
}))
|
||||
manager.SetUserStore(&fakeUserStore{users: map[string]*iam_pb.Identity{
|
||||
"app": {Name: "app", PolicyNames: []string{"ReadAll"}},
|
||||
}})
|
||||
require.NoError(t, manager.UpdateBucketPolicy(ctx, "test", []byte(`{"Version":"2012-10-17","Statement":[{
|
||||
"Effect":"Deny","Principal":"*","Action":"s3:GetObject","Resource":"arn:aws:s3:::test/scanned/*",
|
||||
"Condition":{"StringNotEquals":{"s3:ExistingObjectTag/ScanStatus":"CLEAN"}}}]}`)))
|
||||
|
||||
read := func(requestContext map[string]interface{}) bool {
|
||||
allowed, err := manager.IsActionAllowed(ctx, &ActionRequest{
|
||||
Principal: "arn:aws:iam::seaweedfs:user/app",
|
||||
Action: "s3:GetObject",
|
||||
Resource: "arn:aws:s3:::test/scanned/a.txt",
|
||||
RequestContext: requestContext,
|
||||
PolicyNames: []string{"ReadAll"},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return allowed
|
||||
}
|
||||
assert.False(t, read(map[string]interface{}{}), "an object without the tag is denied")
|
||||
assert.False(t, read(map[string]interface{}{"s3:ExistingObjectTag/ScanStatus": []string{"INFECTED"}}))
|
||||
assert.True(t, read(map[string]interface{}{"s3:ExistingObjectTag/ScanStatus": []string{"CLEAN"}}),
|
||||
"an object tagged CLEAN is readable")
|
||||
}
|
||||
@@ -88,6 +88,11 @@ type IdentityAccessManagement struct {
|
||||
// evaluate that mirror. Set by NewS3ApiServer; nil in tests.
|
||||
primeBucketForIAM func(bucket string) s3err.ErrorCode
|
||||
|
||||
// objectEntryForPolicy returns the extended attributes of the object a
|
||||
// request names, for bucket policy conditions on its existing tags. Set by
|
||||
// NewS3ApiServer; nil in tests.
|
||||
objectEntryForPolicy func(r *http.Request, bucket, object string) (map[string][]byte, bool)
|
||||
|
||||
// Cached policy engine for IAM policy fallback evaluation.
|
||||
// Keyed by policy name, kept in sync by PutPolicy/DeletePolicy.
|
||||
iamPolicyEngine *policy_engine.PolicyEngine
|
||||
@@ -2130,7 +2135,11 @@ func (iam *IdentityAccessManagement) authorizeRequest(r *http.Request, identity
|
||||
if isBucketListingRequest(r, action) {
|
||||
policyObject = ""
|
||||
}
|
||||
allowed, evaluated, err := iam.policyEngine.EvaluatePolicy(bucket, policyObject, string(action), principal, r, claims, nil)
|
||||
if iam.primeBucketForIAM != nil && policyObject != "" && policyObject != "/" {
|
||||
iam.primeBucketForIAM(bucket)
|
||||
}
|
||||
policyReq, allowed, evaluated, err := iam.evaluateBucketPolicy(bucket, policyObject, string(action), principal, r, claims)
|
||||
r = policyReq
|
||||
|
||||
if err != nil {
|
||||
// SECURITY: Fail-close on policy evaluation errors
|
||||
@@ -3215,6 +3224,30 @@ func objectKeyPolicyRequest(r *http.Request, method, bucket, objectKey, versionI
|
||||
return keyReq
|
||||
}
|
||||
|
||||
// evaluateBucketPolicy evaluates the bucket policy before the handler reads
|
||||
// the object. Read that early, a negated condition on s3:ExistingObjectTag
|
||||
// sees no tag and would deny an object whose tag satisfies it, so a Deny is
|
||||
// decided again on the tags the object has. The returned request carries
|
||||
// those tags to the identity checks, which evaluate the mirrored bucket
|
||||
// policy again.
|
||||
func (iam *IdentityAccessManagement) evaluateBucketPolicy(bucket, object, action, principal string, r *http.Request, claims map[string]interface{}) (policyReq *http.Request, allowed, evaluated bool, err error) {
|
||||
allowed, evaluated, err = iam.policyEngine.EvaluatePolicy(bucket, object, action, principal, r, claims, nil)
|
||||
if err != nil || !evaluated || allowed || object == "" || object == "/" ||
|
||||
iam.objectEntryForPolicy == nil || !iam.policyEngine.HasExistingObjectTagDeny(bucket) {
|
||||
return r, allowed, evaluated, err
|
||||
}
|
||||
extended, found := servedObjectEntry(r, bucket, object)
|
||||
if !found {
|
||||
extended, found = iam.objectEntryForPolicy(r, bucket, object)
|
||||
}
|
||||
if !found {
|
||||
return r, allowed, evaluated, err
|
||||
}
|
||||
r = r.WithContext(policy_engine.WithExistingObjectTags(r.Context(), extended))
|
||||
allowed, evaluated, err = iam.policyEngine.EvaluatePolicy(bucket, object, action, principal, r, claims, extended)
|
||||
return r, allowed, evaluated, err
|
||||
}
|
||||
|
||||
func (iam *IdentityAccessManagement) authorizeObjectKeyAction(r *http.Request, identity *Identity, method string, action Action, bucket, objectKey, versionId string) s3err.ErrorCode {
|
||||
if identity == nil {
|
||||
return s3err.ErrAccessDenied
|
||||
@@ -3232,7 +3265,8 @@ func (iam *IdentityAccessManagement) authorizeObjectKeyAction(r *http.Request, i
|
||||
}
|
||||
}
|
||||
principal := buildPrincipalARN(identity, keyReq)
|
||||
allowed, evaluated, err := iam.policyEngine.EvaluatePolicy(bucket, objectKey, string(action), principal, keyReq, identity.Claims, nil)
|
||||
policyReq, allowed, evaluated, err := iam.evaluateBucketPolicy(bucket, objectKey, string(action), principal, keyReq, identity.Claims)
|
||||
keyReq = policyReq
|
||||
if err != nil {
|
||||
glog.Errorf("policy evaluation failed for %s %s/%s: %v - denying", action, bucket, objectKey, err)
|
||||
return s3err.ErrAccessDenied
|
||||
|
||||
@@ -3,6 +3,7 @@ package s3api
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"maps"
|
||||
"net"
|
||||
"net/http"
|
||||
"sync"
|
||||
@@ -108,6 +109,7 @@ func (iam *IdentityAccessManagement) abortWhenRevoked(f http.HandlerFunc, identi
|
||||
}
|
||||
ctx, cancel := context.WithCancel(r.Context())
|
||||
defer cancel()
|
||||
ctx = context.WithValue(ctx, servedObjectEntriesKey{}, &sync.Map{})
|
||||
r = r.WithContext(ctx)
|
||||
bucket, _ := s3_constants.GetBucketAndObject(r)
|
||||
admitted := time.Now()
|
||||
@@ -133,6 +135,29 @@ func (iam *IdentityAccessManagement) abortWhenRevoked(f http.HandlerFunc, identi
|
||||
|
||||
type inFlightRequestKey struct{}
|
||||
|
||||
type servedObjectEntriesKey struct{}
|
||||
|
||||
// recordServedObjectEntry keeps the entry a tracked request was authorized
|
||||
// against, so a re-check decides tag conditions on the version being served
|
||||
// rather than on the one current by then.
|
||||
func recordServedObjectEntry(r *http.Request, bucket, object string, extended map[string][]byte) {
|
||||
if served, ok := r.Context().Value(servedObjectEntriesKey{}).(*sync.Map); ok {
|
||||
served.Store(bucket+"/"+object, maps.Clone(extended))
|
||||
}
|
||||
}
|
||||
|
||||
func servedObjectEntry(r *http.Request, bucket, object string) (map[string][]byte, bool) {
|
||||
served, ok := r.Context().Value(servedObjectEntriesKey{}).(*sync.Map)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
extended, found := served.Load(bucket + "/" + object)
|
||||
if !found {
|
||||
return nil, false
|
||||
}
|
||||
return extended.(map[string][]byte), true
|
||||
}
|
||||
|
||||
// untrackInFlight stops re-checking r before it stores a change to access,
|
||||
// which would otherwise judge r by its own change and abort it after the
|
||||
// change is stored. It reports false when r was aborted already, so the change
|
||||
|
||||
@@ -110,6 +110,30 @@ func (engine *PolicyEngine) HasPolicyForBucket(bucketName string) bool {
|
||||
return exists
|
||||
}
|
||||
|
||||
// HasExistingObjectTagDeny reports whether the bucket policy has a Deny
|
||||
// statement conditioned on s3:ExistingObjectTag/<key>.
|
||||
func (engine *PolicyEngine) HasExistingObjectTagDeny(bucketName string) bool {
|
||||
engine.mutex.RLock()
|
||||
context, exists := engine.contexts[bucketName]
|
||||
engine.mutex.RUnlock()
|
||||
if !exists {
|
||||
return false
|
||||
}
|
||||
for _, stmt := range context.policy.Statements {
|
||||
if stmt.Statement.Effect != PolicyEffectDeny {
|
||||
continue
|
||||
}
|
||||
for _, conditionMap := range stmt.Statement.Condition {
|
||||
for key := range conditionMap {
|
||||
if strings.HasPrefix(key, ExistingObjectTagPrefix) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// EvaluatePolicy evaluates a policy for the given arguments
|
||||
func (engine *PolicyEngine) EvaluatePolicy(bucketName string, args *PolicyEvaluationArgs) PolicyEvaluationResult {
|
||||
engine.mutex.RLock()
|
||||
@@ -446,6 +470,14 @@ func WithRequestTime(ctx context.Context, t time.Time) context.Context {
|
||||
return context.WithValue(ctx, requestTimeKey{}, t)
|
||||
}
|
||||
|
||||
type existingObjectTagsKey struct{}
|
||||
|
||||
// WithExistingObjectTags makes RequestConditionValues report the tags held in
|
||||
// an object entry's extended attributes as s3:ExistingObjectTag/<key>.
|
||||
func WithExistingObjectTags(ctx context.Context, extended map[string][]byte) context.Context {
|
||||
return context.WithValue(ctx, existingObjectTagsKey{}, extended)
|
||||
}
|
||||
|
||||
// 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.
|
||||
@@ -472,8 +504,13 @@ func RequestConditionValues(r *http.Request) map[string][]string {
|
||||
values["aws:Referer"] = []string{referer}
|
||||
}
|
||||
|
||||
// Note: s3:ExistingObjectTag/<key> conditions are evaluated using objectEntry
|
||||
// passed to EvaluatePolicy, not extracted from the request.
|
||||
if extended, ok := r.Context().Value(existingObjectTagsKey{}).(map[string][]byte); ok {
|
||||
for key, value := range extended {
|
||||
if tagKey, found := strings.CutPrefix(key, s3_constants.AmzObjectTaggingPrefix); found && tagKey != "" {
|
||||
values[ExistingObjectTagPrefix+tagKey] = []string{string(value)}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if tags := requestObjectTags(r); len(tags) > 0 {
|
||||
for key, value := range tags {
|
||||
|
||||
@@ -1467,3 +1467,21 @@ func TestMultipartUploadInheritsPutObjectPermission(t *testing.T) {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestRequestConditionValuesReportExistingObjectTags(t *testing.T) {
|
||||
r := httptest.NewRequest(http.MethodGet, "/bucket/key", nil)
|
||||
if _, found := RequestConditionValues(r)[ExistingObjectTagPrefix+"ScanStatus"]; found {
|
||||
t.Fatal("existing object tag reported without an entry")
|
||||
}
|
||||
r = r.WithContext(WithExistingObjectTags(r.Context(), map[string][]byte{
|
||||
s3_constants.AmzObjectTaggingPrefix + "ScanStatus": []byte("CLEAN"),
|
||||
s3_constants.AmzUserMetaPrefix + "Other": []byte("x"),
|
||||
}))
|
||||
values := RequestConditionValues(r)
|
||||
if got := values[ExistingObjectTagPrefix+"ScanStatus"]; len(got) != 1 || got[0] != "CLEAN" {
|
||||
t.Errorf("s3:ExistingObjectTag/ScanStatus = %v, want [CLEAN]", got)
|
||||
}
|
||||
if _, found := values[ExistingObjectTagPrefix+"Other"]; found {
|
||||
t.Error("user metadata reported as an object tag")
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,18 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/policy_engine"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
@@ -670,3 +676,198 @@ func TestCheckVersionReadGrantPreservesQueryAuth(t *testing.T) {
|
||||
assert.Equal(t, "v1", q.Get("versionId"))
|
||||
assert.False(t, q.Has("attributes"))
|
||||
}
|
||||
|
||||
// A Deny with a negated condition on the object's existing tag is decided on
|
||||
// the tags the object has, not on the missing entry the auth layer starts with.
|
||||
func TestNegatedExistingObjectTagDenyDecidedOnObjectTags(t *testing.T) {
|
||||
const (
|
||||
bucket = "scan-bucket"
|
||||
accessKey = "LOCALSCANKEY00000001"
|
||||
secretKey = "local-scan-secret-for-loopback-only"
|
||||
)
|
||||
tagged := func(value string) map[string][]byte {
|
||||
return map[string][]byte{s3_constants.AmzObjectTaggingPrefix + "ScanStatus": []byte(value)}
|
||||
}
|
||||
objects := map[string]map[string][]byte{
|
||||
"scanned/clean.txt": tagged("CLEAN"),
|
||||
"scanned/infected.txt": tagged("INFECTED"),
|
||||
"scanned/untagged.txt": nil,
|
||||
"other/plain.txt": nil,
|
||||
}
|
||||
conditions := []struct {
|
||||
name, condition string
|
||||
infected s3err.ErrorCode
|
||||
}{
|
||||
{"StringNotEquals", `{"StringNotEquals":{"s3:ExistingObjectTag/ScanStatus":"CLEAN"}}`, s3err.ErrAccessDenied},
|
||||
{"StringNotLike", `{"StringNotLike":{"s3:ExistingObjectTag/ScanStatus":"CLEAN"}}`, s3err.ErrAccessDenied},
|
||||
{"StringNotEqualsIgnoreCase", `{"StringNotEqualsIgnoreCase":{"s3:ExistingObjectTag/ScanStatus":"clean"}}`, s3err.ErrAccessDenied},
|
||||
{"Null", `{"Null":{"s3:ExistingObjectTag/ScanStatus":"true"}}`, s3err.ErrNone},
|
||||
}
|
||||
|
||||
for _, tc := range conditions {
|
||||
condition := tc.condition
|
||||
want := map[string]s3err.ErrorCode{
|
||||
"scanned/clean.txt": s3err.ErrNone,
|
||||
"scanned/infected.txt": tc.infected,
|
||||
"scanned/untagged.txt": s3err.ErrAccessDenied,
|
||||
"scanned/missing.txt": s3err.ErrAccessDenied,
|
||||
"other/plain.txt": s3err.ErrNone,
|
||||
}
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
iam := &IdentityAccessManagement{
|
||||
hashes: make(map[string]*sync.Pool),
|
||||
hashCounters: make(map[string]*int32),
|
||||
}
|
||||
require.NoError(t, iam.loadS3ApiConfiguration(&iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{{
|
||||
Name: "app",
|
||||
Actions: []string{"Read", "Write", "List", "Tagging"},
|
||||
Credentials: []*iam_pb.Credential{{AccessKey: accessKey, SecretKey: secretKey}},
|
||||
}},
|
||||
}))
|
||||
iam.policyEngine = NewBucketPolicyEngine()
|
||||
require.NoError(t, iam.policyEngine.engine.SetBucketPolicy(bucket, `{"Version":"2012-10-17","Statement":[{
|
||||
"Effect":"Deny","Principal":"*","Action":["s3:GetObject","s3:GetObjectVersion"],
|
||||
"Resource":"arn:aws:s3:::`+bucket+`/scanned/*","Condition":`+condition+`}]}`))
|
||||
iam.objectEntryForPolicy = func(r *http.Request, b, object string) (map[string][]byte, bool) {
|
||||
extended, found := objects[strings.TrimPrefix(object, "/")]
|
||||
return extended, found && b == bucket
|
||||
}
|
||||
|
||||
for key, code := range want {
|
||||
for _, method := range []string{http.MethodGet, http.MethodHead} {
|
||||
req := mustNewRequest(method, "http://127.0.0.1:9000/"+bucket+"/"+key, 0, nil, t)
|
||||
require.NoError(t, signRequestV4(req, accessKey, secretKey))
|
||||
req = mux.SetURLVars(req, map[string]string{"bucket": bucket, "object": key})
|
||||
_, got := iam.authRequest(req, s3_constants.ACTION_READ)
|
||||
assert.Equal(t, code, got, "%s %s", method, key)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Only a Deny that reads the object's tags costs an entry lookup.
|
||||
func TestDenyWithoutExistingObjectTagSkipsEntryLookup(t *testing.T) {
|
||||
const bucket = "ip-bucket"
|
||||
engine := NewBucketPolicyEngine()
|
||||
require.NoError(t, engine.engine.SetBucketPolicy(bucket, `{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Deny","Principal":"*","Action":"s3:GetObject","Resource":"arn:aws:s3:::`+bucket+`/*",
|
||||
"Condition":{"StringNotEquals":{"aws:UserAgent":"scanner"}}},
|
||||
{"Effect":"Allow","Principal":"*","Action":"s3:GetObject","Resource":"arn:aws:s3:::`+bucket+`/*",
|
||||
"Condition":{"StringEquals":{"s3:ExistingObjectTag/public":"yes"}}}]}`))
|
||||
assert.False(t, engine.HasExistingObjectTagDeny(bucket))
|
||||
|
||||
lookups := 0
|
||||
iam := &IdentityAccessManagement{policyEngine: engine}
|
||||
iam.objectEntryForPolicy = func(*http.Request, string, string) (map[string][]byte, bool) {
|
||||
lookups++
|
||||
return nil, true
|
||||
}
|
||||
req := httptest.NewRequest(http.MethodGet, "/"+bucket+"/a.txt", nil)
|
||||
_, _, evaluated, err := iam.evaluateBucketPolicy(bucket, "/a.txt", string(s3_constants.ACTION_READ), "*", req, nil)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, evaluated)
|
||||
assert.Zero(t, lookups)
|
||||
}
|
||||
|
||||
// The identity checks that follow evaluate the mirrored bucket policy again,
|
||||
// so the request they get carries the tags the Deny was decided on.
|
||||
func TestEvaluateBucketPolicyHandsOnObjectTags(t *testing.T) {
|
||||
const bucket = "scan-bucket"
|
||||
engine := NewBucketPolicyEngine()
|
||||
require.NoError(t, engine.engine.SetBucketPolicy(bucket, `{"Version":"2012-10-17","Statement":[{
|
||||
"Effect":"Deny","Principal":"*","Action":"s3:GetObject","Resource":"arn:aws:s3:::`+bucket+`/*",
|
||||
"Condition":{"StringNotEquals":{"s3:ExistingObjectTag/ScanStatus":"CLEAN"}}}]}`))
|
||||
iam := &IdentityAccessManagement{policyEngine: engine}
|
||||
iam.objectEntryForPolicy = func(*http.Request, string, string) (map[string][]byte, bool) {
|
||||
return map[string][]byte{s3_constants.AmzObjectTaggingPrefix + "ScanStatus": []byte("CLEAN")}, true
|
||||
}
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/"+bucket+"/a.txt", nil)
|
||||
policyReq, _, evaluated, err := iam.evaluateBucketPolicy(bucket, "/a.txt", string(s3_constants.ACTION_READ), "*", req, nil)
|
||||
require.NoError(t, err)
|
||||
assert.False(t, evaluated, "no statement matches an object tagged CLEAN")
|
||||
assert.Equal(t, []string{"CLEAN"}, policy_engine.RequestConditionValues(policyReq)["s3:ExistingObjectTag/ScanStatus"])
|
||||
}
|
||||
|
||||
// A tracked request is checked again on the version it is serving, not on
|
||||
// the one that became current while it ran.
|
||||
func TestEvaluateBucketPolicyRechecksTheServedVersion(t *testing.T) {
|
||||
const bucket = "scan-bucket"
|
||||
engine := NewBucketPolicyEngine()
|
||||
require.NoError(t, engine.engine.SetBucketPolicy(bucket, `{"Version":"2012-10-17","Statement":[{
|
||||
"Effect":"Deny","Principal":"*","Action":"s3:GetObject","Resource":"arn:aws:s3:::`+bucket+`/*",
|
||||
"Condition":{"StringNotEquals":{"s3:ExistingObjectTag/ScanStatus":"CLEAN"}}}]}`))
|
||||
iam := &IdentityAccessManagement{policyEngine: engine}
|
||||
iam.objectEntryForPolicy = func(*http.Request, string, string) (map[string][]byte, bool) {
|
||||
return map[string][]byte{s3_constants.AmzObjectTaggingPrefix + "ScanStatus": []byte("CLEAN")}, true
|
||||
}
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/"+bucket+"/a.txt", nil)
|
||||
req = req.WithContext(context.WithValue(req.Context(), servedObjectEntriesKey{}, &sync.Map{}))
|
||||
recordServedObjectEntry(req, bucket, "/a.txt", map[string][]byte{s3_constants.AmzObjectTaggingPrefix + "ScanStatus": []byte("INFECTED")})
|
||||
|
||||
_, allowed, evaluated, err := iam.evaluateBucketPolicy(bucket, "/a.txt", string(s3_constants.ACTION_READ), "*", req, nil)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, evaluated && !allowed, "the served version is not tagged CLEAN")
|
||||
}
|
||||
|
||||
// The first request on a bucket whose policy is not loaded yet is decided
|
||||
// like any later one.
|
||||
func TestColdBucketDecidesExistingObjectTagDenyOnObjectTags(t *testing.T) {
|
||||
const (
|
||||
bucket = "scan-bucket"
|
||||
accessKey = "LOCALSCANKEY00000001"
|
||||
secretKey = "local-scan-secret-for-loopback-only"
|
||||
)
|
||||
objects := map[string]string{"scanned/clean.txt": "CLEAN", "scanned/infected.txt": "INFECTED"}
|
||||
want := map[string]s3err.ErrorCode{"scanned/clean.txt": s3err.ErrNone, "scanned/infected.txt": s3err.ErrAccessDenied}
|
||||
|
||||
for key, code := range want {
|
||||
iam := &IdentityAccessManagement{
|
||||
hashes: make(map[string]*sync.Pool),
|
||||
hashCounters: make(map[string]*int32),
|
||||
}
|
||||
require.NoError(t, iam.loadS3ApiConfiguration(&iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{{
|
||||
Name: "app",
|
||||
Actions: []string{"Read"},
|
||||
Credentials: []*iam_pb.Credential{{AccessKey: accessKey, SecretKey: secretKey}},
|
||||
}},
|
||||
}))
|
||||
iam.policyEngine = NewBucketPolicyEngine()
|
||||
iam.primeBucketForIAM = func(b string) s3err.ErrorCode {
|
||||
require.NoError(t, iam.policyEngine.engine.SetBucketPolicy(b, `{"Version":"2012-10-17","Statement":[{
|
||||
"Effect":"Deny","Principal":"*","Action":"s3:GetObject","Resource":"arn:aws:s3:::`+b+`/scanned/*",
|
||||
"Condition":{"StringNotEquals":{"s3:ExistingObjectTag/ScanStatus":"CLEAN"}}}]}`))
|
||||
return s3err.ErrNone
|
||||
}
|
||||
iam.objectEntryForPolicy = func(r *http.Request, b, object string) (map[string][]byte, bool) {
|
||||
value, found := objects[strings.TrimPrefix(object, "/")]
|
||||
return map[string][]byte{s3_constants.AmzObjectTaggingPrefix + "ScanStatus": []byte(value)}, found
|
||||
}
|
||||
|
||||
req := mustNewRequest(http.MethodGet, "http://127.0.0.1:9000/"+bucket+"/"+key, 0, nil, t)
|
||||
require.NoError(t, signRequestV4(req, accessKey, secretKey))
|
||||
req = mux.SetURLVars(req, map[string]string{"bucket": bucket, "object": key})
|
||||
_, got := iam.authRequest(req, s3_constants.ACTION_READ)
|
||||
assert.Equal(t, code, got, key)
|
||||
}
|
||||
}
|
||||
|
||||
// A handler changing the entry it served after the check leaves the recorded
|
||||
// tags as they were authorized.
|
||||
func TestServedObjectEntryKeepsTheTagsAuthorized(t *testing.T) {
|
||||
req := httptest.NewRequest(http.MethodPut, "/scan-bucket/a.txt?tagging", nil)
|
||||
req = req.WithContext(context.WithValue(req.Context(), servedObjectEntriesKey{}, &sync.Map{}))
|
||||
extended := map[string][]byte{s3_constants.AmzObjectTaggingPrefix + "ScanStatus": []byte("CLEAN")}
|
||||
recordServedObjectEntry(req, "scan-bucket", "/a.txt", extended)
|
||||
|
||||
delete(extended, s3_constants.AmzObjectTaggingPrefix+"ScanStatus")
|
||||
extended[s3_constants.AmzObjectTaggingPrefix+"ScanStatus"] = []byte("INFECTED")
|
||||
|
||||
served, found := servedObjectEntry(req, "scan-bucket", "/a.txt")
|
||||
require.True(t, found)
|
||||
assert.Equal(t, "CLEAN", string(served[s3_constants.AmzObjectTaggingPrefix+"ScanStatus"]))
|
||||
}
|
||||
@@ -91,6 +91,10 @@ func (bpe *BucketPolicyEngine) HasPolicyForBucket(bucket string) bool {
|
||||
return bpe.engine.HasPolicyForBucket(bucket)
|
||||
}
|
||||
|
||||
func (bpe *BucketPolicyEngine) HasExistingObjectTagDeny(bucket string) bool {
|
||||
return bpe.engine.HasExistingObjectTagDeny(bucket)
|
||||
}
|
||||
|
||||
// GetBucketPolicy gets the policy for a bucket
|
||||
func (bpe *BucketPolicyEngine) GetBucketPolicy(bucket string) (*policy_engine.PolicyDocument, error) {
|
||||
return bpe.engine.GetBucketPolicy(bucket)
|
||||
|
||||
@@ -429,6 +429,13 @@ func NewS3ApiServerWithStore(router *mux.Router, option *S3ApiServerOption, expl
|
||||
_, code := s3ApiServer.getBucketConfig(bucket)
|
||||
return code
|
||||
}
|
||||
iam.objectEntryForPolicy = func(r *http.Request, bucket, object string) (map[string][]byte, bool) {
|
||||
entry, err := s3ApiServer.resolveObjectEntry(bucket, object, r.URL.Query().Get("versionId"))
|
||||
if err != nil || entry == nil {
|
||||
return nil, false
|
||||
}
|
||||
return entry.Extended, true
|
||||
}
|
||||
|
||||
// Initialize advanced IAM system if config is provided or explicitly enabled
|
||||
if option.IamConfig != "" || option.EnableIam {
|
||||
@@ -703,6 +710,7 @@ func (s3a *S3ApiServer) checkPolicyWithEntry(r *http.Request, bucket, object, ac
|
||||
//
|
||||
// Returns s3err.ErrNone if allowed, or an error code if denied or on error.
|
||||
func (s3a *S3ApiServer) recheckPolicyWithObjectEntry(r *http.Request, bucket, object, action string, objectEntry map[string][]byte, handlerName string) s3err.ErrorCode {
|
||||
recordServedObjectEntry(r, bucket, object, objectEntry)
|
||||
if isAnonymousObjectRead(r) {
|
||||
// Refined like writeAnonymousAwareNotFound's masked miss, so a denied
|
||||
// existing key and a missing key answer alike on a malformed name.
|
||||
|
||||
Reference in new issue
Block a user