Example #1
0
        /// 获取存储桶 ACL
        public void GetBucketAcl()
        {
            //.cssg-snippet-body-start:[get-bucket-acl]
            try
            {
                string bucket = "examplebucket-1250000000"; //格式:BucketName-APPID
                GetBucketACLRequest request = new GetBucketACLRequest(bucket);
                //执行请求
                GetBucketACLResult result = cosXml.GetBucketACL(request);
                //存储桶的 ACL 信息
                AccessControlPolicy acl = result.accessControlPolicy;
            }
            catch (COSXML.CosException.CosClientException clientEx)
            {
                //请求失败
                Console.WriteLine("CosClientException: " + clientEx);
            }
            catch (COSXML.CosException.CosServerException serverEx)
            {
                //请求失败
                Console.WriteLine("CosServerException: " + serverEx.GetInfo());
            }

            //.cssg-snippet-body-end
        }
        void IAccessControlPolicyRepository.Add(AccessControlPolicy policy)
        {
            var MongoDB = _mongoClient.GetDatabase(JsonAccessControlSetting.PrivacyAccessControlDbName);
            var Collec  = MongoDB.GetCollection <AccessControlPolicy>(JsonAccessControlSetting.AccessControlCollectionName);

            Collec.InsertOneAsync(policy);
        }
Example #3
0
        public void GetInfoTest()
        {
            AccessControlPolicy target = new AccessControlPolicy(); // TODO: Initialize to an appropriate value
            string expected            = string.Empty;              // TODO: Initialize to an appropriate value
            string actual;

            actual = target.GetInfo();
            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("Verify the correctness of this test method.");
        }
Example #4
0
        public void MarshalResponse(IConfig config, GetObjectAclResponse response, IDictionary <string, string> headers, Stream responseStream)
        {
            response.RequestCharged = headers.ContainsKey(AmzHeaders.XAmzRequestCharged);

            XmlSerializer s = new XmlSerializer(typeof(AccessControlPolicy));

            using (XmlTextReader r = new XmlTextReader(responseStream))
            {
                r.Namespaces = true;

                AccessControlPolicy aclOutput = (AccessControlPolicy)s.Deserialize(r);

                if (aclOutput.Owner != null)
                {
                    response.Owner      = new S3Identity();
                    response.Owner.Id   = aclOutput.Owner.Id;
                    response.Owner.Name = aclOutput.Owner.DisplayName;
                }

                if (aclOutput.AccessControlList?.Grants != null)
                {
                    response.Grants = new List <S3Grant>(aclOutput.AccessControlList.Grants.Sum(x => x.Grantee.Count));

                    foreach (Grant grant in aclOutput.AccessControlList.Grants)
                    {
                        foreach (GranteeBase grantee in grant.Grantee)
                        {
                            S3Grant s3Grant = new S3Grant();
                            s3Grant.Permission = ValueHelper.ParseEnum <Permission>(grant.Permission);

                            if (grantee is Group grantGroup)
                            {
                                s3Grant.Uri  = grantGroup.Uri;
                                s3Grant.Type = GrantType.Group;
                            }
                            else if (grantee is CanonicalUser grantUser)
                            {
                                s3Grant.Id   = grantUser.Id;
                                s3Grant.Name = grantUser.DisplayName;
                                s3Grant.Type = GrantType.User;
                            }

                            response.Grants.Add(s3Grant);
                        }
                    }
                }
                else
                {
                    response.Grants = Array.Empty <S3Grant>();
                }
            }
        }
Example #5
0
        bool IConditionalExpressionService.IsAccessControlPolicyRelateToContext(AccessControlPolicy policy, JObject user, JObject resource, JObject environment)
        {
            if (CheckRelativeFunction(policy.Target, user, resource, environment) == true)
            {
                return(true);
            }

            foreach (var rule in policy.Rules)
            {
                if (CheckRelativeFunction(rule.Condition, user, resource, environment) == true)
                {
                    return(true);
                }
            }
            return(false);
        }
Example #6
0
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
        static async Task <AccessControlPolicy> ObjectReadAcl(S3Context ctx)
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
        {
            Console.WriteLine("ObjectReadAcl: " + ctx.Request.Bucket + "/" + ctx.Request.Key);

            AccessControlList acl = new AccessControlList(
                new List <Grant>()
            {
                new Grant(_Grantee, "FULL_CONTROL")
            });

            AccessControlPolicy policy = new AccessControlPolicy(
                _Owner,
                acl);

            return(policy);
        }
Example #7
0
        /// <summary>
        /// Get bucket ACL
        /// </summary>
        /// <param name="bucket">NAme of bucket to retrieve canned ACL</param>
        /// <returns>Canned ACL</returns>
        public Acl GetBucketAcl(string bucket)
        {
            var request  = new RestRequest(bucket + "?acl", Method.GET);
            var response = client.Execute(request);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                var content      = StripXmlnsXsi(response.Content);
                var contentBytes = System.Text.Encoding.UTF8.GetBytes(content);
                var stream       = new MemoryStream(contentBytes);
                AccessControlPolicy bucketList = (AccessControlPolicy)(new XmlSerializer(typeof(AccessControlPolicy)).Deserialize(stream));

                bool publicRead        = false;
                bool publicWrite       = false;
                bool authenticatedRead = false;
                foreach (var x in bucketList.Grants)
                {
                    if ("http://acs.amazonaws.com/groups/global/AllUsers".Equals(x.Grantee.URI) && x.Permission.Equals("READ"))
                    {
                        publicRead = true;
                    }
                    if ("http://acs.amazonaws.com/groups/global/AllUsers".Equals(x.Grantee.URI) && x.Permission.Equals("WRITE"))
                    {
                        publicWrite = true;
                    }
                    if ("http://acs.amazonaws.com/groups/global/AuthenticatedUsers".Equals(x.Grantee.URI) && x.Permission.Equals("READ"))
                    {
                        authenticatedRead = true;
                    }
                }
                if (publicRead && publicWrite && !authenticatedRead)
                {
                    return(Acl.PublicReadWrite);
                }
                if (publicRead && !publicWrite && !authenticatedRead)
                {
                    return(Acl.PublicRead);
                }
                if (!publicRead && !publicWrite && authenticatedRead)
                {
                    return(Acl.AuthenticatedRead);
                }
                return(Acl.Private);
            }
            throw ParseError(response);
        }
Example #8
0
        public void getBucketAcl()
        {
            //.cssg-snippet-body-start:[get-bucket-acl]
            CosXmlConfig config = new CosXmlConfig.Builder()
                                  .SetConnectionTimeoutMs(60000) //设置连接超时时间,单位毫秒,默认45000ms
                                  .SetReadWriteTimeoutMs(40000)  //设置读写超时时间,单位毫秒,默认45000ms
                                  .IsHttps(true)                 //设置默认 HTTPS 请求
                                  .SetAppid("1253653367")        //设置腾讯云账户的账户标识 APPID
                                  .SetRegion("ap-guangzhou")     //设置一个默认的存储桶地域
                                  .Build();

            string secretId       = Environment.GetEnvironmentVariable("COS_KEY");    //云 API 密钥 SecretId
            string secretKey      = Environment.GetEnvironmentVariable("COS_SECRET"); //云 API 密钥 SecretKey
            long   durationSecond = 600;                                              //每次请求签名有效时长,单位为秒
            QCloudCredentialProvider qCloudCredentialProvider = new DefaultQCloudCredentialProvider(secretId,
                                                                                                    secretKey, durationSecond);

            CosXml cosXml = new CosXmlServer(config, qCloudCredentialProvider);

            try
            {
                string bucket = "bucket-cssg-test-dotnet-1253653367"; //格式:BucketName-APPID
                GetBucketACLRequest request = new GetBucketACLRequest(bucket);
                //设置签名有效时长
                request.SetSign(TimeUtils.GetCurrentTime(TimeUnit.SECONDS), 600);
                //执行请求
                GetBucketACLResult result = cosXml.GetBucketACL(request);
                //存储桶的 ACL 信息
                AccessControlPolicy acl = result.accessControlPolicy;
            }
            catch (COSXML.CosException.CosClientException clientEx)
            {
                //请求失败
                Console.WriteLine("CosClientException: " + clientEx);
                Assert.Null(clientEx);
            }
            catch (COSXML.CosException.CosServerException serverEx)
            {
                //请求失败
                Console.WriteLine("CosServerException: " + serverEx.GetInfo());
                Assert.Null(serverEx);
            }
            //.cssg-snippet-body-end
        }
Example #9
0
        public void testAccessControlPolicy()
        {
            AccessControlPolicy accessControlPolicy = new AccessControlPolicy();

            accessControlPolicy.owner                    = new AccessControlPolicy.Owner();
            accessControlPolicy.accessControlList        = new AccessControlPolicy.AccessControlList();
            accessControlPolicy.accessControlList.grants = new List <AccessControlPolicy.Grant>();
            accessControlPolicy.owner.id                 = "qcs::cam::uin/<OwnerUin>:uin/<SubUin>";
            accessControlPolicy.owner.displayName        = "qcs::cam::uin/<OwnerUin>:uin/<SubUin>";
            for (int i = 0; i < 3; i++)
            {
                AccessControlPolicy.Grant grant = new AccessControlPolicy.Grant();
                grant.grantee             = new AccessControlPolicy.Grantee();
                grant.grantee.id          = "qcs::cam::uin/<OwnerUin>:uin/<SubUin>";
                grant.grantee.displayName = "qcs::cam::uin/<OwnerUin>:uin/<SubUin>";
                grant.permission          = "permission";
                accessControlPolicy.accessControlList.grants.Add(grant);
            }
        }
        public void Post([FromBody] AccessControlPolicyInsertCommand command)
        {
            bool IsResourceRequired = false;

            if (command.Target.Contains("\"Resource."))
            {
                IsResourceRequired = true;
            }

            var accessControlRules = new List <AccessControlRule>();

            foreach (var rule in command.Rules)
            {
                var condition         = _conditionalExpressionService.Parse(rule.Condition);
                var accessControlRule = new AccessControlRule()
                {
                    Id        = rule.RuleID,
                    Effect    = rule.Effect,
                    Condition = condition
                };
                accessControlRules.Add(accessControlRule);

                if (!IsResourceRequired)
                {
                    IsResourceRequired = rule.Condition.Contains("\"Resource.");
                }
            }
            var target             = _conditionalExpressionService.Parse(command.Target);
            var accessControlModel = new AccessControlPolicy()
            {
                PolicyId       = command.PolicyID,
                CollectionName = command.CollectionName,
                Action         = command.Action,
                Description    = command.Description,
                RuleCombining  = command.RuleCombining,
                Target         = target,
                Rules          = accessControlRules,
                IsAttributeResourceRequired = IsResourceRequired
            };

            _accessControlPolicyRepository.Add(accessControlModel);
        }
Example #11
0
        private void GetBucketACL()
        {
            try
            {
                GetBucketACLRequest request = new GetBucketACLRequest(bucket);

                //执行请求
                GetBucketACLResult result = cosXml.GetBucketACL(request);

                AccessControlPolicy acl = result.accessControlPolicy;

                // Console.WriteLine(result.GetResultInfo());
                Assert.IsNotEmpty(result.GetResultInfo());

                Assert.AreEqual(result.httpCode, 200);
                Assert.NotNull(acl.owner);
                Assert.NotNull(acl.owner.id);
                Assert.NotNull(acl.owner.displayName);
                Assert.NotNull(acl.accessControlList);
                Assert.NotNull(acl.accessControlList.grants);
                Assert.NotZero(acl.accessControlList.grants.Count);
                Assert.NotNull(acl.accessControlList.grants[0].permission);
                Assert.NotNull(acl.accessControlList.grants[0].grantee);
                Assert.NotNull(acl.accessControlList.grants[0].grantee.id);
                Assert.NotNull(acl.accessControlList.grants[0].grantee.displayName);
            }
            catch (COSXML.CosException.CosClientException clientEx)
            {
                Console.WriteLine("CosClientException: " + clientEx.StackTrace);
                Assert.Fail();
            }
            catch (COSXML.CosException.CosServerException serverEx)
            {
                Console.WriteLine("CosServerException: " + serverEx.GetInfo());
                Assert.Fail();
            }
        }
Example #12
0
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
        static async Task ObjectWriteAcl(S3Context ctx, AccessControlPolicy acp)
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
        {
            Console.WriteLine("ObjectWriteAcl: " + ctx.Request.Bucket + "/" + ctx.Request.Key);
            Console.WriteLine(ctx.Request.DataAsString + Environment.NewLine);
        }
        public async Task <AccessMode> GetObjectAclAsync(string bucketName, string objectName)
        {
            if (string.IsNullOrEmpty(bucketName))
            {
                throw new ArgumentNullException(nameof(bucketName));
            }
            if (string.IsNullOrEmpty(objectName))
            {
                throw new ArgumentNullException(nameof(objectName));
            }
            bool isPublicRead  = false;
            bool isPublicWrite = false;

            //此处存在一个问题
            //当储存桶权限设置为公共读,对象权限设置为继承,但是获取到的权限仍然是私有的。但是此时对象是可以呗公共访问到。
            //同样,储存桶设置为公共读,对象设置为私有,获取到的权限仍然是私有的。

            //获取储存桶权限
            //AccessMode bucketMode = await GetBucketAclAsync(bucketName);
            //switch (bucketMode)
            //{
            //    case AccessMode.PublicRead:
            //        {
            //            isPublicRead = true;
            //            isPublicWrite = false;
            //            break;
            //        }
            //    case AccessMode.PublicReadWrite:
            //        {
            //            isPublicRead = true;
            //            isPublicWrite = true;
            //            break;
            //        }
            //    case AccessMode.Default:
            //    case AccessMode.Private:
            //    default:
            //        {
            //            isPublicRead = false;
            //            isPublicWrite = false;
            //            break;
            //        }
            //}

            bucketName = ConvertBucketName(bucketName);
            GetObjectACLRequest request = new GetObjectACLRequest(bucketName, objectName);
            GetObjectACLResult  result  = _client.GetObjectACL(request);
            AccessControlPolicy acl     = result.accessControlPolicy;

            if (acl != null &&
                acl.accessControlList != null &&
                acl.accessControlList.grants != null &&
                acl.accessControlList.grants.Count > 0)
            {
                foreach (var item in acl.accessControlList.grants)
                {
                    if (string.IsNullOrEmpty(item.grantee.uri))
                    {
                        continue;
                    }
                    if (item.grantee.uri.Contains("allusers", StringComparison.OrdinalIgnoreCase))
                    {
                        switch (item.permission.ToLower())
                        {
                        case "read":
                            isPublicRead = true;
                            break;

                        case "write":
                            isPublicWrite = true;
                            break;
                        }
                    }
                }
            }

            //结果
            if (isPublicRead && !isPublicWrite)
            {
                return(await Task.FromResult(AccessMode.PublicRead));
            }
            else if (isPublicRead && isPublicWrite)
            {
                return(await Task.FromResult(AccessMode.PublicReadWrite));
            }
            else if (!isPublicRead && isPublicWrite)
            {
                return(await Task.FromResult(AccessMode.Private));
            }
            else
            {
                return(await Task.FromResult(AccessMode.Private));
            }
        }
 public bool IsAccessControlPolicyRelateToContext(AccessControlPolicy policy, JObject user, JObject resource, JObject environment)
 {
     return(true);
 }
Example #15
0
        public Task <AccessMode> GetBucketAclAsync(string bucketName)
        {
            if (string.IsNullOrEmpty(bucketName))
            {
                throw new ArgumentNullException(nameof(bucketName));
            }
            bucketName = ConvertBucketName(bucketName);
            GetBucketACLRequest request = new GetBucketACLRequest(bucketName);
            //执行请求
            GetBucketACLResult result = _client.GetBucketACL(request);
            //存储桶的 ACL 信息
            AccessControlPolicy acl = result.accessControlPolicy;

            bool isPublicRead  = false;
            bool isPublicWrite = false;

            if (acl != null &&
                acl.accessControlList != null &&
                acl.accessControlList.grants != null &&
                acl.accessControlList.grants.Count > 0)
            {
                foreach (var item in acl.accessControlList.grants)
                {
                    if (string.IsNullOrEmpty(item.grantee.uri))
                    {
                        continue;
                    }
                    if (item.grantee.uri.Contains("allusers", StringComparison.OrdinalIgnoreCase))
                    {
                        switch (item.permission.ToLower())
                        {
                        case "read":
                            isPublicRead = true;
                            break;

                        case "write":
                            isPublicWrite = true;
                            break;
                        }
                    }
                }
            }

            //结果
            if (isPublicRead && !isPublicWrite)
            {
                return(Task.FromResult(AccessMode.PublicRead));
            }
            else if (isPublicRead && isPublicWrite)
            {
                return(Task.FromResult(AccessMode.PublicReadWrite));
            }
            else if (!isPublicRead && isPublicWrite)
            {
                return(Task.FromResult(AccessMode.Private));
            }
            else
            {
                return(Task.FromResult(AccessMode.Private));
            }
        }
Example #16
0
        private async Task RequestHandler(HttpContext ctx)
        {
            if (ctx == null)
            {
                throw new ArgumentNullException(nameof(ctx));
            }
            DateTime  startTime = DateTime.Now;
            S3Context s3ctx     = null;

            try
            {
                s3ctx = new S3Context(ctx, _BaseDomains, null, (Logging.S3Requests ? Logger : null));
                s3ctx.Response.Headers.Add("x-amz-request-id", s3ctx.Request.RequestId);
                s3ctx.Response.Headers.Add("x-amz-id-2", s3ctx.Request.RequestId);
            }
            catch (Exception e)
            {
                if (Logging.Exceptions)
                {
                    Logger?.Invoke(_Header + "Exception:" + Environment.NewLine + Common.SerializeJson(e, true));
                }

                return;
            }

            bool                    success           = false;
            bool                    exists            = false;
            S3Object                s3obj             = null;
            ObjectMetadata          md                = null;
            AccessControlPolicy     acp               = null;
            LegalHold               legalHold         = null;
            Retention               retention         = null;
            Tagging                 tagging           = null;
            ListAllMyBucketsResult  buckets           = null;
            ListBucketResult        listBucketResult  = null;
            ListVersionsResult      listVersionResult = null;
            LocationConstraint      location          = null;
            BucketLoggingStatus     bucketLogging     = null;
            VersioningConfiguration versionConfig     = null;
            WebsiteConfiguration    wc                = null;
            DeleteMultiple          delMultiple       = null;
            DeleteResult            delResult         = null;

            try
            {
                if (Logging.HttpRequests)
                {
                    Logger?.Invoke(_Header + "HTTP request: " + Environment.NewLine + s3ctx.Http.ToJson(true));
                }

                if (Logging.S3Requests)
                {
                    Logger?.Invoke(_Header + "S3 request: " + Environment.NewLine + s3ctx.Request.ToJson(true));
                }

                if (PreRequestHandler != null)
                {
                    success = await PreRequestHandler(s3ctx).ConfigureAwait(false);

                    if (success)
                    {
                        await s3ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                }

                switch (s3ctx.Request.RequestType)
                {
                    #region Service

                case S3RequestType.ListBuckets:
                    if (Service.ListBuckets != null)
                    {
                        buckets = await Service.ListBuckets(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "application/xml";
                        await ctx.Response.Send(Common.SerializeXml(buckets)).ConfigureAwait(false);

                        return;
                    }
                    break;

                    #endregion

                    #region Bucket

                case S3RequestType.BucketDelete:
                    if (Bucket.Delete != null)
                    {
                        await Bucket.Delete(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 204;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketDeleteTags:
                    if (Bucket.DeleteTagging != null)
                    {
                        await Bucket.DeleteTagging(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 204;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketDeleteWebsite:
                    if (Bucket.DeleteWebsite != null)
                    {
                        await Bucket.DeleteWebsite(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 204;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketExists:
                    if (Bucket.Exists != null)
                    {
                        exists = await Bucket.Exists(s3ctx).ConfigureAwait(false);

                        if (exists)
                        {
                            ctx.Response.StatusCode  = 200;
                            ctx.Response.ContentType = "text/plain";
                            await ctx.Response.Send().ConfigureAwait(false);
                        }
                        else
                        {
                            ctx.Response.StatusCode  = 404;
                            ctx.Response.ContentType = "text/plain";
                            await ctx.Response.Send().ConfigureAwait(false);
                        }
                        return;
                    }
                    break;

                case S3RequestType.BucketRead:
                    if (Bucket.Read != null)
                    {
                        listBucketResult = await Bucket.Read(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "application/xml";
                        await ctx.Response.Send(Common.SerializeXml(listBucketResult)).ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketReadAcl:
                    if (Bucket.ReadAcl != null)
                    {
                        acp = await Bucket.ReadAcl(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "application/xml";
                        await ctx.Response.Send(Common.SerializeXml(acp)).ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketReadLocation:
                    if (Bucket.ReadLocation != null)
                    {
                        location = await Bucket.ReadLocation(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "application/xml";
                        await ctx.Response.Send(Common.SerializeXml(location)).ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketReadLogging:
                    if (Bucket.ReadLogging != null)
                    {
                        bucketLogging = await Bucket.ReadLogging(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "application/xml";
                        await ctx.Response.Send(Common.SerializeXml(bucketLogging)).ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketReadTags:
                    if (Bucket.ReadTagging != null)
                    {
                        tagging = await Bucket.ReadTagging(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "application/xml";
                        await ctx.Response.Send(Common.SerializeXml(tagging)).ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketReadVersioning:
                    if (Bucket.ReadVersioning != null)
                    {
                        versionConfig = await Bucket.ReadVersioning(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "application/xml";
                        await ctx.Response.Send(Common.SerializeXml(versionConfig)).ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketReadVersions:
                    if (Bucket.ReadVersions != null)
                    {
                        listVersionResult = await Bucket.ReadVersions(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "application/xml";
                        await ctx.Response.Send(Common.SerializeXml(listVersionResult)).ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketReadWebsite:
                    if (Bucket.ReadWebsite != null)
                    {
                        wc = await Bucket.ReadWebsite(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "application/xml";
                        await ctx.Response.Send(Common.SerializeXml(wc)).ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketWrite:
                    if (Bucket.Write != null)
                    {
                        await Bucket.Write(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketWriteAcl:
                    if (Bucket.WriteAcl != null)
                    {
                        try
                        {
                            acp = Common.DeserializeXml <AccessControlPolicy>(s3ctx.Request.DataAsString);
                        }
                        catch (InvalidOperationException ioe)
                        {
                            ioe.Data.Add("Context", s3ctx);
                            ioe.Data.Add("RequestBody", s3ctx.Request.DataAsString);
                            Logger?.Invoke(_Header + "XML exception: " + Environment.NewLine + Common.SerializeJson(ioe, true));
                            await s3ctx.Response.Send(S3Objects.ErrorCode.MalformedXML).ConfigureAwait(false);

                            return;
                        }

                        await Bucket.WriteAcl(s3ctx, acp).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketWriteLogging:
                    if (Bucket.WriteLogging != null)
                    {
                        try
                        {
                            bucketLogging = Common.DeserializeXml <BucketLoggingStatus>(s3ctx.Request.DataAsString);
                        }
                        catch (InvalidOperationException ioe)
                        {
                            ioe.Data.Add("Context", s3ctx);
                            ioe.Data.Add("RequestBody", s3ctx.Request.DataAsString);
                            Logger?.Invoke(_Header + "XML exception: " + Environment.NewLine + Common.SerializeJson(ioe, true));
                            await s3ctx.Response.Send(S3Objects.ErrorCode.MalformedXML).ConfigureAwait(false);

                            return;
                        }

                        await Bucket.WriteLogging(s3ctx, bucketLogging).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketWriteTags:
                    if (Bucket.WriteTagging != null)
                    {
                        try
                        {
                            tagging = Common.DeserializeXml <Tagging>(s3ctx.Request.DataAsString);
                        }
                        catch (InvalidOperationException ioe)
                        {
                            ioe.Data.Add("Context", s3ctx);
                            ioe.Data.Add("RequestBody", s3ctx.Request.DataAsString);
                            Logger?.Invoke(_Header + "XML exception: " + Environment.NewLine + Common.SerializeJson(ioe, true));
                            await s3ctx.Response.Send(S3Objects.ErrorCode.MalformedXML).ConfigureAwait(false);

                            return;
                        }

                        await Bucket.WriteTagging(s3ctx, tagging).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketWriteVersioning:
                    if (Bucket.WriteVersioning != null)
                    {
                        try
                        {
                            versionConfig = Common.DeserializeXml <VersioningConfiguration>(s3ctx.Request.DataAsString);
                        }
                        catch (InvalidOperationException ioe)
                        {
                            ioe.Data.Add("Context", s3ctx);
                            ioe.Data.Add("RequestBody", s3ctx.Request.DataAsString);
                            Logger?.Invoke(_Header + "XML exception: " + Environment.NewLine + Common.SerializeJson(ioe, true));
                            await s3ctx.Response.Send(S3Objects.ErrorCode.MalformedXML).ConfigureAwait(false);

                            return;
                        }

                        await Bucket.WriteVersioning(s3ctx, versionConfig).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketWriteWebsite:
                    if (Bucket.WriteWebsite != null)
                    {
                        try
                        {
                            wc = Common.DeserializeXml <WebsiteConfiguration>(s3ctx.Request.DataAsString);
                        }
                        catch (InvalidOperationException ioe)
                        {
                            ioe.Data.Add("Context", s3ctx);
                            ioe.Data.Add("RequestBody", s3ctx.Request.DataAsString);
                            Logger?.Invoke(_Header + "XML exception: " + Environment.NewLine + Common.SerializeJson(ioe, true));
                            await s3ctx.Response.Send(S3Objects.ErrorCode.MalformedXML).ConfigureAwait(false);

                            return;
                        }

                        await Bucket.WriteWebsite(s3ctx, wc).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                    #endregion

                    #region Object

                case S3RequestType.ObjectDelete:
                    if (Object.Delete != null)
                    {
                        await Object.Delete(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 204;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.ObjectDeleteMultiple:
                    if (Object.DeleteMultiple != null)
                    {
                        try
                        {
                            delMultiple = Common.DeserializeXml <DeleteMultiple>(s3ctx.Request.DataAsString);
                        }
                        catch (InvalidOperationException ioe)
                        {
                            ioe.Data.Add("Context", s3ctx);
                            ioe.Data.Add("RequestBody", s3ctx.Request.DataAsString);
                            Logger?.Invoke(_Header + "XML exception: " + Environment.NewLine + Common.SerializeJson(ioe, true));
                            await s3ctx.Response.Send(S3Objects.ErrorCode.MalformedXML).ConfigureAwait(false);

                            return;
                        }

                        delResult = await Object.DeleteMultiple(s3ctx, delMultiple).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "application/xml";
                        await ctx.Response.Send(Common.SerializeXml(delResult)).ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.ObjectDeleteTags:
                    if (Object.DeleteTagging != null)
                    {
                        await Object.DeleteTagging(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 204;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.ObjectExists:
                    if (Object.Exists != null)
                    {
                        md = await Object.Exists(s3ctx).ConfigureAwait(false);

                        if (md != null)
                        {
                            if (!String.IsNullOrEmpty(md.ETag))
                            {
                                ctx.Response.Headers.Add("ETag", md.ETag);
                            }
                            ctx.Response.Headers.Add("Last-Modified", md.LastModified.ToString());
                            ctx.Response.Headers.Add("x-amz-storage-class", md.StorageClass);
                            ctx.Response.StatusCode    = 200;
                            ctx.Response.ContentLength = md.Size;
                            ctx.Response.ContentType   = md.ContentType;
                            await ctx.Response.Send(md.Size).ConfigureAwait(false);
                        }
                        else
                        {
                            ctx.Response.StatusCode = 404;
                            await ctx.Response.Send().ConfigureAwait(false);
                        }
                        return;
                    }
                    break;

                case S3RequestType.ObjectRead:
                    if (Object.Read != null)
                    {
                        s3obj = await Object.Read(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode    = 200;
                        ctx.Response.ContentType   = s3obj.ContentType;
                        ctx.Response.ContentLength = s3obj.Size;
                        await ctx.Response.Send(s3obj.Size, s3obj.Data).ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.ObjectReadAcl:
                    if (Object.ReadAcl != null)
                    {
                        acp = await Object.ReadAcl(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "application/xml";
                        await ctx.Response.Send(Common.SerializeXml(acp)).ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.ObjectReadLegalHold:
                    if (Object.ReadLegalHold != null)
                    {
                        legalHold = await Object.ReadLegalHold(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "application/xml";
                        await ctx.Response.Send(Common.SerializeXml(legalHold)).ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.ObjectReadRange:
                    if (Object.ReadRange != null)
                    {
                        s3obj = await Object.ReadRange(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode    = 200;
                        ctx.Response.ContentType   = s3obj.ContentType;
                        ctx.Response.ContentLength = s3obj.Size;
                        await ctx.Response.Send(s3obj.Size, s3obj.Data).ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.ObjectReadRetention:
                    if (Object.ReadRetention != null)
                    {
                        retention = await Object.ReadRetention(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "application/xml";
                        await ctx.Response.Send(Common.SerializeXml(retention)).ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.ObjectReadTags:
                    if (Object.ReadTagging != null)
                    {
                        tagging = await Object.ReadTagging(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "application/xml";
                        await ctx.Response.Send(Common.SerializeXml(tagging)).ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.ObjectWrite:
                    if (Object.Write != null)
                    {
                        await Object.Write(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.ObjectWriteAcl:
                    if (Object.WriteAcl != null)
                    {
                        try
                        {
                            acp = Common.DeserializeXml <AccessControlPolicy>(s3ctx.Request.DataAsString);
                        }
                        catch (InvalidOperationException ioe)
                        {
                            ioe.Data.Add("Context", s3ctx);
                            ioe.Data.Add("RequestBody", s3ctx.Request.DataAsString);
                            Logger?.Invoke(_Header + "XML exception: " + Environment.NewLine + Common.SerializeJson(ioe, true));
                            await s3ctx.Response.Send(S3Objects.ErrorCode.MalformedXML).ConfigureAwait(false);

                            return;
                        }

                        await Object.WriteAcl(s3ctx, acp).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.ObjectWriteLegalHold:
                    if (Object.WriteLegalHold != null)
                    {
                        try
                        {
                            legalHold = Common.DeserializeXml <LegalHold>(s3ctx.Request.DataAsString);
                        }
                        catch (InvalidOperationException ioe)
                        {
                            ioe.Data.Add("Context", s3ctx);
                            ioe.Data.Add("RequestBody", s3ctx.Request.DataAsString);
                            Logger?.Invoke(_Header + "XML exception: " + Environment.NewLine + Common.SerializeJson(ioe, true));
                            await s3ctx.Response.Send(S3Objects.ErrorCode.MalformedXML).ConfigureAwait(false);

                            return;
                        }

                        await Object.WriteLegalHold(s3ctx, legalHold).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.ObjectWriteRetention:
                    if (Object.WriteRetention != null)
                    {
                        try
                        {
                            retention = Common.DeserializeXml <Retention>(s3ctx.Request.DataAsString);
                        }
                        catch (InvalidOperationException ioe)
                        {
                            ioe.Data.Add("Context", s3ctx);
                            ioe.Data.Add("RequestBody", s3ctx.Request.DataAsString);
                            Logger?.Invoke(_Header + "XML exception: " + Environment.NewLine + Common.SerializeJson(ioe, true));
                            await s3ctx.Response.Send(S3Objects.ErrorCode.MalformedXML).ConfigureAwait(false);

                            return;
                        }

                        await Object.WriteRetention(s3ctx, retention).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.ObjectWriteTags:
                    if (Object.WriteTagging != null)
                    {
                        try
                        {
                            tagging = Common.DeserializeXml <Tagging>(s3ctx.Request.DataAsString);
                        }
                        catch (InvalidOperationException ioe)
                        {
                            ioe.Data.Add("Context", s3ctx);
                            ioe.Data.Add("RequestBody", s3ctx.Request.DataAsString);
                            Logger?.Invoke(_Header + "XML exception: " + Environment.NewLine + Common.SerializeJson(ioe, true));
                            await s3ctx.Response.Send(S3Objects.ErrorCode.MalformedXML).ConfigureAwait(false);

                            return;
                        }

                        await Object.WriteTagging(s3ctx, tagging).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                    #endregion
                }

                if (DefaultRequestHandler != null)
                {
                    await DefaultRequestHandler(s3ctx).ConfigureAwait(false);

                    return;
                }

                await s3ctx.Response.Send(S3Objects.ErrorCode.InvalidRequest).ConfigureAwait(false);

                return;
            }
            catch (S3Exception s3e)
            {
                if (Logging.Exceptions)
                {
                    Logger?.Invoke(_Header + "S3 exception:" + Environment.NewLine + Common.SerializeJson(s3e, true));
                }

                await s3ctx.Response.Send(s3e.Error).ConfigureAwait(false);

                return;
            }
            catch (Exception e)
            {
                if (Logging.Exceptions)
                {
                    Logger?.Invoke(_Header + "exception:" + Environment.NewLine + Common.SerializeJson(e, true));
                }

                await s3ctx.Response.Send(S3Objects.ErrorCode.InternalError).ConfigureAwait(false);

                return;
            }
            finally
            {
                if (Logging.HttpRequests)
                {
                    Logger?.Invoke(
                        _Header +
                        "[" +
                        ctx.Request.Source.IpAddress + ":" +
                        ctx.Request.Source.Port +
                        "] " +
                        ctx.Request.Method.ToString() + " " +
                        ctx.Request.Url.RawWithoutQuery + " " +
                        s3ctx.Response.StatusCode +
                        " [" + Common.TotalMsFrom(startTime) + "ms]");
                }

                if (PostRequestHandler != null)
                {
                    await PostRequestHandler(s3ctx).ConfigureAwait(false);
                }
            }
        }
Example #17
0
        public void AccessControlPolicyConstructorTest()
        {
            AccessControlPolicy target = new AccessControlPolicy();

            Assert.Inconclusive("TODO: Implement code to verify target");
        }
Example #18
0
 internal override void ParseResponseBody(System.IO.Stream inputStream, string contentType, long contentLength)
 {
     accessControlPolicy = new AccessControlPolicy();
     XmlParse.ParseAccessControlPolicy(inputStream, accessControlPolicy);
 }