public void StorageCredentialsSAS() { StorageCredentials cred = new StorageCredentials(token); Assert.IsNull(cred.AccountName); Assert.IsFalse(cred.IsAnonymous); Assert.IsTrue(cred.IsSAS); Assert.IsFalse(cred.IsSharedKey); Uri testUri = new Uri("http://test/abc"); Assert.AreEqual(testUri.AbsoluteUri + token, cred.TransformUri(testUri).AbsoluteUri, true); testUri = new Uri("http://test/abc?query=a&query2=b"); string expectedUri = testUri.AbsoluteUri + "&" + token.Substring(1); Assert.AreEqual(expectedUri, cred.TransformUri(testUri).AbsoluteUri, true); byte[] dummyKey = { 0, 1, 2 }; string base64EncodedDummyKey = Convert.ToBase64String(dummyKey); TestHelper.ExpectedException <InvalidOperationException>( () => cred.UpdateKey(base64EncodedDummyKey, null), "Updating shared key on a SAS credentials instance should fail."); }
public async Task CloudBlobSASUnknownParamsAsync() { // Create Source on server CloudBlockBlob blob = this.testContainer.GetBlockBlobReference("source"); string data = "String data"; await UploadTextAsync(blob, data, Encoding.UTF8); UriBuilder blobURIBuilder = new UriBuilder(blob.Uri); blobURIBuilder.Query = "MyQuery=value&YOURQUERY=value2"; // Add the query params unknown to the service // Source SAS must have read permissions SharedAccessBlobPermissions permissions = SharedAccessBlobPermissions.Read; SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy() { SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5), SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30), Permissions = permissions, }; string sasToken = blob.GetSharedAccessSignature(policy); StorageCredentials credentials = new StorageCredentials(sasToken); CloudBlockBlob sasBlob = new CloudBlockBlob(credentials.TransformUri(blobURIBuilder.Uri)); // Add the SAS query params // Validate that we can fetch the attributes on the blob (no exception thrown) await sasBlob.FetchAttributesAsync(); }
private static HttpWebRequest BlobGetRequest(KeyValuePair <long, int> blockOffsetAndLength, CloudBlockBlob blob) { StorageCredentials credentials = blob.ServiceClient.Credentials; var transformedUri = credentials.TransformUri(blob.Uri); // Prepare the HttpWebRequest to download data from the chunk. HttpWebRequest blobGetRequest = BlobHttpWebRequestFactory.Get( transformedUri, Timeout, snapshot: null, offset: blockOffsetAndLength.Key, count: blockOffsetAndLength.Value, rangeContentMD5: false, accessCondition: AccessCondition.GenerateEmptyCondition(), operationContext: new OperationContext()); if (credentials.IsSharedKey) { IAuthenticationHandler authenticationHandler = new SharedKeyAuthenticationHandler( SharedKeyCanonicalizer.Instance, credentials, credentials.AccountName); authenticationHandler.SignRequest(blobGetRequest, new OperationContext()); } return(blobGetRequest); }
public void StorageCredentialsSharedKey() { StorageCredentials cred = new StorageCredentials(TestBase.TargetTenantConfig.AccountName, TestBase.TargetTenantConfig.AccountKey); Assert.AreEqual(TestBase.TargetTenantConfig.AccountName, cred.AccountName, false); Assert.IsFalse(cred.IsAnonymous); Assert.IsFalse(cred.IsSAS); Assert.IsTrue(cred.IsSharedKey); Uri testUri = new Uri("http://test/abc?querya=1"); Assert.AreEqual(testUri, cred.TransformUri(testUri)); Assert.AreEqual(TestBase.TargetTenantConfig.AccountKey, Convert.ToBase64String(cred.ExportKey())); byte[] dummyKey = { 0, 1, 2 }; string base64EncodedDummyKey = Convert.ToBase64String(dummyKey); cred.UpdateKey(base64EncodedDummyKey, null); Assert.AreEqual(base64EncodedDummyKey, Convert.ToBase64String(cred.ExportKey())); #if !RTMD dummyKey[0] = 3; base64EncodedDummyKey = Convert.ToBase64String(dummyKey); cred.UpdateKey(dummyKey, null); Assert.AreEqual(base64EncodedDummyKey, Convert.ToBase64String(cred.ExportKey())); #endif }
public void StorageCredentialsSAS() { StorageCredentials cred = new StorageCredentials(token); Assert.IsNull(cred.AccountName); Assert.IsFalse(cred.IsAnonymous); Assert.IsTrue(cred.IsSAS); Assert.IsFalse(cred.IsSharedKey); Uri testUri = new Uri("http://test/abc"); Assert.AreEqual(testUri.AbsoluteUri + token + "&" + Constants.QueryConstants.ApiVersion + "=" + Constants.HeaderConstants.TargetStorageVersion, cred.TransformUri(testUri).AbsoluteUri, true); testUri = new Uri("http://test/abc?query=a&query2=b"); string expectedUri = testUri.AbsoluteUri + "&" + token.Substring(1) + "&" + Constants.QueryConstants.ApiVersion + "=" + Constants.HeaderConstants.TargetStorageVersion; Assert.AreEqual(expectedUri, cred.TransformUri(testUri).AbsoluteUri, true); byte[] dummyKey = { 0, 1, 2 }; string base64EncodedDummyKey = Convert.ToBase64String(dummyKey); TestHelper.ExpectedException <InvalidOperationException>( () => cred.UpdateKey(base64EncodedDummyKey), "Updating shared key on a SAS credentials instance should fail."); TestHelper.ExpectedException <ArgumentException>( () => new StorageCredentials(tokenWithApiVersion), "Unexpected 'api-version' parameter included in the SAS token."); }
public override object GetTransferObject(string rootPath, FileNode fileNode, StorageCredentials credentials = null) { Uri result = base.GetCloudBlobReference(rootPath, fileNode).SnapshotQualifiedUri; if (credentials != null) { result = credentials.TransformUri(result); } return(result); }
public ActionResult GetRandomBlobUploadUrl(string sasVersion) { var container = GetBlobContainer(); var blob = container.GetBlockBlobReference(Guid.NewGuid().ToString("D") + ".jpg"); var policy = new SharedAccessBlobPolicy() { Permissions = SharedAccessBlobPermissions.Write, SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(15), }; var sas = blob.GetSharedAccessSignature(policy, null, null, sasVersion); var credentials = new StorageCredentials(sas); var uri = credentials.TransformUri(blob.Uri); return(Content(uri.AbsoluteUri)); }
/// <summary> /// Get the target blob from a sas blob uri with read and write permissions. /// The sas uri is valid fo 1 day. /// </summary> /// <param name="tgtContainer"></param> /// <param name="tgtBlobName"></param> /// <returns></returns> private CloudBlob GetTgtBlobWithSasUri(CloudBlobContainer tgtContainer, string tgtBlobName) { var tgtBlob = tgtContainer.GetBlockBlobReference(tgtBlobName); var writePolicy = new SharedAccessBlobPolicy { Permissions = SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.Read, SharedAccessExpiryTime = new DateTimeOffset(DateTime.UtcNow.AddDays(1)) }; var tgtSasToken = tgtBlob.GetSharedAccessSignature(writePolicy); StorageCredentials credentials = new StorageCredentials(tgtSasToken); return(new CloudBlockBlob(credentials.TransformUri(tgtBlob.Uri))); }
public void StorageCredentialsAnonymous() { StorageCredentials cred = new StorageCredentials(); Assert.IsNull(cred.AccountName); Assert.IsTrue(cred.IsAnonymous); Assert.IsFalse(cred.IsSAS); Assert.IsFalse(cred.IsSharedKey); Uri testUri = new Uri("http://test/abc?querya=1"); Assert.AreEqual(testUri, cred.TransformUri(testUri)); byte[] dummyKey = { 0, 1, 2 }; string base64EncodedDummyKey = Convert.ToBase64String(dummyKey); TestHelper.ExpectedException <InvalidOperationException>( () => cred.UpdateKey(base64EncodedDummyKey, null), "Updating shared key on an anonymous credentials instance should fail."); }
public void CloudBlobSASUnknownParams() { CloudBlobContainer container = GetRandomContainerReference(); try { container.Create(); // Create Source on server CloudBlockBlob blob = container.GetBlockBlobReference("source"); string data = "String data"; UploadText(blob, data, Encoding.UTF8); UriBuilder blobURIBuilder = new UriBuilder(blob.Uri); blobURIBuilder.Query = "MyQuery=value&YOURQUERY=value2"; // Add the query params unknown to the service // Source SAS must have read permissions SharedAccessBlobPermissions permissions = SharedAccessBlobPermissions.Read; SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy() { SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5), SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30), Permissions = permissions, }; string sasToken = blob.GetSharedAccessSignature(policy); // Replace one of the SAS keys with a capitalized version to ensure we are case-insensitive on expected parameter keys as well StorageCredentials credentials = new StorageCredentials(sasToken); StringBuilder sasString = new StringBuilder(credentials.TransformUri(blobURIBuilder.Uri).ToString()); sasString.Replace("sp=", "SP="); CloudBlockBlob sasBlob = new CloudBlockBlob(new Uri(sasString.ToString())); // Validate that we can fetch the attributes on the blob (no exception thrown) sasBlob.FetchAttributes(); } finally { container.DeleteIfExists(); } }
private static void CloudFileCopy(bool sourceIsSas, bool destinationIsSas) { CloudFileShare share = GetRandomShareReference(); try { share.Create(); // Create Source on server CloudFile source = share.GetRootDirectoryReference().GetFileReference("source"); string data = "String data"; UploadText(source, data, Encoding.UTF8); source.Metadata["Test"] = "value"; source.SetMetadata(); string permission = "O:S-1-5-21-2127521184-1604012920-1887927527-21560751G:S-1-5-21-2127521184-1604012920-1887927527-513D:AI(A;;FA;;;SY)(A;;FA;;;BA)(A;;0x1200a9;;;S-1-5-21-397955417-626881126-188441444-3053964)"; string permissionKey = share.CreateFilePermission(permission); source.Properties.FilePermissionKey = permissionKey; var attributes = CloudFileNtfsAttributes.NoScrubData | CloudFileNtfsAttributes.Temporary; var creationTime = DateTimeOffset.UtcNow.AddDays(-1); source.Properties.NtfsAttributes = attributes; DateTimeOffset lastWriteTime = DateTimeOffset.UtcNow; source.Properties.LastWriteTime = lastWriteTime; source.Properties.CreationTime = creationTime; source.SetProperties(); // Create Destination on server CloudFile destination = share.GetRootDirectoryReference().GetFileReference("destination"); destination.Create(1); CloudFile copySource = source; CloudFile copyDestination = destination; if (sourceIsSas) { // Source SAS must have read permissions SharedAccessFilePermissions permissions = SharedAccessFilePermissions.Read; SharedAccessFilePolicy policy = new SharedAccessFilePolicy() { SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5), SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30), Permissions = permissions, }; string sasToken = share.GetSharedAccessSignature(policy); // Get source StorageCredentials credentials = new StorageCredentials(sasToken); copySource = new CloudFile(credentials.TransformUri(source.Uri)); } if (destinationIsSas) { Assert.IsTrue(sourceIsSas); // Destination SAS must have write permissions SharedAccessFilePermissions permissions = SharedAccessFilePermissions.Write; SharedAccessFilePolicy policy = new SharedAccessFilePolicy() { SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5), SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30), Permissions = permissions, }; string sasToken = destination.GetSharedAccessSignature(policy); // Get destination StorageCredentials credentials = new StorageCredentials(sasToken); copyDestination = new CloudFile(credentials.TransformUri(destination.Uri)); } // Start copy and wait for completion string copyId = copyDestination.StartCopy(TestHelper.Defiddler(copySource), null, null, new FileCopyOptions() { PreservePermissions = true, PreserveCreationTime = true, PreserveLastWriteTime = true, PreserveNtfsAttributes = true, SetArchive = false }, null, null); WaitForCopy(destination); // Check original file references for equality Assert.AreEqual(CopyStatus.Success, destination.CopyState.Status); Assert.AreEqual(source.Uri.AbsolutePath, destination.CopyState.Source.AbsolutePath); Assert.AreEqual(data.Length, destination.CopyState.TotalBytes); Assert.AreEqual(data.Length, destination.CopyState.BytesCopied); Assert.AreEqual(copyId, destination.CopyState.CopyId); Assert.IsTrue(destination.CopyState.CompletionTime > DateTimeOffset.UtcNow.Subtract(TimeSpan.FromMinutes(1))); if (!destinationIsSas) { // Abort Copy is not supported for SAS destination TestHelper.ExpectedException( () => copyDestination.AbortCopy(copyId), "Aborting a copy operation after completion should fail", HttpStatusCode.Conflict, "NoPendingCopyOperation"); } source.FetchAttributes(); Assert.IsNotNull(destination.Properties.ETag); Assert.AreNotEqual(source.Properties.ETag, destination.Properties.ETag); Assert.IsTrue(destination.Properties.LastModified > DateTimeOffset.UtcNow.Subtract(TimeSpan.FromMinutes(1))); string copyData = DownloadText(destination, Encoding.UTF8); Assert.AreEqual(data, copyData, "Data inside copy of file not equal."); destination.FetchAttributes(); FileProperties prop1 = destination.Properties; FileProperties prop2 = source.Properties; Assert.AreEqual(prop1.CacheControl, prop2.CacheControl); Assert.AreEqual(prop1.ContentEncoding, prop2.ContentEncoding); Assert.AreEqual(prop1.ContentLanguage, prop2.ContentLanguage); Assert.AreEqual(prop1.ContentMD5, prop2.ContentMD5); Assert.AreEqual(prop1.ContentType, prop2.ContentType); Assert.AreEqual(lastWriteTime, destination.Properties.LastWriteTime.Value); Assert.AreEqual(creationTime, destination.Properties.CreationTime.Value); Assert.AreEqual(attributes, destination.Properties.NtfsAttributes.Value); Assert.IsNotNull(destination.Properties.FilePermissionKey); Assert.IsNull(destination.FilePermission); Assert.AreEqual("value", destination.Metadata["Test"], false, "Copied metadata not same"); destination.Delete(); source.Delete(); } finally { share.DeleteIfExists(); } }
private static void TestAccess(string sasToken, SharedAccessFilePermissions permissions, SharedAccessFileHeaders headers, CloudFileShare share, CloudFile file) { StorageCredentials credentials = string.IsNullOrEmpty(sasToken) ? new StorageCredentials() : new StorageCredentials(sasToken); if (share != null) { share = new CloudFileShare(credentials.TransformUri(share.Uri)); file = share.GetRootDirectoryReference().GetFileReference(file.Name); } else { file = new CloudFile(credentials.TransformUri(file.Uri)); } if (share != null) { if ((permissions & SharedAccessFilePermissions.List) == SharedAccessFilePermissions.List) { share.GetRootDirectoryReference().ListFilesAndDirectories().ToArray(); } else { TestHelper.ExpectedException( () => share.GetRootDirectoryReference().ListFilesAndDirectories().ToArray(), "List files while SAS does not allow for listing", HttpStatusCode.NotFound); } } if ((permissions & SharedAccessFilePermissions.Read) == SharedAccessFilePermissions.Read) { file.FetchAttributes(); // Test headers if (headers != null) { if (headers.CacheControl != null) { Assert.AreEqual(headers.CacheControl, file.Properties.CacheControl); } if (headers.ContentDisposition != null) { Assert.AreEqual(headers.ContentDisposition, file.Properties.ContentDisposition); } if (headers.ContentEncoding != null) { Assert.AreEqual(headers.ContentEncoding, file.Properties.ContentEncoding); } if (headers.ContentLanguage != null) { Assert.AreEqual(headers.ContentLanguage, file.Properties.ContentLanguage); } if (headers.ContentType != null) { Assert.AreEqual(headers.ContentType, file.Properties.ContentType); } } } else { TestHelper.ExpectedException( () => file.FetchAttributes(), "Fetch file attributes while SAS does not allow for reading", HttpStatusCode.NotFound); } if ((permissions & SharedAccessFilePermissions.Write) == SharedAccessFilePermissions.Write) { file.SetMetadata(); } else { TestHelper.ExpectedException( () => file.SetMetadata(), "Set file metadata while SAS does not allow for writing", HttpStatusCode.NotFound); } if ((permissions & SharedAccessFilePermissions.Delete) == SharedAccessFilePermissions.Delete) { file.Delete(); } else { TestHelper.ExpectedException( () => file.Delete(), "Delete file while SAS does not allow for deleting", HttpStatusCode.NotFound); } }
/// <summary> /// Helper function for testing the IPAddressOrRange funcitonality for blobs /// </summary> /// <param name="generateInitialIPAddressOrRange">Function that generates an initial IPAddressOrRange object to use. This is expected to fail on the service.</param> /// <param name="generateFinalIPAddressOrRange">Function that takes in the correct IP address (according to the service) and returns the IPAddressOrRange object /// that should be accepted by the service</param> public void CloudBlobSASIPAddressHelper(Func <IPAddressOrRange> generateInitialIPAddressOrRange, Func <IPAddress, IPAddressOrRange> generateFinalIPAddressOrRange) { CloudBlobContainer container = GetRandomContainerReference(); try { container.Create(); CloudBlob blob; SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy() { Permissions = SharedAccessBlobPermissions.Read, SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5), SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30), }; CloudBlockBlob blockBlob = container.GetBlockBlobReference("bb"); byte[] data = new byte[] { 0x1, 0x2, 0x3, 0x4 }; blockBlob.UploadFromByteArray(data, 0, 4); // The plan then is to use an incorrect IP address to make a call to the service // ensure that we get an error message // parse the error message to get my actual IP (as far as the service sees) // then finally test the success case to ensure we can actually make requests IPAddressOrRange ipAddressOrRange = generateInitialIPAddressOrRange(); string blockBlobToken = blockBlob.GetSharedAccessSignature(policy, null, null, null, ipAddressOrRange); StorageCredentials blockBlobSAS = new StorageCredentials(blockBlobToken); Uri blockBlobSASUri = blockBlobSAS.TransformUri(blockBlob.Uri); StorageUri blockBlobSASStorageUri = blockBlobSAS.TransformUri(blockBlob.StorageUri); blob = new CloudBlob(blockBlobSASUri); byte[] target = new byte[4]; OperationContext opContext = new OperationContext(); IPAddress actualIP = null; opContext.ResponseReceived += (sender, e) => { Stream stream = e.Response.GetResponseStream(); stream.Seek(0, SeekOrigin.Begin); using (StreamReader reader = new StreamReader(stream)) { string text = reader.ReadToEnd(); XDocument xdocument = XDocument.Parse(text); actualIP = IPAddress.Parse(xdocument.Descendants("SourceIP").First().Value); } }; bool exceptionThrown = false; try { blob.DownloadRangeToByteArray(target, 0, 0, 4, null, null, opContext); } catch (StorageException) { exceptionThrown = true; Assert.IsNotNull(actualIP); } Assert.IsTrue(exceptionThrown); ipAddressOrRange = generateFinalIPAddressOrRange(actualIP); blockBlobToken = blockBlob.GetSharedAccessSignature(policy, null, null, null, ipAddressOrRange); blockBlobSAS = new StorageCredentials(blockBlobToken); blockBlobSASUri = blockBlobSAS.TransformUri(blockBlob.Uri); blockBlobSASStorageUri = blockBlobSAS.TransformUri(blockBlob.StorageUri); blob = new CloudBlob(blockBlobSASUri); blob.DownloadRangeToByteArray(target, 0, 0, 4, null, null, null); for (int i = 0; i < 4; i++) { Assert.AreEqual(data[i], target[i]); } Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(blockBlob.Uri)); Assert.IsNull(blob.StorageUri.SecondaryUri); blob = new CloudBlob(blockBlobSASStorageUri, null, null); blob.DownloadRangeToByteArray(target, 0, 0, 4, null, null, null); for (int i = 0; i < 4; i++) { Assert.AreEqual(data[i], target[i]); } Assert.IsTrue(blob.StorageUri.Equals(blockBlob.StorageUri)); } finally { container.DeleteIfExists(); } }
private static void TestAccess(string sasToken, SharedAccessBlobPermissions permissions, SharedAccessBlobHeaders headers, CloudBlobContainer container, CloudBlob blob) { CloudBlob SASblob; StorageCredentials credentials = string.IsNullOrEmpty(sasToken) ? new StorageCredentials() : new StorageCredentials(sasToken); if (container != null) { container = new CloudBlobContainer(credentials.TransformUri(container.Uri)); if (blob.BlobType == BlobType.BlockBlob) { SASblob = container.GetBlockBlobReference(blob.Name); } else if (blob.BlobType == BlobType.PageBlob) { SASblob = container.GetPageBlobReference(blob.Name); } else { SASblob = container.GetAppendBlobReference(blob.Name); } } else { if (blob.BlobType == BlobType.BlockBlob) { SASblob = new CloudBlockBlob(credentials.TransformUri(blob.Uri)); } else if (blob.BlobType == BlobType.PageBlob) { SASblob = new CloudPageBlob(credentials.TransformUri(blob.Uri)); } else { SASblob = new CloudAppendBlob(credentials.TransformUri(blob.Uri)); } } HttpStatusCode failureCode = sasToken == null ? HttpStatusCode.NotFound : HttpStatusCode.Forbidden; // We want to ensure that 'create', 'add', and 'write' permissions all allow for correct writing of blobs, as is reasonable. if (((permissions & SharedAccessBlobPermissions.Create) == SharedAccessBlobPermissions.Create) || ((permissions & SharedAccessBlobPermissions.Write) == SharedAccessBlobPermissions.Write)) { if (blob.BlobType == BlobType.PageBlob) { CloudPageBlob SASpageBlob = (CloudPageBlob)SASblob; SASpageBlob.Create(512); CloudPageBlob pageBlob = (CloudPageBlob)blob; byte[] buffer = new byte[512]; buffer[0] = 2; // random data if (((permissions & SharedAccessBlobPermissions.Write) == SharedAccessBlobPermissions.Write)) { SASpageBlob.UploadFromByteArray(buffer, 0, 512); } else { TestHelper.ExpectedException( () => SASpageBlob.UploadFromByteArray(buffer, 0, 512), "pageBlob SAS token without Write perms should not allow for writing/adding", failureCode); pageBlob.UploadFromByteArray(buffer, 0, 512); } } else if (blob.BlobType == BlobType.BlockBlob) { if ((permissions & SharedAccessBlobPermissions.Write) == SharedAccessBlobPermissions.Write) { UploadText(SASblob, "blob", Encoding.UTF8); } else { TestHelper.ExpectedException( () => UploadText(SASblob, "blob", Encoding.UTF8), "Block blob SAS token without Write or perms should not allow for writing", failureCode); UploadText(blob, "blob", Encoding.UTF8); } } else // append blob { // If the sas token contains Feb 2012, append won't be accepted if (sasToken.Contains(Constants.VersionConstants.February2012)) { UploadText(blob, "blob", Encoding.UTF8); } else { CloudAppendBlob SASAppendBlob = SASblob as CloudAppendBlob; SASAppendBlob.CreateOrReplace(); byte[] textAsBytes = Encoding.UTF8.GetBytes("blob"); using (MemoryStream stream = new MemoryStream()) { stream.Write(textAsBytes, 0, textAsBytes.Length); stream.Seek(0, SeekOrigin.Begin); if (((permissions & SharedAccessBlobPermissions.Add) == SharedAccessBlobPermissions.Add) || ((permissions & SharedAccessBlobPermissions.Write) == SharedAccessBlobPermissions.Write)) { SASAppendBlob.AppendBlock(stream, null); } else { TestHelper.ExpectedException( () => SASAppendBlob.AppendBlock(stream, null), "Append blob SAS token without Write or Add perms should not allow for writing/adding", failureCode); stream.Seek(0, SeekOrigin.Begin); ((CloudAppendBlob)blob).AppendBlock(stream, null); } } } } } else { TestHelper.ExpectedException( () => UploadText(SASblob, "blob", Encoding.UTF8), "UploadText SAS does not allow for writing/adding", ((blob.BlobType == BlobType.AppendBlob) && (sasToken != null) && (sasToken.Contains(Constants.VersionConstants.February2012))) ? HttpStatusCode.BadRequest : failureCode); UploadText(blob, "blob", Encoding.UTF8); } if (container != null) { if ((permissions & SharedAccessBlobPermissions.List) == SharedAccessBlobPermissions.List) { container.ListBlobs().ToArray(); } else { TestHelper.ExpectedException( () => container.ListBlobs().ToArray(), "List blobs while SAS does not allow for listing", failureCode); } } // need to have written to the blob to read from it. if (((permissions & SharedAccessBlobPermissions.Read) == SharedAccessBlobPermissions.Read)) { SASblob.FetchAttributes(); // Test headers if (headers != null) { if (headers.CacheControl != null) { Assert.AreEqual(headers.CacheControl, SASblob.Properties.CacheControl); } if (headers.ContentDisposition != null) { Assert.AreEqual(headers.ContentDisposition, SASblob.Properties.ContentDisposition); } if (headers.ContentEncoding != null) { Assert.AreEqual(headers.ContentEncoding, SASblob.Properties.ContentEncoding); } if (headers.ContentLanguage != null) { Assert.AreEqual(headers.ContentLanguage, SASblob.Properties.ContentLanguage); } if (headers.ContentType != null) { Assert.AreEqual(headers.ContentType, SASblob.Properties.ContentType); } } } else { TestHelper.ExpectedException( () => SASblob.FetchAttributes(), "Fetch blob attributes while SAS does not allow for reading", failureCode); } if ((permissions & SharedAccessBlobPermissions.Write) == SharedAccessBlobPermissions.Write) { SASblob.SetMetadata(); } else { TestHelper.ExpectedException( () => SASblob.SetMetadata(), "Set blob metadata while SAS does not allow for writing", failureCode); } if ((permissions & SharedAccessBlobPermissions.Delete) == SharedAccessBlobPermissions.Delete) { SASblob.Delete(); } else { TestHelper.ExpectedException( () => SASblob.Delete(), "Delete blob while SAS does not allow for deleting", failureCode); } }
public void CloudBlobSASApiVersionQueryParam() { CloudBlobContainer container = GetRandomContainerReference(); try { container.Create(); CloudBlob blob; SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy() { Permissions = SharedAccessBlobPermissions.Read, SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5), SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30), }; CloudBlockBlob blockBlob = container.GetBlockBlobReference("bb"); blockBlob.PutBlockList(new string[] { }); CloudPageBlob pageBlob = container.GetPageBlobReference("pb"); pageBlob.Create(0); CloudAppendBlob appendBlob = container.GetAppendBlobReference("ab"); appendBlob.CreateOrReplace(); string blockBlobToken = blockBlob.GetSharedAccessSignature(policy); StorageCredentials blockBlobSAS = new StorageCredentials(blockBlobToken); Uri blockBlobSASUri = blockBlobSAS.TransformUri(blockBlob.Uri); StorageUri blockBlobSASStorageUri = blockBlobSAS.TransformUri(blockBlob.StorageUri); string pageBlobToken = pageBlob.GetSharedAccessSignature(policy); StorageCredentials pageBlobSAS = new StorageCredentials(pageBlobToken); Uri pageBlobSASUri = pageBlobSAS.TransformUri(pageBlob.Uri); StorageUri pageBlobSASStorageUri = pageBlobSAS.TransformUri(pageBlob.StorageUri); string appendBlobToken = appendBlob.GetSharedAccessSignature(policy); StorageCredentials appendBlobSAS = new StorageCredentials(appendBlobToken); Uri appendBlobSASUri = appendBlobSAS.TransformUri(appendBlob.Uri); StorageUri appendBlobSASStorageUri = appendBlobSAS.TransformUri(appendBlob.StorageUri); OperationContext apiVersionCheckContext = new OperationContext(); apiVersionCheckContext.SendingRequest += (sender, e) => { Assert.IsTrue(e.Request.RequestUri.Query.Contains("api-version")); }; blob = new CloudBlob(blockBlobSASUri); blob.FetchAttributes(operationContext: apiVersionCheckContext); Assert.AreEqual(blob.BlobType, BlobType.BlockBlob); Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(blockBlob.Uri)); Assert.IsNull(blob.StorageUri.SecondaryUri); blob = new CloudBlob(pageBlobSASUri); blob.FetchAttributes(operationContext: apiVersionCheckContext); Assert.AreEqual(blob.BlobType, BlobType.PageBlob); Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(pageBlob.Uri)); Assert.IsNull(blob.StorageUri.SecondaryUri); blob = new CloudBlob(blockBlobSASStorageUri, null, null); blob.FetchAttributes(operationContext: apiVersionCheckContext); Assert.AreEqual(blob.BlobType, BlobType.BlockBlob); Assert.IsTrue(blob.StorageUri.Equals(blockBlob.StorageUri)); blob = new CloudBlob(pageBlobSASStorageUri, null, null); blob.FetchAttributes(operationContext: apiVersionCheckContext); Assert.AreEqual(blob.BlobType, BlobType.PageBlob); Assert.IsTrue(blob.StorageUri.Equals(pageBlob.StorageUri)); } finally { container.DeleteIfExists(); } }
private static void CloudBlockBlobCopy(bool sourceIsSas, bool destinationIsSas) { CloudBlobContainer container = GetRandomContainerReference(); try { container.Create(); // Create Source on server CloudBlockBlob source = container.GetBlockBlobReference("source"); string data = "String data"; UploadText(source, data, Encoding.UTF8); source.Metadata["Test"] = "value"; source.SetMetadata(); // Create Destination on server CloudBlockBlob destination = container.GetBlockBlobReference("destination"); destination.PutBlockList(new string[] { }); CloudBlockBlob copySource = source; CloudBlockBlob copyDestination = destination; if (sourceIsSas) { // Source SAS must have read permissions SharedAccessBlobPermissions permissions = SharedAccessBlobPermissions.Read; SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy() { SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5), SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30), Permissions = permissions, }; string sasToken = source.GetSharedAccessSignature(policy); // Get source StorageCredentials credentials = new StorageCredentials(sasToken); copySource = new CloudBlockBlob(credentials.TransformUri(source.Uri)); } if (destinationIsSas) { if (!sourceIsSas) { // Source container must be public if source is not SAS BlobContainerPermissions containerPermissions = new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob }; container.SetPermissions(containerPermissions); } // Destination SAS must have write permissions SharedAccessBlobPermissions permissions = SharedAccessBlobPermissions.Write; SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy() { SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5), SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30), Permissions = permissions, }; string sasToken = destination.GetSharedAccessSignature(policy); // Get destination StorageCredentials credentials = new StorageCredentials(sasToken); copyDestination = new CloudBlockBlob(credentials.TransformUri(destination.Uri)); } // Start copy and wait for completion string copyId = copyDestination.StartCopyFromBlob(TestHelper.Defiddler(copySource)); WaitForCopy(destination); // Check original blob references for equality Assert.AreEqual(CopyStatus.Success, destination.CopyState.Status); Assert.AreEqual(source.Uri.AbsolutePath, destination.CopyState.Source.AbsolutePath); Assert.AreEqual(data.Length, destination.CopyState.TotalBytes); Assert.AreEqual(data.Length, destination.CopyState.BytesCopied); Assert.AreEqual(copyId, destination.CopyState.CopyId); Assert.IsTrue(destination.CopyState.CompletionTime > DateTimeOffset.UtcNow.Subtract(TimeSpan.FromMinutes(1))); if (!destinationIsSas) { // Abort Copy is not supported for SAS destination TestHelper.ExpectedException( () => copyDestination.AbortCopy(copyId), "Aborting a copy operation after completion should fail", HttpStatusCode.Conflict, "NoPendingCopyOperation"); } source.FetchAttributes(); Assert.IsNotNull(destination.Properties.ETag); Assert.AreNotEqual(source.Properties.ETag, destination.Properties.ETag); Assert.IsTrue(destination.Properties.LastModified > DateTimeOffset.UtcNow.Subtract(TimeSpan.FromMinutes(1))); string copyData = DownloadText(destination, Encoding.UTF8); Assert.AreEqual(data, copyData, "Data inside copy of blob not equal."); destination.FetchAttributes(); BlobProperties prop1 = destination.Properties; BlobProperties prop2 = source.Properties; Assert.AreEqual(prop1.CacheControl, prop2.CacheControl); Assert.AreEqual(prop1.ContentEncoding, prop2.ContentEncoding); Assert.AreEqual(prop1.ContentLanguage, prop2.ContentLanguage); Assert.AreEqual(prop1.ContentMD5, prop2.ContentMD5); Assert.AreEqual(prop1.ContentType, prop2.ContentType); Assert.AreEqual("value", destination.Metadata["Test"], false, "Copied metadata not same"); destination.Delete(); source.Delete(); } finally { container.DeleteIfExists(); } }
public async Task CloudBlobContainerGetBlobReferenceFromServerAsync() { CloudBlobContainer container = GetRandomContainerReference(); try { await container.CreateAsync(); SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy() { Permissions = SharedAccessBlobPermissions.Read, SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5), SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30), }; CloudBlockBlob blockBlob = container.GetBlockBlobReference("bb"); await blockBlob.PutBlockListAsync(new List <string>()); CloudPageBlob pageBlob = container.GetPageBlobReference("pb"); await pageBlob.CreateAsync(0); CloudAppendBlob appendBlob = container.GetAppendBlobReference("ab"); await appendBlob.CreateOrReplaceAsync(); CloudBlobClient client; ICloudBlob blob; blob = await container.GetBlobReferenceFromServerAsync("bb"); Assert.IsInstanceOfType(blob, typeof(CloudBlockBlob)); Assert.IsTrue(blob.StorageUri.Equals(blockBlob.StorageUri)); CloudBlockBlob blockBlobSnapshot = await((CloudBlockBlob)blob).CreateSnapshotAsync(); await blob.SetPropertiesAsync(); Uri blockBlobSnapshotUri = new Uri(blockBlobSnapshot.Uri.AbsoluteUri + "?snapshot=" + blockBlobSnapshot.SnapshotTime.Value.UtcDateTime.ToString("o")); blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(blockBlobSnapshotUri); AssertAreEqual(blockBlobSnapshot.Properties, blob.Properties); Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(blockBlobSnapshot.Uri)); Assert.IsNull(blob.StorageUri.SecondaryUri); blob = await container.GetBlobReferenceFromServerAsync("pb"); Assert.IsInstanceOfType(blob, typeof(CloudPageBlob)); Assert.IsTrue(blob.StorageUri.Equals(pageBlob.StorageUri)); CloudPageBlob pageBlobSnapshot = await((CloudPageBlob)blob).CreateSnapshotAsync(); await blob.SetPropertiesAsync(); Uri pageBlobSnapshotUri = new Uri(pageBlobSnapshot.Uri.AbsoluteUri + "?snapshot=" + pageBlobSnapshot.SnapshotTime.Value.UtcDateTime.ToString("o")); blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(pageBlobSnapshotUri); AssertAreEqual(pageBlobSnapshot.Properties, blob.Properties); Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(pageBlobSnapshot.Uri)); Assert.IsNull(blob.StorageUri.SecondaryUri); blob = await container.GetBlobReferenceFromServerAsync("ab"); Assert.IsInstanceOfType(blob, typeof(CloudAppendBlob)); Assert.IsTrue(blob.StorageUri.Equals(appendBlob.StorageUri)); CloudAppendBlob appendBlobSnapshot = await((CloudAppendBlob)blob).CreateSnapshotAsync(); await blob.SetPropertiesAsync(); Uri appendBlobSnapshotUri = new Uri(appendBlobSnapshot.Uri.AbsoluteUri + "?snapshot=" + appendBlobSnapshot.SnapshotTime.Value.UtcDateTime.ToString("o")); blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(appendBlobSnapshotUri); AssertAreEqual(appendBlobSnapshot.Properties, blob.Properties); Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(appendBlobSnapshot.Uri)); Assert.IsNull(blob.StorageUri.SecondaryUri); blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(blockBlob.Uri); Assert.IsInstanceOfType(blob, typeof(CloudBlockBlob)); Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(blockBlob.Uri)); Assert.IsNull(blob.StorageUri.SecondaryUri); blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(pageBlob.Uri); Assert.IsInstanceOfType(blob, typeof(CloudPageBlob)); Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(pageBlob.Uri)); Assert.IsNull(blob.StorageUri.SecondaryUri); blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(appendBlob.Uri); Assert.IsInstanceOfType(blob, typeof(CloudAppendBlob)); Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(appendBlob.Uri)); Assert.IsNull(blob.StorageUri.SecondaryUri); blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(blockBlob.StorageUri, null, null, null); Assert.IsInstanceOfType(blob, typeof(CloudBlockBlob)); Assert.IsTrue(blob.StorageUri.Equals(blockBlob.StorageUri)); blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(pageBlob.StorageUri, null, null, null); Assert.IsInstanceOfType(blob, typeof(CloudPageBlob)); Assert.IsTrue(blob.StorageUri.Equals(pageBlob.StorageUri)); blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(appendBlob.StorageUri, null, null, null); Assert.IsInstanceOfType(blob, typeof(CloudAppendBlob)); Assert.IsTrue(blob.StorageUri.Equals(appendBlob.StorageUri)); string blockBlobToken = blockBlob.GetSharedAccessSignature(policy); StorageCredentials blockBlobSAS = new StorageCredentials(blockBlobToken); Uri blockBlobSASUri = blockBlobSAS.TransformUri(blockBlob.Uri); StorageUri blockBlobSASStorageUri = blockBlobSAS.TransformUri(blockBlob.StorageUri); string appendBlobToken = appendBlob.GetSharedAccessSignature(policy); StorageCredentials appendBlobSAS = new StorageCredentials(appendBlobToken); Uri appendBlobSASUri = appendBlobSAS.TransformUri(appendBlob.Uri); StorageUri appendBlobSASStorageUri = appendBlobSAS.TransformUri(appendBlob.StorageUri); string pageBlobToken = pageBlob.GetSharedAccessSignature(policy); StorageCredentials pageBlobSAS = new StorageCredentials(pageBlobToken); Uri pageBlobSASUri = pageBlobSAS.TransformUri(pageBlob.Uri); StorageUri pageBlobSASStorageUri = pageBlobSAS.TransformUri(pageBlob.StorageUri); blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(blockBlobSASUri); Assert.IsInstanceOfType(blob, typeof(CloudBlockBlob)); Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(blockBlob.Uri)); Assert.IsNull(blob.StorageUri.SecondaryUri); blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(pageBlobSASUri); Assert.IsInstanceOfType(blob, typeof(CloudPageBlob)); Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(pageBlob.Uri)); Assert.IsNull(blob.StorageUri.SecondaryUri); blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(appendBlobSASUri); Assert.IsInstanceOfType(blob, typeof(CloudAppendBlob)); Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(appendBlob.Uri)); Assert.IsNull(blob.StorageUri.SecondaryUri); blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(blockBlobSASStorageUri, null, null, null); Assert.IsInstanceOfType(blob, typeof(CloudBlockBlob)); Assert.IsTrue(blob.StorageUri.Equals(blockBlob.StorageUri)); blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(pageBlobSASStorageUri, null, null, null); Assert.IsInstanceOfType(blob, typeof(CloudPageBlob)); Assert.IsTrue(blob.StorageUri.Equals(pageBlob.StorageUri)); blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(appendBlobSASStorageUri, null, null, null); Assert.IsInstanceOfType(blob, typeof(CloudAppendBlob)); Assert.IsTrue(blob.StorageUri.Equals(appendBlob.StorageUri)); client = new CloudBlobClient(container.ServiceClient.BaseUri, blockBlobSAS); blob = await client.GetBlobReferenceFromServerAsync(blockBlobSASUri); Assert.IsInstanceOfType(blob, typeof(CloudBlockBlob)); Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(blockBlob.Uri)); Assert.IsNull(blob.StorageUri.SecondaryUri); client = new CloudBlobClient(container.ServiceClient.BaseUri, pageBlobSAS); blob = await client.GetBlobReferenceFromServerAsync(pageBlobSASUri); Assert.IsInstanceOfType(blob, typeof(CloudPageBlob)); Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(pageBlob.Uri)); Assert.IsNull(blob.StorageUri.SecondaryUri); client = new CloudBlobClient(container.ServiceClient.BaseUri, appendBlobSAS); blob = await client.GetBlobReferenceFromServerAsync(appendBlobSASUri); Assert.IsInstanceOfType(blob, typeof(CloudAppendBlob)); Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(appendBlob.Uri)); Assert.IsNull(blob.StorageUri.SecondaryUri); client = new CloudBlobClient(container.ServiceClient.StorageUri, blockBlobSAS); blob = await client.GetBlobReferenceFromServerAsync(blockBlobSASStorageUri, null, null, null); Assert.IsInstanceOfType(blob, typeof(CloudBlockBlob)); Assert.IsTrue(blob.StorageUri.Equals(blockBlob.StorageUri)); client = new CloudBlobClient(container.ServiceClient.StorageUri, pageBlobSAS); blob = await client.GetBlobReferenceFromServerAsync(pageBlobSASStorageUri, null, null, null); Assert.IsInstanceOfType(blob, typeof(CloudPageBlob)); Assert.IsTrue(blob.StorageUri.Equals(pageBlob.StorageUri)); client = new CloudBlobClient(container.ServiceClient.StorageUri, appendBlobSAS); blob = await client.GetBlobReferenceFromServerAsync(appendBlobSASStorageUri, null, null, null); Assert.IsInstanceOfType(blob, typeof(CloudAppendBlob)); Assert.IsTrue(blob.StorageUri.Equals(appendBlob.StorageUri)); } finally { container.DeleteIfExistsAsync().AsTask().Wait(); } }
private static void TestAccess(string sasToken, SharedAccessFilePermissions permissions, SharedAccessFileHeaders headers, CloudFileShare share, CloudFile file) { CloudFileShare SASshare = null; CloudFile SASfile; StorageCredentials credentials = string.IsNullOrEmpty(sasToken) ? new StorageCredentials() : new StorageCredentials(sasToken); string fileText = "file"; if (share != null) { SASshare = new CloudFileShare(credentials.TransformUri(share.Uri)); SASfile = SASshare.GetRootDirectoryReference().GetFileReference(file.Name); } else { SASfile = new CloudFile(credentials.TransformUri(file.Uri)); } if ((permissions & SharedAccessFilePermissions.Write) == SharedAccessFilePermissions.Write) { UploadText(SASfile, fileText, Encoding.UTF8); } else if ((permissions & SharedAccessFilePermissions.Create) == SharedAccessFilePermissions.Create) { SASfile.Create(Encoding.UTF8.GetBytes(fileText).Length); TestHelper.ExpectedException( () => UploadText(SASfile, fileText, Encoding.UTF8), "UploadText SAS does not allow for writing", HttpStatusCode.Forbidden); UploadText(file, fileText, Encoding.UTF8); } else { TestHelper.ExpectedException( () => SASfile.Create(Encoding.UTF8.GetBytes(fileText).Length), "Create file succeeded but SAS does not allow for writing/creating", HttpStatusCode.Forbidden); TestHelper.ExpectedException( () => UploadText(SASfile, fileText, Encoding.UTF8), "UploadText SAS does not allow for writing/creating", HttpStatusCode.Forbidden); UploadText(file, fileText, Encoding.UTF8); } if (SASshare != null) { if ((permissions & SharedAccessFilePermissions.List) == SharedAccessFilePermissions.List) { SASshare.GetRootDirectoryReference().ListFilesAndDirectories().ToArray(); } else { TestHelper.ExpectedException( () => SASshare.GetRootDirectoryReference().ListFilesAndDirectories().ToArray(), "List files while SAS does not allow for listing", HttpStatusCode.Forbidden); } } if ((permissions & SharedAccessFilePermissions.Read) == SharedAccessFilePermissions.Read) { SASfile.FetchAttributes(); // Test headers if (headers != null) { if (headers.CacheControl != null) { Assert.AreEqual(headers.CacheControl, SASfile.Properties.CacheControl); } if (headers.ContentDisposition != null) { Assert.AreEqual(headers.ContentDisposition, SASfile.Properties.ContentDisposition); } if (headers.ContentEncoding != null) { Assert.AreEqual(headers.ContentEncoding, SASfile.Properties.ContentEncoding); } if (headers.ContentLanguage != null) { Assert.AreEqual(headers.ContentLanguage, SASfile.Properties.ContentLanguage); } if (headers.ContentType != null) { Assert.AreEqual(headers.ContentType, SASfile.Properties.ContentType); } } } else { TestHelper.ExpectedException( () => SASfile.FetchAttributes(), "Fetch file attributes while SAS does not allow for reading", HttpStatusCode.Forbidden); } if ((permissions & SharedAccessFilePermissions.Write) == SharedAccessFilePermissions.Write) { SASfile.SetMetadata(); } else { TestHelper.ExpectedException( () => SASfile.SetMetadata(), "Set file metadata while SAS does not allow for writing", HttpStatusCode.Forbidden); } if ((permissions & SharedAccessFilePermissions.Delete) == SharedAccessFilePermissions.Delete) { SASfile.Delete(); } else { TestHelper.ExpectedException( () => SASfile.Delete(), "Delete file while SAS does not allow for deleting", HttpStatusCode.Forbidden); } }
private static string TransformUri(Uri resourceUri, string sasToken) { var creds = new StorageCredentials(sasToken); return(creds.TransformUri(resourceUri).ToString()); }
/// <summary> /// Helper function for testing the IPAddressOrRange funcitonality for blobs /// </summary> /// <param name="generateInitialIPAddressOrRange">Function that generates an initial IPAddressOrRange object to use. This is expected to fail on the service.</param> /// <param name="generateFinalIPAddressOrRange">Function that takes in the correct IP address (according to the service) and returns the IPAddressOrRange object /// that should be accepted by the service</param> public void CloudBlobSASIPAddressHelper(Func <IPAddressOrRange> generateInitialIPAddressOrRange, Func <IPAddress, IPAddressOrRange> generateFinalIPAddressOrRange) { CloudBlobContainer container = GetRandomContainerReference(); try { container.Create(); CloudBlob blob; SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy() { Permissions = SharedAccessBlobPermissions.Read, SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5), SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30), }; CloudBlockBlob blockBlob = container.GetBlockBlobReference("bb"); byte[] data = new byte[] { 0x1, 0x2, 0x3, 0x4 }; blockBlob.UploadFromByteArray(data, 0, 4); // The plan then is to use an incorrect IP address to make a call to the service // ensure that we get an error message // parse the error message to get my actual IP (as far as the service sees) // then finally test the success case to ensure we can actually make requests IPAddressOrRange ipAddressOrRange = generateInitialIPAddressOrRange(); string blockBlobToken = blockBlob.GetSharedAccessSignature(policy, null, null, null, ipAddressOrRange); StorageCredentials blockBlobSAS = new StorageCredentials(blockBlobToken); Uri blockBlobSASUri = blockBlobSAS.TransformUri(blockBlob.Uri); StorageUri blockBlobSASStorageUri = blockBlobSAS.TransformUri(blockBlob.StorageUri); blob = new CloudBlob(blockBlobSASUri); byte[] target = new byte[4]; OperationContext opContext = new OperationContext(); IPAddress actualIP = null; bool exceptionThrown = false; try { blob.DownloadRangeToByteArray(target, 0, 0, 4, null, null, opContext); } catch (StorageException) { exceptionThrown = true; //The IP should not be included in the error details for security reasons Assert.IsNull(actualIP); } Assert.IsTrue(exceptionThrown); ipAddressOrRange = null; blockBlobToken = blockBlob.GetSharedAccessSignature(policy, null, null, null, ipAddressOrRange); blockBlobSAS = new StorageCredentials(blockBlobToken); blockBlobSASUri = blockBlobSAS.TransformUri(blockBlob.Uri); blockBlobSASStorageUri = blockBlobSAS.TransformUri(blockBlob.StorageUri); blob = new CloudBlob(blockBlobSASUri); blob.DownloadRangeToByteArray(target, 0, 0, 4, null, null, null); for (int i = 0; i < 4; i++) { Assert.AreEqual(data[i], target[i]); } Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(blockBlob.Uri)); Assert.IsNull(blob.StorageUri.SecondaryUri); blob = new CloudBlob(blockBlobSASStorageUri, null, null); blob.DownloadRangeToByteArray(target, 0, 0, 4, null, null, null); for (int i = 0; i < 4; i++) { Assert.AreEqual(data[i], target[i]); } Assert.IsTrue(blob.StorageUri.Equals(blockBlob.StorageUri)); } finally { container.DeleteIfExists(); } }
public void CloudBlobSASApiVersionQueryParam() { CloudBlobContainer container = GetRandomContainerReference(); try { container.Create(); ICloudBlob blob; SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy() { Permissions = SharedAccessBlobPermissions.Read, SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5), SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30), }; CloudBlockBlob blockBlob = container.GetBlockBlobReference("bb"); blockBlob.PutBlockList(new string[] { }); CloudPageBlob pageBlob = container.GetPageBlobReference("pb"); pageBlob.Create(0); string blockBlobToken = blockBlob.GetSharedAccessSignature(policy); StorageCredentials blockBlobSAS = new StorageCredentials(blockBlobToken); Uri blockBlobSASUri = blockBlobSAS.TransformUri(blockBlob.Uri); StorageUri blockBlobSASStorageUri = blockBlobSAS.TransformUri(blockBlob.StorageUri); string pageBlobToken = pageBlob.GetSharedAccessSignature(policy); StorageCredentials pageBlobSAS = new StorageCredentials(pageBlobToken); Uri pageBlobSASUri = pageBlobSAS.TransformUri(pageBlob.Uri); StorageUri pageBlobSASStorageUri = pageBlobSAS.TransformUri(pageBlob.StorageUri); OperationContext apiVersionCheckContext = new OperationContext(); apiVersionCheckContext.SendingRequest += (sender, e) => { Assert.IsNull(e.Request.Headers.Get("x-ms-version")); Assert.IsTrue(e.Request.RequestUri.Query.Contains("api-version")); }; blob = container.ServiceClient.GetBlobReferenceFromServer(blockBlobSASUri, operationContext: apiVersionCheckContext); Assert.IsInstanceOfType(blob, typeof(CloudBlockBlob)); Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(blockBlob.Uri)); Assert.IsNull(blob.StorageUri.SecondaryUri); blob = container.ServiceClient.GetBlobReferenceFromServer(pageBlobSASUri, operationContext: apiVersionCheckContext); Assert.IsInstanceOfType(blob, typeof(CloudPageBlob)); Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(pageBlob.Uri)); Assert.IsNull(blob.StorageUri.SecondaryUri); blob = container.ServiceClient.GetBlobReferenceFromServer(blockBlobSASStorageUri, operationContext: apiVersionCheckContext); Assert.IsInstanceOfType(blob, typeof(CloudBlockBlob)); Assert.IsTrue(blob.StorageUri.Equals(blockBlob.StorageUri)); blob = container.ServiceClient.GetBlobReferenceFromServer(pageBlobSASStorageUri, operationContext: apiVersionCheckContext); Assert.IsInstanceOfType(blob, typeof(CloudPageBlob)); Assert.IsTrue(blob.StorageUri.Equals(pageBlob.StorageUri)); } finally { container.DeleteIfExists(); } }
private static void TestAccess(string sasToken, SharedAccessBlobPermissions permissions, SharedAccessBlobHeaders headers, CloudBlobContainer container, ICloudBlob blob) { StorageCredentials credentials = string.IsNullOrEmpty(sasToken) ? new StorageCredentials() : new StorageCredentials(sasToken); if (container != null) { container = new CloudBlobContainer(credentials.TransformUri(container.Uri)); if (blob.BlobType == BlobType.BlockBlob) { blob = container.GetBlockBlobReference(blob.Name); } else { blob = container.GetPageBlobReference(blob.Name); } } else { if (blob.BlobType == BlobType.BlockBlob) { blob = new CloudBlockBlob(credentials.TransformUri(blob.Uri)); } else { blob = new CloudPageBlob(credentials.TransformUri(blob.Uri)); } } if (container != null) { if ((permissions & SharedAccessBlobPermissions.List) == SharedAccessBlobPermissions.List) { container.ListBlobs().ToArray(); } else { TestHelper.ExpectedException( () => container.ListBlobs().ToArray(), "List blobs while SAS does not allow for listing", HttpStatusCode.NotFound); } } if ((permissions & SharedAccessBlobPermissions.Read) == SharedAccessBlobPermissions.Read) { blob.FetchAttributes(); // Test headers if (headers != null) { if (headers.CacheControl != null) { Assert.AreEqual(headers.CacheControl, blob.Properties.CacheControl); } if (headers.ContentDisposition != null) { Assert.AreEqual(headers.ContentDisposition, blob.Properties.ContentDisposition); } if (headers.ContentEncoding != null) { Assert.AreEqual(headers.ContentEncoding, blob.Properties.ContentEncoding); } if (headers.ContentLanguage != null) { Assert.AreEqual(headers.ContentLanguage, blob.Properties.ContentLanguage); } if (headers.ContentType != null) { Assert.AreEqual(headers.ContentType, blob.Properties.ContentType); } } } else { TestHelper.ExpectedException( () => blob.FetchAttributes(), "Fetch blob attributes while SAS does not allow for reading", HttpStatusCode.NotFound); } if ((permissions & SharedAccessBlobPermissions.Write) == SharedAccessBlobPermissions.Write) { blob.SetMetadata(); } else { TestHelper.ExpectedException( () => blob.SetMetadata(), "Set blob metadata while SAS does not allow for writing", HttpStatusCode.NotFound); } if ((permissions & SharedAccessBlobPermissions.Delete) == SharedAccessBlobPermissions.Delete) { blob.Delete(); } else { TestHelper.ExpectedException( () => blob.Delete(), "Delete blob while SAS does not allow for deleting", HttpStatusCode.NotFound); } }
private static async Task CloudFileCopyAsync(bool sourceIsSas, bool destinationIsSas) { CloudFileShare share = GetRandomShareReference(); try { await share.CreateAsync(); // Create Source on server CloudFile source = share.GetRootDirectoryReference().GetFileReference("source"); string data = "String data"; await UploadTextAsync(source, data, Encoding.UTF8); source.Metadata["Test"] = "value"; await source.SetMetadataAsync(); // Create Destination on server CloudFile destination = share.GetRootDirectoryReference().GetFileReference("destination"); await destination.CreateAsync(1); CloudFile copySource = source; CloudFile copyDestination = destination; if (sourceIsSas) { // Source SAS must have read permissions SharedAccessFilePermissions permissions = SharedAccessFilePermissions.Read; SharedAccessFilePolicy policy = new SharedAccessFilePolicy() { SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5), SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30), Permissions = permissions, }; string sasToken = source.GetSharedAccessSignature(policy); // Get source StorageCredentials credentials = new StorageCredentials(sasToken); copySource = new CloudFile(credentials.TransformUri(source.Uri)); } if (destinationIsSas) { Assert.IsTrue(sourceIsSas); // Destination SAS must have write permissions SharedAccessFilePermissions permissions = SharedAccessFilePermissions.Write; SharedAccessFilePolicy policy = new SharedAccessFilePolicy() { SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5), SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30), Permissions = permissions, }; string sasToken = destination.GetSharedAccessSignature(policy); // Get destination StorageCredentials credentials = new StorageCredentials(sasToken); copyDestination = new CloudFile(credentials.TransformUri(destination.Uri)); } // Start copy and wait for completion string copyId = await copyDestination.StartCopyAsync(TestHelper.Defiddler(copySource)); await WaitForCopyAsync(destination); // Check original file references for equality Assert.AreEqual(CopyStatus.Success, destination.CopyState.Status); Assert.AreEqual(source.Uri.AbsolutePath, destination.CopyState.Source.AbsolutePath); Assert.AreEqual(data.Length, destination.CopyState.TotalBytes); Assert.AreEqual(data.Length, destination.CopyState.BytesCopied); Assert.AreEqual(copyId, destination.CopyState.CopyId); Assert.IsTrue(destination.CopyState.CompletionTime > DateTimeOffset.UtcNow.Subtract(TimeSpan.FromMinutes(1))); if (!destinationIsSas) { // Abort Copy is not supported for SAS destination OperationContext context = new OperationContext(); await TestHelper.ExpectedExceptionAsync( async() => await copyDestination.AbortCopyAsync(copyId, null, null, context), context, "Aborting a copy operation after completion should fail", HttpStatusCode.Conflict, "NoPendingCopyOperation"); } await source.FetchAttributesAsync(); Assert.IsNotNull(destination.Properties.ETag); Assert.AreNotEqual(source.Properties.ETag, destination.Properties.ETag); Assert.IsTrue(destination.Properties.LastModified > DateTimeOffset.UtcNow.Subtract(TimeSpan.FromMinutes(1))); string copyData = await DownloadTextAsync(destination, Encoding.UTF8); Assert.AreEqual(data, copyData, "Data inside copy of file not equal."); await destination.FetchAttributesAsync(); FileProperties prop1 = destination.Properties; FileProperties prop2 = source.Properties; Assert.AreEqual(prop1.CacheControl, prop2.CacheControl); Assert.AreEqual(prop1.ContentEncoding, prop2.ContentEncoding); Assert.AreEqual(prop1.ContentLanguage, prop2.ContentLanguage); Assert.AreEqual(prop1.ContentMD5, prop2.ContentMD5); Assert.AreEqual(prop1.ContentType, prop2.ContentType); Assert.AreEqual("value", destination.Metadata["Test"], false, "Copied metadata not same"); await destination.DeleteAsync(); await source.DeleteAsync(); } finally { share.DeleteIfExistsAsync().AsTask().Wait(); } }
public void CloudFileSASIPAddressHelper(Func <IPAddressOrRange> generateInitialIPAddressOrRange, Func <IPAddress, IPAddressOrRange> generateFinalIPAddressOrRange) { CloudFileShare share = GetRandomShareReference(); try { share.Create(); CloudFile file; SharedAccessFilePolicy policy = new SharedAccessFilePolicy() { Permissions = SharedAccessFilePermissions.Read, SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5), SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30), }; CloudFile fileWithKey = share.GetRootDirectoryReference().GetFileReference("filefile"); byte[] data = new byte[] { 0x1, 0x2, 0x3, 0x4 }; fileWithKey.UploadFromByteArray(data, 0, 4); // We need an IP address that will never be a valid source IPAddressOrRange ipAddressOrRange = generateInitialIPAddressOrRange(); string fileToken = fileWithKey.GetSharedAccessSignature(policy, null, null, null, ipAddressOrRange); StorageCredentials fileSAS = new StorageCredentials(fileToken); Uri fileSASUri = fileSAS.TransformUri(fileWithKey.Uri); StorageUri fileSASStorageUri = fileSAS.TransformUri(fileWithKey.StorageUri); file = new CloudFile(fileSASUri); byte[] target = new byte[4]; OperationContext opContext = new OperationContext(); IPAddress actualIP = null; opContext.ResponseReceived += (sender, e) => { Stream stream = HttpResponseParsers.GetResponseStream(e.Response); stream.Seek(0, SeekOrigin.Begin); using (StreamReader reader = new StreamReader(stream)) { string text = reader.ReadToEnd(); XDocument xdocument = XDocument.Parse(text); actualIP = IPAddress.Parse(xdocument.Descendants("SourceIP").First().Value); } }; bool exceptionThrown = false; try { file.DownloadRangeToByteArray(target, 0, 0, 4, null, null, opContext); } catch (StorageException) { exceptionThrown = true; //The IP should not be included in the error details for security reasons Assert.IsNull(actualIP); } Assert.IsTrue(exceptionThrown); ipAddressOrRange = null; fileToken = fileWithKey.GetSharedAccessSignature(policy, null, null, null, ipAddressOrRange); fileSAS = new StorageCredentials(fileToken); fileSASUri = fileSAS.TransformUri(fileWithKey.Uri); fileSASStorageUri = fileSAS.TransformUri(fileWithKey.StorageUri); file = new CloudFile(fileSASUri); file.DownloadRangeToByteArray(target, 0, 0, 4, null, null, null); for (int i = 0; i < 4; i++) { Assert.AreEqual(data[i], target[i]); } Assert.IsTrue(file.StorageUri.PrimaryUri.Equals(fileWithKey.Uri)); Assert.IsNull(file.StorageUri.SecondaryUri); file = new CloudFile(fileSASStorageUri, null); file.DownloadRangeToByteArray(target, 0, 0, 4, null, null, null); for (int i = 0; i < 4; i++) { Assert.AreEqual(data[i], target[i]); } Assert.IsTrue(file.StorageUri.Equals(fileWithKey.StorageUri)); } finally { share.DeleteIfExists(); } }
private static async Task TestAccess(string sasToken, SharedAccessFilePermissions permissions, SharedAccessFileHeaders headers, CloudFileShare share, CloudFile file) { CloudFileShare SASshare = null; CloudFile SASfile; OperationContext context = new OperationContext(); StorageCredentials credentials = string.IsNullOrEmpty(sasToken) ? new StorageCredentials() : new StorageCredentials(sasToken); string fileText = "file"; if (share != null) { SASshare = new CloudFileShare(credentials.TransformUri(share.Uri)); SASfile = SASshare.GetRootDirectoryReference().GetFileReference(file.Name); } else { SASfile = new CloudFile(credentials.TransformUri(file.Uri)); } if ((permissions & SharedAccessFilePermissions.Write) == SharedAccessFilePermissions.Write) { await UploadTextAsync(SASfile, fileText, Encoding.UTF8); } else if ((permissions & SharedAccessFilePermissions.Create) == SharedAccessFilePermissions.Create) { await SASfile.CreateAsync(Encoding.UTF8.GetBytes(fileText).Length); context = new OperationContext(); await TestHelper.ExpectedExceptionAsync( async() => await UploadTextAsync(SASfile, fileText, Encoding.UTF8, operationContext: context), context, "UploadText SAS does not allow for writing", HttpStatusCode.Forbidden, ""); await UploadTextAsync(file, fileText, Encoding.UTF8); } else { context = new OperationContext(); await TestHelper.ExpectedExceptionAsync( async() => await SASfile.CreateAsync(Encoding.UTF8.GetBytes(fileText).Length, null /* accessCondition */, null /* options */, context), context, "Create file succeeded but SAS does not allow for writing/creating", HttpStatusCode.Forbidden, ""); context = new OperationContext(); await TestHelper.ExpectedExceptionAsync( async() => await UploadTextAsync(SASfile, fileText, Encoding.UTF8, operationContext: context), context, "UploadText SAS does not allow for writing/creating", HttpStatusCode.Forbidden, ""); await UploadTextAsync(file, fileText, Encoding.UTF8); } if (SASshare != null) { if ((permissions & SharedAccessFilePermissions.List) == SharedAccessFilePermissions.List) { var results = await SASshare.GetRootDirectoryReference().ListFilesAndDirectoriesSegmentedAsync(null); } else { context = new OperationContext(); await TestHelper.ExpectedExceptionAsync( async() => { var results = await SASshare.GetRootDirectoryReference().ListFilesAndDirectoriesSegmentedAsync(null /* maxResults */, null /* currentToken */, null /* options */, context); }, context, "List files while SAS does not allow for listing", HttpStatusCode.Forbidden, ""); } } if ((permissions & SharedAccessFilePermissions.Read) == SharedAccessFilePermissions.Read) { await SASfile.FetchAttributesAsync(); // Test headers if (headers != null) { if (headers.CacheControl != null) { Assert.AreEqual(headers.CacheControl, SASfile.Properties.CacheControl); } if (headers.ContentDisposition != null) { Assert.AreEqual(headers.ContentDisposition, SASfile.Properties.ContentDisposition); } if (headers.ContentEncoding != null) { Assert.AreEqual(headers.ContentEncoding, SASfile.Properties.ContentEncoding); } if (headers.ContentLanguage != null) { Assert.AreEqual(headers.ContentLanguage, SASfile.Properties.ContentLanguage); } if (headers.ContentType != null) { Assert.AreEqual(headers.ContentType, SASfile.Properties.ContentType); } } } else { context = new OperationContext(); await TestHelper.ExpectedExceptionAsync( async() => await SASfile.FetchAttributesAsync(null /* accessCondition */, null /* options */, context), context, "Fetch file attributes while SAS does not allow for reading", HttpStatusCode.Forbidden, ""); } if ((permissions & SharedAccessFilePermissions.Write) == SharedAccessFilePermissions.Write) { await SASfile.SetMetadataAsync(); } else { context = new OperationContext(); await TestHelper.ExpectedExceptionAsync( async() => await SASfile.SetMetadataAsync(null /* accessCondition */, null /* options */, context), context, "Set file metadata while SAS does not allow for writing", HttpStatusCode.Forbidden, ""); } if ((permissions & SharedAccessFilePermissions.Delete) == SharedAccessFilePermissions.Delete) { await SASfile.DeleteAsync(); } else { context = new OperationContext(); await TestHelper.ExpectedExceptionAsync( async() => await SASfile.DeleteAsync(null /* accessCondition */, null /* options */, context), context, "Delete file while SAS does not allow for deleting", HttpStatusCode.Forbidden, ""); } }
private async Task IncrementalCopyAsyncImpl(int overload) { CloudBlobContainer container = GetRandomContainerReference(); try { await container.CreateAsync(); CloudPageBlob source = container.GetPageBlobReference("source"); await source.CreateAsync(1024); string data = new string('a', 512); await UploadTextAsync(source, data, Encoding.UTF8); CloudPageBlob sourceSnapshot = await source.CreateSnapshotAsync(null, null, null, null); SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy() { SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5), SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30), Permissions = SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.Write, }; string sasToken = sourceSnapshot.GetSharedAccessSignature(policy); StorageCredentials blobSAS = new StorageCredentials(sasToken); Uri sourceSnapshotUri = blobSAS.TransformUri(TestHelper.Defiddler(sourceSnapshot).SnapshotQualifiedUri); StorageCredentials accountSAS = new StorageCredentials(sasToken); CloudStorageAccount accountWithSAS = new CloudStorageAccount(accountSAS, source.ServiceClient.StorageUri, null, null, null); CloudPageBlob snapshotWithSas = await accountWithSAS.CreateCloudBlobClient().GetBlobReferenceFromServerAsync(sourceSnapshot.SnapshotQualifiedUri) as CloudPageBlob; CloudPageBlob copy = container.GetPageBlobReference("copy"); string copyId = null; if (overload == 0) { #if !FACADE_NETCORE copyId = await copy.StartIncrementalCopyAsync(accountSAS.TransformUri(TestHelper.Defiddler(snapshotWithSas).SnapshotQualifiedUri)); #else Uri snapShotQualifiedUri = accountSAS.TransformUri(TestHelper.Defiddler(snapshotWithSas).SnapshotQualifiedUri); copyId = await copy.StartIncrementalCopyAsync(new CloudPageBlob(new StorageUri(snapShotQualifiedUri), null, null)); #endif } else if (overload == 1) { #if !FACADE_NETCORE CloudPageBlob blob = new CloudPageBlob(accountSAS.TransformUri(TestHelper.Defiddler(snapshotWithSas).SnapshotQualifiedUri)); #else Uri snapShotQualifiedUri = accountSAS.TransformUri(TestHelper.Defiddler(snapshotWithSas).SnapshotQualifiedUri); CloudPageBlob blob = new CloudPageBlob(new StorageUri(snapShotQualifiedUri), null, null); #endif copyId = await copy.StartIncrementalCopyAsync(blob); } else if (overload == 2) { #if !FACADE_NETCORE CloudPageBlob blob = new CloudPageBlob(accountSAS.TransformUri(TestHelper.Defiddler(snapshotWithSas).SnapshotQualifiedUri)); #else Uri snapShotQualifiedUri = accountSAS.TransformUri(TestHelper.Defiddler(snapshotWithSas).SnapshotQualifiedUri); CloudPageBlob blob = new CloudPageBlob(new StorageUri(snapShotQualifiedUri), null, null); #endif copyId = await copy.StartIncrementalCopyAsync(blob, null, null, null, CancellationToken.None); } else { #if !FACADE_NETCORE copyId = await copy.StartIncrementalCopyAsync(accountSAS.TransformUri(TestHelper.Defiddler(snapshotWithSas).SnapshotQualifiedUri), null, null, null, CancellationToken.None); #else Uri snapShotQualifiedUri = accountSAS.TransformUri(TestHelper.Defiddler(snapshotWithSas).SnapshotQualifiedUri); CloudPageBlob blob = new CloudPageBlob(new StorageUri(snapShotQualifiedUri), null, null); copyId = await copy.StartIncrementalCopyAsync(blob, null, null, null, CancellationToken.None); #endif } await WaitForCopyAsync(copy); Assert.AreEqual(BlobType.PageBlob, copy.BlobType); Assert.AreEqual(CopyStatus.Success, copy.CopyState.Status); Assert.AreEqual(source.Uri.AbsolutePath, copy.CopyState.Source.AbsolutePath); Assert.AreEqual(data.Length, copy.CopyState.TotalBytes); Assert.AreEqual(data.Length, copy.CopyState.BytesCopied); Assert.AreEqual(copyId, copy.CopyState.CopyId); Assert.IsTrue(copy.Properties.IsIncrementalCopy); Assert.IsTrue(copy.CopyState.DestinationSnapshotTime.HasValue); Assert.IsTrue(copy.CopyState.CompletionTime > DateTimeOffset.UtcNow.Subtract(TimeSpan.FromMinutes(1))); } finally { container.DeleteIfExistsAsync().Wait(); } }
public async Task CloudBlobContainerGetBlobReferenceFromServerAsync() { CloudBlobContainer container = GetRandomContainerReference(); try { await container.CreateAsync(); SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy() { Permissions = SharedAccessBlobPermissions.Read, SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5), SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30), }; CloudBlockBlob blockBlob = container.GetBlockBlobReference("bb"); await blockBlob.PutBlockListAsync(new List <string>()); CloudPageBlob pageBlob = container.GetPageBlobReference("pb"); await pageBlob.CreateAsync(0); ICloudBlob blob1 = await container.GetBlobReferenceFromServerAsync("bb"); Assert.IsInstanceOfType(blob1, typeof(CloudBlockBlob)); CloudBlockBlob blob1Snapshot = await((CloudBlockBlob)blob1).CreateSnapshotAsync(); await blob1.SetPropertiesAsync(); Uri blob1SnapshotUri = new Uri(blob1Snapshot.Uri.AbsoluteUri + "?snapshot=" + blob1Snapshot.SnapshotTime.Value.UtcDateTime.ToString("o")); ICloudBlob blob1SnapshotReference = await container.ServiceClient.GetBlobReferenceFromServerAsync(blob1SnapshotUri); AssertAreEqual(blob1Snapshot.Properties, blob1SnapshotReference.Properties); ICloudBlob blob2 = await container.GetBlobReferenceFromServerAsync("pb"); Assert.IsInstanceOfType(blob2, typeof(CloudPageBlob)); CloudPageBlob blob2Snapshot = await((CloudPageBlob)blob2).CreateSnapshotAsync(); await blob2.SetPropertiesAsync(); Uri blob2SnapshotUri = new Uri(blob2Snapshot.Uri.AbsoluteUri + "?snapshot=" + blob2Snapshot.SnapshotTime.Value.UtcDateTime.ToString("o")); ICloudBlob blob2SnapshotReference = await container.ServiceClient.GetBlobReferenceFromServerAsync(blob2SnapshotUri); AssertAreEqual(blob2Snapshot.Properties, blob2SnapshotReference.Properties); ICloudBlob blob3 = await container.ServiceClient.GetBlobReferenceFromServerAsync(blockBlob.Uri); Assert.IsInstanceOfType(blob3, typeof(CloudBlockBlob)); ICloudBlob blob4 = await container.ServiceClient.GetBlobReferenceFromServerAsync(pageBlob.Uri); Assert.IsInstanceOfType(blob4, typeof(CloudPageBlob)); string blockBlobToken = blockBlob.GetSharedAccessSignature(policy); StorageCredentials blockBlobSAS = new StorageCredentials(blockBlobToken); Uri blockBlobSASUri = blockBlobSAS.TransformUri(blockBlob.Uri); string pageBlobToken = pageBlob.GetSharedAccessSignature(policy); StorageCredentials pageBlobSAS = new StorageCredentials(pageBlobToken); Uri pageBlobSASUri = pageBlobSAS.TransformUri(pageBlob.Uri); ICloudBlob blob5 = await container.ServiceClient.GetBlobReferenceFromServerAsync(blockBlobSASUri); Assert.IsInstanceOfType(blob5, typeof(CloudBlockBlob)); ICloudBlob blob6 = await container.ServiceClient.GetBlobReferenceFromServerAsync(pageBlobSASUri); Assert.IsInstanceOfType(blob6, typeof(CloudPageBlob)); CloudBlobClient client7 = new CloudBlobClient(container.ServiceClient.BaseUri, blockBlobSAS); ICloudBlob blob7 = await client7.GetBlobReferenceFromServerAsync(blockBlobSASUri); Assert.IsInstanceOfType(blob7, typeof(CloudBlockBlob)); CloudBlobClient client8 = new CloudBlobClient(container.ServiceClient.BaseUri, pageBlobSAS); ICloudBlob blob8 = await client8.GetBlobReferenceFromServerAsync(pageBlobSASUri); Assert.IsInstanceOfType(blob8, typeof(CloudPageBlob)); } finally { container.DeleteIfExistsAsync().AsTask().Wait(); } }
public void CloudBlobContainerGetBlobReferenceFromServerAPM() { CloudBlobContainer container = GetRandomContainerReference(); try { container.Create(); SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy() { Permissions = SharedAccessBlobPermissions.Read, SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5), SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30), }; CloudBlockBlob blockBlob = container.GetBlockBlobReference("bb"); blockBlob.PutBlockList(new string[] { }); CloudPageBlob pageBlob = container.GetPageBlobReference("pb"); pageBlob.Create(0); using (AutoResetEvent waitHandle = new AutoResetEvent(false)) { IAsyncResult result = container.BeginGetBlobReferenceFromServer("bb", ar => waitHandle.Set(), null); waitHandle.WaitOne(); ICloudBlob blob1 = container.EndGetBlobReferenceFromServer(result); Assert.IsInstanceOfType(blob1, typeof(CloudBlockBlob)); result = ((CloudBlockBlob)blob1).BeginCreateSnapshot( ar => waitHandle.Set(), null); waitHandle.WaitOne(); CloudBlockBlob blob1Snapshot = ((CloudBlockBlob)blob1).EndCreateSnapshot(result); result = blob1.BeginSetProperties( ar => waitHandle.Set(), null); waitHandle.WaitOne(); blob1.EndSetProperties(result); Uri blob1SnapshotUri = new Uri(blob1Snapshot.Uri.AbsoluteUri + "?snapshot=" + blob1Snapshot.SnapshotTime.Value.UtcDateTime.ToString("o")); result = container.ServiceClient.BeginGetBlobReferenceFromServer(blob1SnapshotUri, ar => waitHandle.Set(), null); waitHandle.WaitOne(); ICloudBlob blob1SnapshotReference = container.ServiceClient.EndGetBlobReferenceFromServer(result); AssertAreEqual(blob1Snapshot.Properties, blob1SnapshotReference.Properties); result = container.BeginGetBlobReferenceFromServer("pb", ar => waitHandle.Set(), null); waitHandle.WaitOne(); ICloudBlob blob2 = container.EndGetBlobReferenceFromServer(result); Assert.IsInstanceOfType(blob2, typeof(CloudPageBlob)); result = ((CloudPageBlob)blob2).BeginCreateSnapshot( ar => waitHandle.Set(), null); waitHandle.WaitOne(); CloudPageBlob blob2Snapshot = ((CloudPageBlob)blob2).EndCreateSnapshot(result); result = blob2.BeginSetProperties( ar => waitHandle.Set(), null); waitHandle.WaitOne(); blob2.EndSetProperties(result); Uri blob2SnapshotUri = new Uri(blob2Snapshot.Uri.AbsoluteUri + "?snapshot=" + blob2Snapshot.SnapshotTime.Value.UtcDateTime.ToString("o")); result = container.ServiceClient.BeginGetBlobReferenceFromServer(blob2SnapshotUri, ar => waitHandle.Set(), null); waitHandle.WaitOne(); ICloudBlob blob2SnapshotReference = container.ServiceClient.EndGetBlobReferenceFromServer(result); AssertAreEqual(blob2Snapshot.Properties, blob2SnapshotReference.Properties); result = container.ServiceClient.BeginGetBlobReferenceFromServer(blockBlob.Uri, ar => waitHandle.Set(), null); waitHandle.WaitOne(); ICloudBlob blob3 = container.ServiceClient.EndGetBlobReferenceFromServer(result); Assert.IsInstanceOfType(blob3, typeof(CloudBlockBlob)); result = container.ServiceClient.BeginGetBlobReferenceFromServer(pageBlob.Uri, ar => waitHandle.Set(), null); waitHandle.WaitOne(); ICloudBlob blob4 = container.ServiceClient.EndGetBlobReferenceFromServer(result); Assert.IsInstanceOfType(blob4, typeof(CloudPageBlob)); string blockBlobToken = blockBlob.GetSharedAccessSignature(policy); StorageCredentials blockBlobSAS = new StorageCredentials(blockBlobToken); Uri blockBlobSASUri = blockBlobSAS.TransformUri(blockBlob.Uri); string pageBlobToken = pageBlob.GetSharedAccessSignature(policy); StorageCredentials pageBlobSAS = new StorageCredentials(pageBlobToken); Uri pageBlobSASUri = pageBlobSAS.TransformUri(pageBlob.Uri); result = container.ServiceClient.BeginGetBlobReferenceFromServer(blockBlobSASUri, ar => waitHandle.Set(), null); waitHandle.WaitOne(); ICloudBlob blob5 = container.ServiceClient.EndGetBlobReferenceFromServer(result); Assert.IsInstanceOfType(blob5, typeof(CloudBlockBlob)); result = container.ServiceClient.BeginGetBlobReferenceFromServer(pageBlobSASUri, ar => waitHandle.Set(), null); waitHandle.WaitOne(); ICloudBlob blob6 = container.ServiceClient.EndGetBlobReferenceFromServer(result); Assert.IsInstanceOfType(blob6, typeof(CloudPageBlob)); CloudBlobClient client7 = new CloudBlobClient(container.ServiceClient.BaseUri, blockBlobSAS); result = client7.BeginGetBlobReferenceFromServer(blockBlobSASUri, ar => waitHandle.Set(), null); waitHandle.WaitOne(); ICloudBlob blob7 = client7.EndGetBlobReferenceFromServer(result); Assert.IsInstanceOfType(blob7, typeof(CloudBlockBlob)); CloudBlobClient client8 = new CloudBlobClient(container.ServiceClient.BaseUri, pageBlobSAS); result = client8.BeginGetBlobReferenceFromServer(pageBlobSASUri, ar => waitHandle.Set(), null); waitHandle.WaitOne(); ICloudBlob blob8 = client8.EndGetBlobReferenceFromServer(result); Assert.IsInstanceOfType(blob8, typeof(CloudPageBlob)); } } finally { container.DeleteIfExists(); } }
public RESTCommand(StorageCredentials credentials, Uri uri, UriQueryBuilder builder) { this.Uri = credentials.TransformUri(uri); this.Builder = builder; }