/// <summary> /// Converts the permissions specified for the shared access policy to a string. /// </summary> /// <param name="permissions">A <see cref="SharedAccessFilePermissions"/> object.</param> /// <returns>The shared access permissions, in string format.</returns> public static string PermissionsToString(SharedAccessFilePermissions permissions) { // The service supports a fixed order => rcwdl StringBuilder builder = new StringBuilder(); if ((permissions & SharedAccessFilePermissions.Read) == SharedAccessFilePermissions.Read) { builder.Append("r"); } if ((permissions & SharedAccessFilePermissions.Create) == SharedAccessFilePermissions.Create) { builder.Append("c"); } if ((permissions & SharedAccessFilePermissions.Write) == SharedAccessFilePermissions.Write) { builder.Append("w"); } if ((permissions & SharedAccessFilePermissions.Delete) == SharedAccessFilePermissions.Delete) { builder.Append("d"); } if ((permissions & SharedAccessFilePermissions.List) == SharedAccessFilePermissions.List) { builder.Append("l"); } return(builder.ToString()); }
/// <summary> /// Converts the permissions specified for the shared access policy to a string. /// </summary> /// <param name="permissions">A <see cref="SharedAccessFilePermissions"/> object.</param> /// <returns>The shared access permissions, in string format.</returns> public static string PermissionsToString(SharedAccessFilePermissions permissions) { // The service supports a fixed order => rcwdl StringBuilder builder = new StringBuilder(); if ((permissions & SharedAccessFilePermissions.Read) == SharedAccessFilePermissions.Read) { builder.Append("r"); } if ((permissions & SharedAccessFilePermissions.Create) == SharedAccessFilePermissions.Create) { builder.Append("c"); } if ((permissions & SharedAccessFilePermissions.Write) == SharedAccessFilePermissions.Write) { builder.Append("w"); } if ((permissions & SharedAccessFilePermissions.Delete) == SharedAccessFilePermissions.Delete) { builder.Append("d"); } if ((permissions & SharedAccessFilePermissions.List) == SharedAccessFilePermissions.List) { builder.Append("l"); } return builder.ToString(); }
/// <summary> /// Gets the file share Uri with SAS. /// </summary> /// <param name="permissions">The permissions for a shared access signature associated with this shared access policy.</param> /// <param name="startTime">The start time for a shared access signature associated with this shared access policy.</param> /// <param name="endTime">The expiry time for a shared access signature associated with this shared access policy.</param> /// <returns>The file share Uri with SAS.</returns> public Uri GetFileShareUriWithSas(SharedAccessFilePermissions permissions = SharedAccessFilePermissions.Read, DateTimeOffset?startTime = null, DateTimeOffset?endTime = null) { var uriBuilder = new UriBuilder(this._cloudFileShare.Uri); uriBuilder.Query = this.GetFileShareSas(permissions, startTime, endTime).TrimStart('?'); return(uriBuilder.Uri); }
public void CloudFileSASCombinations() { for (int i = 1; i < 0x20; i++) { CloudFile testFile = this.testShare.GetRootDirectoryReference().GetFileReference("file" + i); SharedAccessFilePermissions permissions = (SharedAccessFilePermissions)i; TestFileSAS(testFile, permissions, null); } }
/// <summary> /// Returns a shared access signature for the file share. /// </summary> /// <param name="permissions">The permissions for a shared access signature associated with this shared access policy.</param> /// <param name="startTime">The start time for a shared access signature associated with this shared access policy.</param> /// <param name="endTime">The expiry time for a shared access signature associated with this shared access policy.</param> /// <returns>The query string returned includes the leading question mark.</returns> public string GetFileShareSas(SharedAccessFilePermissions permissions = SharedAccessFilePermissions.Read, DateTimeOffset?startTime = null, DateTimeOffset?endTime = null) { return(this._cloudFileShare.GetSharedAccessSignature(new SharedAccessFilePolicy { Permissions = permissions, SharedAccessStartTime = startTime, SharedAccessExpiryTime = endTime })); }
/// <summary> /// Returns a shared access signature for the file. /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="directoryName">A System.String containing the name of the subdirectory; null will get the root directory.</param> /// <param name="permissions">The permissions for a shared access signature associated with this shared access policy.</param> /// <param name="startTime">The start time for a shared access signature associated with this shared access policy.</param> /// <param name="endTime">The expiry time for a shared access signature associated with this shared access policy.</param> /// <returns>The query string returned includes the leading question mark.</returns> public string GetFileSas(string fileName, string directoryName = null, SharedAccessFilePermissions permissions = SharedAccessFilePermissions.Read, DateTimeOffset?startTime = null, DateTimeOffset?endTime = null) { return(this.GetFile(fileName, directoryName).GetSharedAccessSignature(new SharedAccessFilePolicy { Permissions = permissions, SharedAccessStartTime = startTime, SharedAccessExpiryTime = endTime })); }
/// <summary> /// Gets the file share Uri with SAS. /// </summary> /// <param name="permissions">The permissions for a shared access signature associated with this shared access policy.</param> /// <param name="startTime">The start time for a shared access signature associated with this shared access policy.</param> /// <param name="endTime">The expiry time for a shared access signature associated with this shared access policy.</param> /// <param name="cancellationToken">A <see cref="T:System.Threading.CancellationToken" /> to observe while waiting for a task to complete.</param> /// <returns>The file share Uri with SAS.</returns> public Task <Uri> GetFileShareUriWithSasAsync(SharedAccessFilePermissions permissions = SharedAccessFilePermissions.Read, DateTimeOffset?startTime = null, DateTimeOffset?endTime = null, CancellationToken?cancellationToken = null) { return(Task.Run(() => { var uriBuilder = new UriBuilder(this._cloudFileShare.Uri); uriBuilder.Query = this.GetFileShareSas(permissions, startTime, endTime).TrimStart('?'); return uriBuilder.Uri; }, cancellationToken ?? CancellationToken.None)); }
/// <summary> /// Returns a shared access signature for the file share. /// </summary> /// <param name="permissions">The permissions for a shared access signature associated with this shared access policy.</param> /// <param name="startTime">The start time for a shared access signature associated with this shared access policy.</param> /// <param name="endTime">The expiry time for a shared access signature associated with this shared access policy.</param> /// <param name="cancellationToken">A <see cref="T:System.Threading.CancellationToken" /> to observe while waiting for a task to complete.</param> /// <returns>The query string returned includes the leading question mark.</returns> public Task <string> GetFileShareSasAsync(SharedAccessFilePermissions permissions = SharedAccessFilePermissions.Read, DateTimeOffset?startTime = null, DateTimeOffset?endTime = null, CancellationToken?cancellationToken = null) { return(Task.Run(() => { return this._cloudFileShare.GetSharedAccessSignature(new SharedAccessFilePolicy { Permissions = permissions, SharedAccessStartTime = startTime, SharedAccessExpiryTime = endTime }); }, cancellationToken ?? CancellationToken.None)); }
private static void TestFileSAS(CloudFile testFile, SharedAccessFilePermissions permissions, SharedAccessFileHeaders headers) { SharedAccessFilePolicy policy = new SharedAccessFilePolicy() { SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5), SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30), Permissions = permissions, }; string sasToken = testFile.GetSharedAccessSignature(policy, headers, null); TestAccess(sasToken, permissions, headers, null, testFile); }
/// <summary> /// Gets the file Uri with SAS. /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="directoryName">A System.String containing the name of the subdirectory; null will get the root directory.</param> /// <param name="permissions">The permissions for a shared access signature associated with this shared access policy.</param> /// <param name="startTime">The start time for a shared access signature associated with this shared access policy.</param> /// <param name="endTime">The expiry time for a shared access signature associated with this shared access policy.</param> /// <returns>The file Uri with SAS.</returns> public Uri GetFileUriWithSas(string fileName, string directoryName = null, SharedAccessFilePermissions permissions = SharedAccessFilePermissions.Read, DateTimeOffset?startTime = null, DateTimeOffset?endTime = null) { var file = this.GetFile(fileName, directoryName); var uriBuilder = new UriBuilder(file.Uri); uriBuilder.Query = file.GetSharedAccessSignature(new SharedAccessFilePolicy() { Permissions = permissions, SharedAccessStartTime = startTime, SharedAccessExpiryTime = endTime }).TrimStart('?'); return(uriBuilder.Uri); }
public void CloudFileShareSASCombinations() { for (int i = 1; i < 0x20; i++) { SharedAccessFilePermissions permissions = (SharedAccessFilePermissions)i; SharedAccessFilePolicy policy = new SharedAccessFilePolicy() { SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5), SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30), Permissions = permissions, }; string sasToken = this.testShare.GetSharedAccessSignature(policy); CloudFile testFile = this.testShare.GetRootDirectoryReference().GetFileReference("file" + i); FileSASTests.TestAccess(sasToken, permissions, null, this.testShare, testFile); } }
public void CloudFileSASHeaders() { for (int i = 1; i < 0x20; i++) { CloudFile testFile = this.testShare.GetRootDirectoryReference().GetFileReference("file" + i); SharedAccessFilePermissions permissions = (SharedAccessFilePermissions)i; SharedAccessFileHeaders headers = new SharedAccessFileHeaders() { CacheControl = "no-transform", ContentDisposition = "attachment", ContentEncoding = "gzip", ContentLanguage = "tr,en", ContentType = "text/html" }; TestFileSAS(testFile, permissions, headers); } }
/// <summary> /// Constructs a <see cref="SharedAccessFilePermissions"/> object from a permissions string. /// </summary> /// <param name="input">The shared access permissions, in string format.</param> /// <returns>A <see cref="SharedAccessFilePermissions"/> object.</returns> public static SharedAccessFilePermissions PermissionsFromString(string input) { CommonUtility.AssertNotNull("input", input); SharedAccessFilePermissions permissions = 0; foreach (char c in input) { switch (c) { case 'r': permissions |= SharedAccessFilePermissions.Read; break; case 'w': permissions |= SharedAccessFilePermissions.Write; break; case 'd': permissions |= SharedAccessFilePermissions.Delete; break; case 'l': permissions |= SharedAccessFilePermissions.List; break; case 'c': permissions |= SharedAccessFilePermissions.Create; break; default: throw new ArgumentOutOfRangeException("input"); } } // In case we ever change none to be something other than 0 if (permissions == 0) { permissions |= SharedAccessFilePermissions.None; } return(permissions); }
private static void TestFileSAS(CloudFile testFile, SharedAccessFilePermissions permissions, SharedAccessFileHeaders headers) { UploadText(testFile, "file", Encoding.UTF8); SharedAccessFilePolicy policy = new SharedAccessFilePolicy() { SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5), SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30), Permissions = permissions, }; string sasToken = testFile.GetSharedAccessSignature(policy, headers, null); TestAccess(sasToken, permissions, headers, null, testFile); }
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); } }
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); } }
public static string PermissionsToString(SharedAccessFilePermissions permissions) { throw new System.NotImplementedException(); }
private static async Task TestFileSAS(CloudFile testFile, SharedAccessFilePermissions permissions, SharedAccessFileHeaders headers) { SharedAccessFilePolicy policy = new SharedAccessFilePolicy() { SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5), SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30), Permissions = permissions, }; string sasToken = testFile.GetSharedAccessSignature(policy, headers, null); await TestAccess(sasToken, permissions, headers, null, testFile); }
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 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(); } }
/// <summary> /// Gets the file Uri with SAS. /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="directoryName">A System.String containing the name of the subdirectory; null will get the root directory.</param> /// <param name="permissions">The permissions for a shared access signature associated with this shared access policy.</param> /// <param name="startTime">The start time for a shared access signature associated with this shared access policy.</param> /// <param name="endTime">The expiry time for a shared access signature associated with this shared access policy.</param> /// <param name="cancellationToken">A <see cref="T:System.Threading.CancellationToken" /> to observe while waiting for a task to complete.</param> /// <returns>The file Uri with SAS.</returns> public Task <Uri> GetFileUriWithSasAsync(string fileName, string directoryName = null, SharedAccessFilePermissions permissions = SharedAccessFilePermissions.Read, DateTimeOffset?startTime = null, DateTimeOffset?endTime = null, CancellationToken?cancellationToken = null) { fileName.ValidateFileName(); if (directoryName != null) { directoryName.ValidateDirectoryName(); } return(Task.Run(() => { var rootDirectory = this._cloudFileShare.GetRootDirectoryReference(); var directory = directoryName != null ? rootDirectory.GetDirectoryReference(directoryName) : rootDirectory; var file = directory.GetFileReference(fileName); var uriBuilder = new UriBuilder(file.Uri); uriBuilder.Query = file.GetSharedAccessSignature(new SharedAccessFilePolicy() { Permissions = permissions, SharedAccessStartTime = startTime, SharedAccessExpiryTime = endTime }).TrimStart('?'); return uriBuilder.Uri; }, cancellationToken ?? CancellationToken.None)); }
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 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(); } }