public async Task SetClearLegalHold()
        {
            // create a blob container
            string                containerName = Recording.GenerateAssetName("testblob");
            BlobContainerData     data          = new BlobContainerData();
            BlobContainerResource container     = (await _blobContainerCollection.CreateOrUpdateAsync(WaitUntil.Completed, containerName, new BlobContainerData())).Value;

            //set legal hold
            LegalHold legalHoldModel = new LegalHold(new List <string> {
                "tag1", "tag2", "tag3"
            });
            LegalHold legalHold = await container.SetLegalHoldAsync(legalHoldModel);

            //validate
            Assert.True(legalHold.HasLegalHold);
            Assert.AreEqual(new List <string> {
                "tag1", "tag2", "tag3"
            }, legalHold.Tags);

            //clear legal hold
            legalHold = await container.ClearLegalHoldAsync(legalHoldModel);

            //validate
            Assert.False(legalHold.HasLegalHold);
            Assert.AreEqual(0, legalHold.Tags.Count);
        }
Exemple #2
0
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
        static async Task <LegalHold> ObjectReadLegalHold(S3Context ctx)
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
        {
            Console.WriteLine("ObjectReadLegalHold: " + ctx.Request.Bucket + "/" + ctx.Request.Key);

            LegalHold legalHold = new LegalHold("OFF");

            return(legalHold);
        }
        public static void PutOnLegalHold(Guid custodianGuid, TimeSpan?period = null)
        {
            var legalHold = new LegalHold
            {
                DateExpiredUtc = period.HasValue ? DateTime.UtcNow + period.Value : (DateTime?)null,
                User           = new User
                {
                    Id = custodianGuid
                }
            };

            HttpPost(LegalHoldsUrl, new[] { legalHold });
        }
Exemple #4
0
        public void BlobContainersSetLegalHoldTest()
        {
            var handler = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var resourcesClient   = StorageManagementTestUtilities.GetResourceManagementClient(context, handler);
                var storageMgmtClient = StorageManagementTestUtilities.GetStorageManagementClient(context, handler);

                // Create resource group
                var rgName = StorageManagementTestUtilities.CreateResourceGroup(resourcesClient);

                // Create storage account
                string accountName = TestUtilities.GenerateName("sto");
                var    parameters  = StorageManagementTestUtilities.GetDefaultStorageAccountParameters();
                parameters.Kind = Kind.StorageV2;
                var account = storageMgmtClient.StorageAccounts.Create(rgName, accountName, parameters);
                StorageManagementTestUtilities.VerifyAccountProperties(account, false);

                // implement case
                try
                {
                    string        containerName = TestUtilities.GenerateName("container");
                    BlobContainer blobContainer = storageMgmtClient.BlobContainers.Create(rgName, accountName, containerName);
                    Assert.Null(blobContainer.Metadata);
                    Assert.Null(blobContainer.PublicAccess);

                    LegalHold legalHold = storageMgmtClient.BlobContainers.SetLegalHold(rgName, accountName, containerName, new List <string> {
                        "tag1", "tag2", "tag3"
                    });
                    Assert.True(legalHold.HasLegalHold);
                    Assert.Equal(new List <string> {
                        "tag1", "tag2", "tag3"
                    }, legalHold.Tags);

                    legalHold = storageMgmtClient.BlobContainers.ClearLegalHold(rgName, accountName, containerName, new List <string> {
                        "tag1", "tag2", "tag3"
                    });
                    Assert.False(legalHold.HasLegalHold);
                    Assert.Equal(0, legalHold.Tags.Count);
                }
                finally
                {
                    // clean up
                    storageMgmtClient.StorageAccounts.Delete(rgName, accountName);
                    resourcesClient.ResourceGroups.Delete(rgName);
                }
            }
        }
        public void MarshalResponse(IConfig config, GetObjectLegalHoldRequest request, GetObjectLegalHoldResponse response, IDictionary <string, string> headers, Stream responseStream)
        {
            response.RequestCharged = headers.ContainsKey(AmzHeaders.XAmzRequestCharged);

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

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

                LegalHold legalHoldOutput = (LegalHold)s.Deserialize(r);
                response.LegalHold = legalHoldOutput.Status == "ON";
            }
        }
Exemple #6
0
        public virtual Response <LegalHold> ClearLegalHold(LegalHold legalHold, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(legalHold, nameof(legalHold));

            using var scope = _blobContainerClientDiagnostics.CreateScope("BlobContainer.ClearLegalHold");
            scope.Start();
            try
            {
                var response = _blobContainerRestClient.ClearLegalHold(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Parent.Name, Id.Name, legalHold, cancellationToken);
                return(response);
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            LegalHold hold = value as LegalHold;

            if (hold != null)
            {
                string returnValue = hold.LegalCaseTitle;

                if (!string.IsNullOrEmpty(hold.LegalCaseNumber))
                {
                    returnValue += string.Format(" ({0})", hold.LegalCaseNumber);
                }

                return(returnValue);
            }

            return(DependencyProperty.UnsetValue);
        }
        public virtual Response <LegalHold> ClearLegalHold(LegalHold legalHold, CancellationToken cancellationToken = default)
        {
            if (legalHold == null)
            {
                throw new ArgumentNullException(nameof(legalHold));
            }

            using var scope = _clientDiagnostics.CreateScope("BlobContainer.ClearLegalHold");
            scope.Start();
            try
            {
                var response = _restClient.ClearLegalHold(Id.ResourceGroupName, Id.Parent.Parent.Name, Id.Parent.Name, Id.Name, legalHold, cancellationToken);
                return(response);
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }
        public virtual async Task <Response <LegalHold> > SetLegalHoldAsync(LegalHold legalHold, CancellationToken cancellationToken = default)
        {
            if (legalHold == null)
            {
                throw new ArgumentNullException(nameof(legalHold));
            }

            using var scope = _clientDiagnostics.CreateScope("BlobContainer.SetLegalHold");
            scope.Start();
            try
            {
                var response = await _restClient.SetLegalHoldAsync(Id.ResourceGroupName, Id.Parent.Parent.Name, Id.Parent.Name, Id.Name, legalHold, cancellationToken).ConfigureAwait(false);

                return(response);
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }
Exemple #10
0
        public void BlobContainersGetTest()
        {
            var handler = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var resourcesClient   = StorageManagementTestUtilities.GetResourceManagementClient(context, handler);
                var storageMgmtClient = StorageManagementTestUtilities.GetStorageManagementClient(context, handler);

                // Create resource group
                var rgName = StorageManagementTestUtilities.CreateResourceGroup(resourcesClient);

                // Create storage account
                string accountName = TestUtilities.GenerateName("sto");
                var    parameters  = StorageManagementTestUtilities.GetDefaultStorageAccountParameters();
                parameters.Kind = Kind.StorageV2;
                var account = storageMgmtClient.StorageAccounts.Create(rgName, accountName, parameters);
                StorageManagementTestUtilities.VerifyAccountProperties(account, false);

                // implement case
                try
                {
                    string        containerName = TestUtilities.GenerateName("container");
                    BlobContainer blobContainer = storageMgmtClient.BlobContainers.Create(rgName, accountName, containerName);
                    Assert.Null(blobContainer.Metadata);
                    Assert.Null(blobContainer.PublicAccess);

                    LegalHold legalHold = storageMgmtClient.BlobContainers.SetLegalHold(rgName, accountName, containerName, new List <string> {
                        "tag1", "tag2", "tag3"
                    });
                    Assert.True(legalHold.HasLegalHold);
                    Assert.Equal(new List <string> {
                        "tag1", "tag2", "tag3"
                    }, legalHold.Tags);

                    ImmutabilityPolicy immutabilityPolicy = storageMgmtClient.BlobContainers.CreateOrUpdateImmutabilityPolicy(rgName, accountName, containerName, ifMatch: "", immutabilityPeriodSinceCreationInDays: 3);
                    Assert.NotNull(immutabilityPolicy.Id);
                    Assert.NotNull(immutabilityPolicy.Type);
                    Assert.NotNull(immutabilityPolicy.Name);
                    Assert.Equal(3, immutabilityPolicy.ImmutabilityPeriodSinceCreationInDays);
                    Assert.Equal(ImmutabilityPolicyState.Unlocked, immutabilityPolicy.State);


                    immutabilityPolicy = storageMgmtClient.BlobContainers.LockImmutabilityPolicy(rgName, accountName, containerName, ifMatch: immutabilityPolicy.Etag);
                    Assert.NotNull(immutabilityPolicy.Id);
                    Assert.NotNull(immutabilityPolicy.Type);
                    Assert.NotNull(immutabilityPolicy.Name);
                    Assert.Equal(3, immutabilityPolicy.ImmutabilityPeriodSinceCreationInDays);
                    Assert.Equal(ImmutabilityPolicyState.Locked, immutabilityPolicy.State);

                    immutabilityPolicy = storageMgmtClient.BlobContainers.ExtendImmutabilityPolicy(rgName, accountName, containerName, ifMatch: immutabilityPolicy.Etag, immutabilityPeriodSinceCreationInDays: 100);
                    Assert.NotNull(immutabilityPolicy.Id);
                    Assert.NotNull(immutabilityPolicy.Type);
                    Assert.NotNull(immutabilityPolicy.Name);
                    Assert.Equal(100, immutabilityPolicy.ImmutabilityPeriodSinceCreationInDays);
                    Assert.Equal(ImmutabilityPolicyState.Locked, immutabilityPolicy.State);

                    blobContainer = storageMgmtClient.BlobContainers.Get(rgName, accountName, containerName);
                    Assert.Null(blobContainer.Metadata);
                    Assert.Equal(PublicAccess.None, blobContainer.PublicAccess);
                    Assert.Equal(3, blobContainer.ImmutabilityPolicy.UpdateHistory.Count);
                    Assert.Equal(ImmutabilityPolicyUpdateType.Put, blobContainer.ImmutabilityPolicy.UpdateHistory[0].Update);
                    Assert.Equal(ImmutabilityPolicyUpdateType.Lock, blobContainer.ImmutabilityPolicy.UpdateHistory[1].Update);
                    Assert.Equal(ImmutabilityPolicyUpdateType.Extend, blobContainer.ImmutabilityPolicy.UpdateHistory[2].Update);
                    Assert.True(blobContainer.LegalHold.HasLegalHold);
                    Assert.Equal(3, blobContainer.LegalHold.Tags.Count);
                    Assert.Equal("tag1", blobContainer.LegalHold.Tags[0].Tag);
                    Assert.Equal("tag2", blobContainer.LegalHold.Tags[1].Tag);
                    Assert.Equal("tag3", blobContainer.LegalHold.Tags[2].Tag);

                    legalHold = storageMgmtClient.BlobContainers.ClearLegalHold(rgName, accountName, containerName, new List <string> {
                        "tag1", "tag2", "tag3"
                    });
                    Assert.False(legalHold.HasLegalHold);
                    //Assert.Equal(null, legalHold.Tags);

                    storageMgmtClient.BlobContainers.Delete(rgName, accountName, containerName);
                }
                finally
                {
                    // clean up
                    storageMgmtClient.StorageAccounts.Delete(rgName, accountName);
                    resourcesClient.ResourceGroups.Delete(rgName);
                }
            }
        }
Exemple #11
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);
                }
            }
        }
        public async Task GetBlobContainer()
        {
            string containerName            = Recording.GenerateAssetName("testblob");
            BlobContainerResource container = (await _blobContainerCollection.CreateOrUpdateAsync(WaitUntil.Completed, containerName, new BlobContainerData())).Value;

            Assert.IsEmpty(container.Data.Metadata);
            Assert.Null(container.Data.PublicAccess);

            LegalHold legalHoldModel = new LegalHold(new List <string> {
                "tag1", "tag2", "tag3"
            });
            LegalHold legalHold = await container.SetLegalHoldAsync(legalHoldModel);

            Assert.IsTrue(legalHold.HasLegalHold);
            Assert.AreEqual(new List <string> {
                "tag1", "tag2", "tag3"
            }, legalHold.Tags);

            ImmutabilityPolicyData immutabilityPolicyModel = new ImmutabilityPolicyData()
            {
                ImmutabilityPeriodSinceCreationInDays = 3
            };
            ImmutabilityPolicyResource immutabilityPolicy = (await container.GetImmutabilityPolicy().CreateOrUpdateAsync(WaitUntil.Completed, immutabilityPolicyModel)).Value;

            Assert.NotNull(immutabilityPolicy.Id);
            Assert.NotNull(immutabilityPolicy.Data.ResourceType);
            Assert.NotNull(immutabilityPolicy.Data.Name);
            Assert.AreEqual(3, immutabilityPolicy.Data.ImmutabilityPeriodSinceCreationInDays);
            Assert.AreEqual(ImmutabilityPolicyState.Unlocked, immutabilityPolicy.Data.State);

            immutabilityPolicy = await container.GetImmutabilityPolicy().LockImmutabilityPolicyAsync(immutabilityPolicy.Data.Etag);

            Assert.NotNull(immutabilityPolicy.Id);
            Assert.NotNull(immutabilityPolicy.Data.ResourceType);
            Assert.NotNull(immutabilityPolicy.Data.Name);
            Assert.AreEqual(3, immutabilityPolicy.Data.ImmutabilityPeriodSinceCreationInDays);
            Assert.AreEqual(ImmutabilityPolicyState.Locked, immutabilityPolicy.Data.State);

            immutabilityPolicyModel = new ImmutabilityPolicyData()
            {
                ImmutabilityPeriodSinceCreationInDays = 100
            };
            immutabilityPolicy = await container.GetImmutabilityPolicy().ExtendImmutabilityPolicyAsync(immutabilityPolicy.Data.Etag, data: immutabilityPolicyModel);

            Assert.NotNull(immutabilityPolicy.Id);
            Assert.NotNull(immutabilityPolicy.Data.ResourceType);
            Assert.NotNull(immutabilityPolicy.Data.Name);
            Assert.AreEqual(100, immutabilityPolicy.Data.ImmutabilityPeriodSinceCreationInDays);
            Assert.AreEqual(ImmutabilityPolicyState.Locked, immutabilityPolicy.Data.State);

            container = await container.GetAsync();

            Assert.IsEmpty(container.Data.Metadata);
            Assert.AreEqual(PublicAccess.None, container.Data.PublicAccess);
            Assert.AreEqual(3, container.Data.ImmutabilityPolicy.UpdateHistory.Count);
            Assert.AreEqual(ImmutabilityPolicyUpdateType.Put, container.Data.ImmutabilityPolicy.UpdateHistory[0].Update);
            Assert.AreEqual(ImmutabilityPolicyUpdateType.Lock, container.Data.ImmutabilityPolicy.UpdateHistory[1].Update);
            Assert.AreEqual(ImmutabilityPolicyUpdateType.Extend, container.Data.ImmutabilityPolicy.UpdateHistory[2].Update);
            Assert.IsTrue(container.Data.LegalHold.HasLegalHold);
            Assert.AreEqual(3, container.Data.LegalHold.Tags.Count);
            Assert.AreEqual("tag1", container.Data.LegalHold.Tags[0].Tag);
            Assert.AreEqual("tag2", container.Data.LegalHold.Tags[1].Tag);
            Assert.AreEqual("tag3", container.Data.LegalHold.Tags[2].Tag);

            legalHold = await container.ClearLegalHoldAsync(legalHold);

            Assert.IsFalse(legalHold.HasLegalHold);

            await container.DeleteAsync(WaitUntil.Completed);
        }
Exemple #13
0
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
        static async Task ObjectWriteLegalHold(S3Context ctx, LegalHold legalHold)
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
        {
            Console.WriteLine("ObjectWriteLegalHold: " + ctx.Request.Bucket + "/" + ctx.Request.Key);
            Console.WriteLine(ctx.Request.DataAsString + Environment.NewLine);
        }