/// <summary> /// Validate the table access policy /// </summary> /// <param name="policy">SharedAccessBlobPolicy object</param> /// <param name="policyIdentifier">The policy identifier which need to be checked.</param> internal static bool ValidateTableAccessPolicy(IStorageTableManagement channel, string tableName, SharedAccessTablePolicy policy, string policyIdentifier) { if (string.IsNullOrEmpty(policyIdentifier)) { return(true); } CloudTable table = channel.GetTableReference(tableName); TableRequestOptions options = null; OperationContext context = null; TablePermissions permission = channel.GetTablePermissions(table, options, context); SharedAccessTablePolicy sharedAccessPolicy = GetExistingPolicy <SharedAccessTablePolicy>(permission.SharedAccessPolicies, policyIdentifier); if (policy.Permissions != SharedAccessTablePermissions.None) { throw new ArgumentException(Resources.SignedPermissionsMustBeOmitted); } if (policy.SharedAccessExpiryTime.HasValue && sharedAccessPolicy.SharedAccessExpiryTime.HasValue) { throw new ArgumentException(Resources.SignedExpiryTimeMustBeOmitted); } return(!sharedAccessPolicy.SharedAccessExpiryTime.HasValue); }
internal async Task <SharedAccessTablePolicies> GetPoliciesAsync(IStorageTableManagement localChannel, string tableName, string policyName) { CloudTable table = localChannel.GetTableReference(tableName); TablePermissions tablePermissions = await localChannel.GetTablePermissionsAsync(table); return(tablePermissions.SharedAccessPolicies); }
public void TableSetPermissionsPermissionsRequestOptionsOperationContextCancellationTokenTask() { CloudTableClient tableClient = GenerateCloudTableClient(); string tableName = GenerateRandomTableName(); CloudTable table = tableClient.GetTableReference(tableName); TablePermissions permissions = new TablePermissions(); TableRequestOptions requestOptions = new TableRequestOptions(); OperationContext operationContext = new OperationContext(); CancellationToken cancellationToken = CancellationToken.None; permissions.SharedAccessPolicies.Add(Guid.NewGuid().ToString(), new SharedAccessTablePolicy() { Permissions = SharedAccessTablePermissions.Query, SharedAccessStartTime = DateTimeOffset.Now.Add(new TimeSpan(-1, 0, 0)), SharedAccessExpiryTime = DateTimeOffset.Now.Add(new TimeSpan(1, 0, 0)) }); try { table.CreateAsync().Wait(); table.ExecuteAsync(TableOperation.Insert(new BaseEntity("PK", "RK"))).Wait(); table.SetPermissionsAsync(permissions, requestOptions, operationContext, cancellationToken); } finally { table.DeleteIfExistsAsync().Wait(); } }
internal string CreateAzureTableStoredAccessPolicy(IStorageTableManagement localChannel, string tableName, string policyName, DateTime?startTime, DateTime?expiryTime, string permission) { if (!NameUtil.IsValidStoredAccessPolicyName(policyName)) { throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Resources.InvalidAccessPolicyName, policyName)); } //Get existing permissions CloudTable table = localChannel.GetTableReference(tableName); TablePermissions tablePermissions = localChannel.GetTablePermissions(table); //Add new policy if (tablePermissions.SharedAccessPolicies.Keys.Contains(policyName)) { throw new ResourceAlreadyExistException(String.Format(CultureInfo.CurrentCulture, Resources.PolicyAlreadyExists, policyName)); } SharedAccessTablePolicy policy = new SharedAccessTablePolicy(); AccessPolicyHelper.SetupAccessPolicy <SharedAccessTablePolicy>(policy, startTime, expiryTime, permission); tablePermissions.SharedAccessPolicies.Add(policyName, policy); //Set permissions back to table localChannel.SetTablePermissions(table, tablePermissions); return(policyName); }
public void NewTableSasWithPolicy() { CloudTable table = tableUtil.CreateTable(); try { TimeSpan sasLifeTime = TimeSpan.FromMinutes(10); TablePermissions permission = new TablePermissions(); string policyName = Utility.GenNameString("saspolicy"); permission.SharedAccessPolicies.Add(policyName, new SharedAccessTablePolicy { SharedAccessExpiryTime = DateTime.Now.Add(sasLifeTime), Permissions = SharedAccessTablePermissions.Query }); table.SetPermissions(permission); string sasToken = CommandAgent.GetTableSasFromCmd(table.Name, policyName, string.Empty); Test.Info("Sleep and wait for sas policy taking effect"); double lifeTime = 1; Thread.Sleep(TimeSpan.FromMinutes(lifeTime)); ValidateSasToken(table, "r", sasToken); } finally { tableUtil.RemoveTable(table); } }
public static Task SetPermissionsAsync(this CloudTable tbl, TablePermissions perms, TableRequestOptions opt, OperationContext ctx, CancellationToken token) { ICancellableAsyncResult result = null; if (opt == null && ctx == null) { result = tbl.BeginSetPermissions(perms, null, null); } else { result = tbl.BeginSetPermissions(perms, opt, ctx, null, null); } var cancellationRegistration = token.Register(result.Cancel); return(Task.Factory.FromAsync(result, ar => { cancellationRegistration.Dispose(); try { tbl.EndSetPermissions(ar); } catch (StorageException se) { // Todo: Use the PnP azure retry block here for transient exceptions throw; } })); }
internal string SetAzureTableStoredAccessPolicy(IStorageTableManagement localChannel, string tableName, string policyName, DateTime?startTime, DateTime?expiryTime, string permission, bool noStartTime, bool noExpiryTime) { DateTime?startTimeToSet = startTime; DateTime?expiryTimetoSet = expiryTime; //Get existing permissions CloudTable table = localChannel.GetTableReference(Table); TablePermissions tablePermissions = localChannel.GetTablePermissions(table, this.RequestOptions, this.TableOperationContext); //Set the policy with new value if (!tablePermissions.SharedAccessPolicies.Keys.Contains(policyName)) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.PolicyNotFound, policyName)); } SharedAccessTablePolicy policy = tablePermissions.SharedAccessPolicies[policyName]; AccessPolicyHelper.SetupAccessPolicy <SharedAccessTablePolicy>(policy, startTime, expiryTime, permission, noStartTime, noExpiryTime); tablePermissions.SharedAccessPolicies[policyName] = policy; //Set permission back to table localChannel.SetTablePermissions(table, tablePermissions, null, TableOperationContext); WriteObject(AccessPolicyHelper.ConstructPolicyOutputPSObject <SharedAccessTablePolicy>(tablePermissions.SharedAccessPolicies, policyName)); return(policyName); }
/// <summary> /// Creates a shared access policy on the table. /// </summary> /// <param name="table">A CloudTable object.</param> /// <param name="policyName">The name of the stored access policy.</param> /// <returns>A Task object</returns> private static async Task CreateSharedAccessPolicy(CloudTable table, string policyName) { // Create a new shared access policy and define its constraints. // The access policy provides add, update, and query permissions. SharedAccessTablePolicy sharedPolicy = new SharedAccessTablePolicy() { // Permissions enable users to add, update, query, and delete entities in the table. SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24), Permissions = SharedAccessTablePermissions.Add | SharedAccessTablePermissions.Update | SharedAccessTablePermissions.Query | SharedAccessTablePermissions.Delete }; try { // Get the table's existing permissions. TablePermissions permissions = await table.GetPermissionsAsync(); // Add the new policy to the table's permissions, and update the table's permissions. permissions.SharedAccessPolicies.Add(policyName, sharedPolicy); await table.SetPermissionsAsync(permissions); } catch (StorageException e) { Console.WriteLine(e.Message); Console.ReadLine(); throw; } }
/// <summary> /// Manage stored access policies specified on the table /// </summary> /// <param name="table"></param> /// <returns></returns> private static async Task TableAclSample(CloudTable table) { // Set table permissions SharedAccessTablePolicy accessTablePolicy = new SharedAccessTablePolicy(); accessTablePolicy.SharedAccessStartTime = new DateTimeOffset(DateTime.Now); accessTablePolicy.SharedAccessExpiryTime = new DateTimeOffset(DateTime.Now.AddMinutes(10)); accessTablePolicy.Permissions = SharedAccessTablePermissions.Update; TablePermissions permissions = new TablePermissions(); permissions.SharedAccessPolicies.Add("key1", accessTablePolicy); Console.WriteLine("Set table permissions"); await table.SetPermissionsAsync(permissions); // Get table permissions Console.WriteLine("Get table permissions:"); permissions = await table.GetPermissionsAsync(); foreach (var keyValue in permissions.SharedAccessPolicies) { Console.WriteLine(" {0}:", keyValue.Key); Console.WriteLine(" permissions: {0}:", keyValue.Value.Permissions); Console.WriteLine(" start time: {0}:", keyValue.Value.SharedAccessStartTime); Console.WriteLine(" expiry time: {0}:", keyValue.Value.SharedAccessExpiryTime); } }
public MockCloudTable(Uri address, ICloudTableClient client) { _uri = address; _client = client; _credentials = null; _entries = null; _permissions = new TablePermissions(); }
public MockCloudTable(Uri tableAbsoluteUri, StorageCredentials credentials) { _client = null; _uri = tableAbsoluteUri; _entries = null; _permissions = new TablePermissions(); _credentials = credentials; }
internal override void RemoveReferences() { base.RemoveReferences(); foreach (var tp in TablePermissions) { tp.DependsOn.Keys.ToList().ForEach(d => d.ReferencedBy.Remove(tp)); tp.DependsOn.Clear(); } TablePermissions.Clear(); }
/// <summary> /// Set table permission /// </summary> /// <param name="table">Cloud table object</param> /// <param name="tablePermissions">table permissions</param> /// <param name="requestOptions">Table request options</param> /// <param name="operationContext">Operation context</param> /// <returns></returns> public void SetTablePermissions(CloudTable table, TablePermissions tablePermissions, TableRequestOptions requestOptions, XTable.OperationContext operationContext) { try { Task.Run(() => table.SetPermissionsAsync(tablePermissions, requestOptions, operationContext)).Wait(); } catch (AggregateException e) when(e.InnerException is XTable.StorageException) { throw e.InnerException; } }
static void InitStorageAccount() { CloudStorageAccount storageAccount = CreateStorageAccount(); var blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer updatesContainer = blobClient.GetContainerReference(settings.UpdatesBlobContainerName); Console.Write("Creating updates blob container ... "); Console.WriteLine(updatesContainer.CreateIfNotExists() ? "Created" : "Already exists"); BlobContainerPermissions updatesContainerPermissions = new BlobContainerPermissions(); updatesContainerPermissions.PublicAccess = BlobContainerPublicAccessType.Blob; Console.Write("Setting permissions on the blob container ... "); updatesContainer.SetPermissions(updatesContainerPermissions); Console.WriteLine("Done"); var tableClient = storageAccount.CreateCloudTableClient(); var telemetryTable = tableClient.GetTableReference(settings.TelemetryTableName); Console.Write("Creating telemetry table ... "); Console.WriteLine(telemetryTable.CreateIfNotExists() ? "Created" : "Already exists"); var tablePermissions = new TablePermissions(); tablePermissions.SharedAccessPolicies.Add(settings.StoredClientsAccessPolicyName, new SharedAccessTablePolicy() { SharedAccessExpiryTime = DateTime.MaxValue, Permissions = SharedAccessTablePermissions.Add }); Console.Write("Setting permissions on telemetry table ... "); telemetryTable.SetPermissions(tablePermissions); CloudBlobContainer issuesContainer = blobClient.GetContainerReference(settings.IssuesBlobContainerName); Console.Write("Creating issues container ... "); Console.WriteLine(issuesContainer.CreateIfNotExists() ? "Created" : "Already exists"); BlobContainerPermissions issuesContainerPermissions = new BlobContainerPermissions(); issuesContainerPermissions.SharedAccessPolicies.Add(settings.StoredClientsAccessPolicyName, new SharedAccessBlobPolicy() { SharedAccessExpiryTime = DateTime.MaxValue, Permissions = SharedAccessBlobPermissions.Create }); Console.Write("Setting permissions on issues container ... "); issuesContainer.SetPermissions(issuesContainerPermissions); Console.WriteLine("Done"); }
internal static RESTCommand <NullType> SetAclImpl(TablePermissions permissions, CloudTableClient client, CloudTable table, TableRequestOptions requestOptions) { RESTCommand <NullType> rESTCommand = new RESTCommand <NullType>(client.Credentials, client.StorageUri); RESTCommandGeneratorUtils.ApplyTableRequestOptionsToStorageCommand(requestOptions, rESTCommand); rESTCommand.HttpClient = client.HttpClient; rESTCommand.BuildRequest = ((RESTCommand <NullType> cmd, Uri uri, UriQueryBuilder uriBuilder, HttpContent httpContent, int?timeout, OperationContext ctx) => TableRequestMessageFactory.BuildStorageRequestMessageForTablePermissions(NavigationHelper.AppendPathToSingleUri(uri, table.Name), uriBuilder, timeout, HttpMethod.Put, permissions, SharedKeyCanonicalizer.Instance, client.Credentials, ctx, requestOptions)); rESTCommand.ParseErrorAsync = StorageExtendedErrorInformationRestHelper.ReadExtendedErrorInfoFromStreamAsync; rESTCommand.PreProcessResponse = ((RESTCommand <NullType> cmd, HttpResponseMessage resp, Exception ex, OperationContext ctx) => HttpResponseParsers.ProcessExpectedStatusCodeNoException(HttpStatusCode.NoContent, resp, NullType.Value, cmd, ex)); return(rESTCommand); }
protected static CloudTable Table(string tableName, bool createIfNotExists = true) { CloudTable table = tableClient.GetTableReference(tableName.ToLower()); if (createIfNotExists) { table.CreateIfNotExists(); // The Azure storage REST API will throw a 404 (not found) error before creating the table. Not sure I like that. } // we might want to do something with this... TablePermissions permissions = table.GetPermissions(); return(table); }
internal static Task <TablePermissions> ParseGetAclAsync(RESTCommand <TablePermissions> cmd, HttpResponseMessage resp, OperationContext ctx) { TablePermissions tablePermissions = new TablePermissions(); CommonUtility.AssertNotNull("permissions", tablePermissions); SharedAccessTablePolicies sharedAccessPolicies = tablePermissions.SharedAccessPolicies; foreach (KeyValuePair <string, SharedAccessTablePolicy> accessIdentifier in new TableAccessPolicyResponse(cmd.ResponseStream).AccessIdentifiers) { sharedAccessPolicies.Add(accessIdentifier.Key, accessIdentifier.Value); } return(Task.FromResult(tablePermissions)); }
/// <summary> /// Creates a Windows Azure SAS key for adding entries to a table. /// Adds a shared policy on the table so that access can later be revoked. If an existing policy with the specified name already /// exists, it is used or altered to match the required level of access (SharedAccessTablePermissions.Add). /// </summary> /// <param name="storageConnectionString">Connection string to storage account where the table resides</param> /// <param name="tableName">The name of the table for which access is granted. If the table does not exist, it is created.</param> /// <param name="sharedPolicyName">The name that is given to the shared policy through which the SAS key is generated</param> /// <param name="expireAfter">How long before the key should expire</param> /// <returns></returns> public Uri CreateAddOnlySasKey(string storageConnectionString, string tableName, string sharedPolicyName, TimeSpan expireAfter) { CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString); CloudTableClient tableClient = storageAccount.CreateCloudTableClient(); CloudTable table = tableClient.GetTableReference(tableName); // Create the table if doesn't exist table.CreateIfNotExists(); // Create a target Shared Policy with desired expiration time and permissions - can later be used to revoke the sas key SharedAccessTablePolicy targetSharedPolicy = new SharedAccessTablePolicy() { SharedAccessExpiryTime = DateTime.UtcNow.Add(expireAfter), Permissions = SharedAccessTablePermissions.Add }; // Get current table permissions TablePermissions tablePermissions = table.GetPermissions(); // If the table already has a policy with this name if (tablePermissions.SharedAccessPolicies.ContainsKey(sharedPolicyName)) { // update it's values to match the target values Console.WriteLine("Updating existing shared policy"); SharedAccessTablePolicy existingSharedPolicy = tablePermissions.SharedAccessPolicies[sharedPolicyName]; existingSharedPolicy.SharedAccessExpiryTime = targetSharedPolicy.SharedAccessExpiryTime; existingSharedPolicy.Permissions = targetSharedPolicy.Permissions; table.SetPermissions(tablePermissions); } else { // No such policy found - create a new one Console.WriteLine("Adding new shared access policy to table"); tablePermissions.SharedAccessPolicies.Add(sharedPolicyName, targetSharedPolicy); table.SetPermissions(tablePermissions); } // Generate the SAS key string sasTableToken = table.GetSharedAccessSignature( null, sharedPolicyName, null, null, null, null); Uri sasUri = new Uri(table.Uri + sasTableToken); Console.WriteLine("Sas Uri: {0}", sasUri); return(sasUri); }
public async Task CloudTableExtensionsTest() { // Arrange var permissions = new TablePermissions(); permissions.SharedAccessPolicies.Add("default", new SharedAccessTablePolicy { Permissions = SharedAccessTablePermissions.Query, SharedAccessExpiryTime = DateTimeOffset.UtcNow, SharedAccessStartTime = DateTimeOffset.UtcNow }); // Act // Create table await _cloudTable.CreateAsync(); // Create table bool createIfNotExistsResult = await _cloudTable.CreateIfNotExistsAsync(); // Check whether table exists bool existsResult = await _cloudTable.ExistsAsync(); // Set & get permissions await _cloudTable.SetPermissionsAsync(permissions); TablePermissions permissionsResult = await _cloudTable.GetPermissionsAsync(); // Delete table await _cloudTable.DeleteAsync(); bool deleteIfExistsResult = await _cloudTable.DeleteIfExistsAsync(); // Assert Assert.False(createIfNotExistsResult); Assert.True(existsResult); Assert.NotNull(permissionsResult); Assert.NotNull(permissionsResult.SharedAccessPolicies); Assert.Equal(permissionsResult.SharedAccessPolicies.Count, permissions.SharedAccessPolicies.Count); foreach (var policy in permissionsResult.SharedAccessPolicies) { Assert.Contains(policy.Key, permissions.SharedAccessPolicies.Keys); SharedAccessTablePolicy value = permissions.SharedAccessPolicies[policy.Key]; Assert.Equal(policy.Value.Permissions, value.Permissions); } Assert.False(deleteIfExistsResult); }
public ICancellableAsyncResult BeginSetPermissions(TablePermissions permissions, TableRequestOptions requestOptions, OperationContext operationContext, AsyncCallback callback, object state) { _permissions = permissions; var result = new TableAsyncResult { AsyncState = _permissions, AsyncWaitHandle = new Mutex(), CompletedSynchronously = true, IsCompleted = true }; callback(result); return(result); }
/// <summary> /// Sets the permissions settings for the table asynchronously. /// </summary> /// <param name="cloudTable">Cloud table.</param> /// <param name="tablePermissions"> /// A <see cref="T:Microsoft.WindowsAzure.Storage.Table.TablePermissions" /> object that represents the permissions to set. /// </param> /// <param name="cancellationToken">Cancellation token.</param> public static Task SetPermissionsAsync( this CloudTable cloudTable, TablePermissions tablePermissions, CancellationToken cancellationToken = default(CancellationToken)) { ICancellableAsyncResult asyncResult = cloudTable.BeginSetPermissions(tablePermissions, null, null); CancellationTokenRegistration registration = cancellationToken.Register(p => asyncResult.Cancel(), null); return(Task.Factory.FromAsync( asyncResult, result => { registration.Dispose(); cloudTable.EndSetPermissions(result); })); }
public AzureTableStorageRepository(CloudStorageAccount cloudStorageAccount) { _initTask = Task.Run(async() => { var client = cloudStorageAccount.CreateCloudTableClient(); var table = client.GetTableReference(TableName); await table.CreateIfNotExistsAsync(); var tablePermissions = new TablePermissions(); tablePermissions.SharedAccessPolicies.Add(TableName, new SharedAccessTablePolicy { Permissions = SharedAccessTablePermissions.Query | SharedAccessTablePermissions.Add | SharedAccessTablePermissions.Update }); await table.SetPermissionsAsync(tablePermissions); _table = table; }); }
public void TableGetPermissionsTask() { CloudTableClient tableClient = GenerateCloudTableClient(); string tableName = GenerateRandomTableName(); CloudTable table = tableClient.GetTableReference(tableName); try { table.CreateAsync().Wait(); table.ExecuteAsync(TableOperation.Insert(new BaseEntity("PK", "RK"))).Wait(); TablePermissions expected = new TablePermissions(); TablePermissions actual = table.GetPermissionsAsync().Result; AssertPermissionsEqual(expected, actual); } finally { table.DeleteIfExistsAsync().Wait(); } }
private static void ListTables() { try { var storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting(ConnectionStringName)); var tableClient = storageAccount.CreateCloudTableClient(); tableClient.DefaultRequestOptions.RetryPolicy = new ExponentialRetry(); var tables = tableClient.ListTables(); foreach (var table in tables) { TablePermissions tablePermission = new TablePermissions(); tablePermission.SharedAccessPolicies.Add(new KeyValuePair <string, SharedAccessTablePolicy>("01", value)); table.SetPermissions(tablePermission); Console.WriteLine($"table with name={table.Name}"); } } catch (StorageException ex) { throw; } }
public void TableGetPermissionsRequestOptionsOperationContextCancellationTokenTask() { CloudTableClient tableClient = GenerateCloudTableClient(); string tableName = GenerateRandomTableName(); CloudTable table = tableClient.GetTableReference(tableName); TableRequestOptions requestOptions = new TableRequestOptions(); OperationContext operationContext = new OperationContext(); CancellationToken cancellationToken = CancellationToken.None; try { table.CreateAsync().Wait(); table.ExecuteAsync(TableOperation.Insert(new BaseEntity("PK", "RK"))).Wait(); TablePermissions expected = new TablePermissions(); TablePermissions actual = table.GetPermissionsAsync(requestOptions, operationContext, cancellationToken).Result; AssertPermissionsEqual(expected, actual); } finally { table.DeleteIfExistsAsync().Wait(); } }
internal bool RemoveAzureTableStoredAccessPolicy(IStorageTableManagement localChannel, string tableName, string policyName) { bool success = false; string result = string.Empty; //Get existing permissions CloudTable table = localChannel.GetTableReference(tableName); TablePermissions tablePermissions = localChannel.GetTablePermissions(table); //remove the specified policy if (!tablePermissions.SharedAccessPolicies.Keys.Contains(policyName)) { throw new ResourceNotFoundException(String.Format(CultureInfo.CurrentCulture, Resources.PolicyNotFound, policyName)); } if (this.Force || ConfirmRemove(policyName)) { tablePermissions.SharedAccessPolicies.Remove(policyName); localChannel.SetTablePermissions(table, tablePermissions); success = true; } return(success); }
internal static void AssertPermissionsEqual(TablePermissions permissions1, TablePermissions permissions2) { Assert.AreEqual(permissions1.SharedAccessPolicies.Count, permissions2.SharedAccessPolicies.Count); foreach (KeyValuePair <string, SharedAccessTablePolicy> pair in permissions1.SharedAccessPolicies) { SharedAccessTablePolicy policy1 = pair.Value; SharedAccessTablePolicy policy2 = permissions2.SharedAccessPolicies[pair.Key]; Assert.IsNotNull(policy1); Assert.IsNotNull(policy2); Assert.AreEqual(policy1.Permissions, policy2.Permissions); if (policy1.SharedAccessStartTime != null) { Assert.IsTrue(Math.Floor((policy1.SharedAccessStartTime.Value - policy2.SharedAccessStartTime.Value).TotalSeconds) == 0); } if (policy1.SharedAccessExpiryTime != null) { Assert.IsTrue(Math.Floor((policy1.SharedAccessExpiryTime.Value - policy2.SharedAccessExpiryTime.Value).TotalSeconds) == 0); } } }
public void TableSetGetPermissionsSync() { CloudTableClient tableClient = GenerateCloudTableClient(); CloudTable table = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N")); try { table.Create(); TableServiceContext context = tableClient.GetTableServiceContext(); context.AddObject(table.Name, new BaseEntity("PK", "RK")); context.SaveChangesWithRetries(); TablePermissions expectedPermissions = new TablePermissions(); TablePermissions testPermissions = table.GetPermissions(); AssertPermissionsEqual(expectedPermissions, testPermissions); // Add a policy, check setting and getting. expectedPermissions.SharedAccessPolicies.Add(Guid.NewGuid().ToString(), new SharedAccessTablePolicy { Permissions = SharedAccessTablePermissions.Query, SharedAccessStartTime = DateTimeOffset.Now - TimeSpan.FromHours(1), SharedAccessExpiryTime = DateTimeOffset.Now + TimeSpan.FromHours(1) }); table.SetPermissions(expectedPermissions); Thread.Sleep(30 * 1000); testPermissions = table.GetPermissions(); AssertPermissionsEqual(expectedPermissions, testPermissions); } finally { table.DeleteIfExists(); } }
/// <summary> /// Reads the share access policies from a stream in XML. /// </summary> /// <param name="inputStream">The stream of XML policies.</param> /// <param name="permissions">The permissions object to which the policies are to be written.</param> public static void ReadSharedAccessIdentifiers(Stream inputStream, TablePermissions permissions) { CommonUtility.AssertNotNull("permissions", permissions); HttpResponseParsers.ReadSharedAccessIdentifiers(permissions.SharedAccessPolicies, new TableAccessPolicyResponse(inputStream)); }
public ICancellableAsyncResult BeginSetPermissions(TablePermissions permissions, AsyncCallback callback, object state) { return(BeginSetPermissions(permissions, null, null, callback, state)); }
/// <summary> /// Reads the share access policies from a stream in XML. /// </summary> /// <param name="inputStream">The stream of XML policies.</param> /// <param name="permissions">The permissions object to which the policies are to be written.</param> public static void ReadSharedAccessIdentifiers(Stream inputStream, TablePermissions permissions) { HttpResponseParsers.ReadSharedAccessIdentifiers(permissions.SharedAccessPolicies, new TableAccessPolicyResponse(inputStream)); }
/// <summary> /// Tests table access permissions with SAS, using a stored policy and using permissions on the URI. /// </summary> /// <param name="accessPermissions">The permissions to test.</param> /// <param name="startPk">The start partition key range.</param> /// <param name="startRk">The start row key range.</param> /// <param name="endPk">The end partition key range.</param> /// <param name="endRk">The end row key range.</param> internal void TestTableSasWithRange( SharedAccessTablePermissions accessPermissions, string startPk, string startRk, string endPk, string endRk) { TestContext.WriteLine("Testing SAS range: spk={0}; epk={1}; srk={2}; erk={3}", startPk, endPk, startRk, endRk); CloudTableClient tableClient = GenerateCloudTableClient(); CloudTable table = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N")); try { table.Create(); // Set up a policy string identifier = Guid.NewGuid().ToString(); TablePermissions permissions = new TablePermissions(); permissions.SharedAccessPolicies.Add(identifier, new SharedAccessTablePolicy { Permissions = accessPermissions, SharedAccessExpiryTime = DateTimeOffset.Now.AddDays(1) }); table.SetPermissions(permissions); Thread.Sleep(30 * 1000); // Prepare SAS authentication using access identifier string sasString = table.GetSharedAccessSignature(new SharedAccessTablePolicy(), identifier, startPk, startRk, endPk, endRk); CloudTableClient identifierSasClient = new CloudTableClient(tableClient.BaseUri, new StorageCredentials(sasString)); // Prepare SAS authentication using explicit policy sasString = table.GetSharedAccessSignature( new SharedAccessTablePolicy { Permissions = accessPermissions, SharedAccessExpiryTime = DateTimeOffset.Now.AddMinutes(30) }, null, startPk, startRk, endPk, endRk); CloudTableClient explicitSasClient = new CloudTableClient(tableClient.BaseUri, new StorageCredentials(sasString)); // Point query TestPointQuery(identifierSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk); TestPointQuery(explicitSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk); // Add row TestAdd(identifierSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk); TestAdd(explicitSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk); // Update row (merge) TestUpdateMerge(identifierSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk); TestUpdateMerge(explicitSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk); // Update row (replace) TestUpdateReplace(identifierSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk); TestUpdateReplace(explicitSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk); // Delete row TestDelete(identifierSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk); TestDelete(explicitSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk); // Upsert row (merge) TestUpsertMerge(identifierSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk); TestUpsertMerge(explicitSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk); // Upsert row (replace) TestUpsertReplace(identifierSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk); TestUpsertReplace(explicitSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk); } finally { table.DeleteIfExists(); } }
public void TableSetGetPermissionsTask() { CloudTableClient tableClient = GenerateCloudTableClient(); CloudTable table = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N")); try { table.CreateAsync().Wait(); TableServiceContext context = tableClient.GetTableServiceContext(); context.AddObject(table.Name, new BaseEntity("PK", "RK")); context.SaveChangesWithRetriesAsync().Wait(); TablePermissions expectedPermissions = new TablePermissions(); TablePermissions testPermissions = table.GetPermissionsAsync().Result; AssertPermissionsEqual(expectedPermissions, testPermissions); // Add a policy, check setting and getting. expectedPermissions.SharedAccessPolicies.Add(Guid.NewGuid().ToString(), new SharedAccessTablePolicy { Permissions = SharedAccessTablePermissions.Query, SharedAccessStartTime = DateTimeOffset.Now - TimeSpan.FromHours(1), SharedAccessExpiryTime = DateTimeOffset.Now + TimeSpan.FromHours(1) }); table.SetPermissionsAsync(expectedPermissions).Wait(); Thread.Sleep(30 * 1000); testPermissions = table.GetPermissionsAsync(null, new OperationContext()).Result; AssertPermissionsEqual(expectedPermissions, testPermissions); } finally { table.DeleteIfExistsAsync().Wait(); } }
public void TableGetEnumeratorPermissionsSync() { CloudTableClient tableClient = GenerateCloudTableClient(); CloudTable table = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N")); try { table.Create(); TableServiceContext context = tableClient.GetTableServiceContext(); context.AddObject(table.Name, new BaseEntity("PK", "RK")); context.SaveChangesWithRetries(); TablePermissions expectedPermissions = new TablePermissions(); TablePermissions testPermissions = table.GetPermissions(); AssertPermissionsEqual(expectedPermissions, testPermissions); string key = Guid.NewGuid().ToString(); DateTime start = DateTime.UtcNow; start = new DateTime(start.Year, start.Month, start.Day, start.Hour, start.Minute, start.Second, DateTimeKind.Utc); DateTime expiry = start.AddMinutes(30); KeyValuePair<String, SharedAccessTablePolicy> policy = new KeyValuePair<string, SharedAccessTablePolicy>(key, new SharedAccessTablePolicy { Permissions = SharedAccessTablePermissions.Query, SharedAccessStartTime = start, SharedAccessExpiryTime = expiry }); string key2 = Guid.NewGuid().ToString(); DateTime start2 = DateTime.UtcNow; start2 = new DateTime(start2.Year, start2.Month, start2.Day, start2.Hour, start2.Minute, start2.Second, DateTimeKind.Utc); DateTime expiry2 = start2.AddMinutes(30); KeyValuePair<String, SharedAccessTablePolicy> policy2 = new KeyValuePair<string, SharedAccessTablePolicy>(key2, new SharedAccessTablePolicy { Permissions = SharedAccessTablePermissions.Query, SharedAccessStartTime = start2, SharedAccessExpiryTime = expiry2 }); expectedPermissions.SharedAccessPolicies.Add(policy); expectedPermissions.SharedAccessPolicies.Add(policy2); Assert.AreEqual(2, expectedPermissions.SharedAccessPolicies.Count); IEnumerator<KeyValuePair<string, SharedAccessTablePolicy>> policies = expectedPermissions.SharedAccessPolicies.GetEnumerator(); policies.MoveNext(); Assert.AreEqual(policy, policies.Current); policies.MoveNext(); Assert.AreEqual(policy2, policies.Current); } finally { table.DeleteIfExists(); } }
public void TableCopyPermissionsSync() { CloudTableClient tableClient = GenerateCloudTableClient(); CloudTable table = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N")); try { TablePermissions expectedPermissions = new TablePermissions(); string key = Guid.NewGuid().ToString(); KeyValuePair<String, SharedAccessTablePolicy> policy = new KeyValuePair<string, SharedAccessTablePolicy>(key, new SharedAccessTablePolicy { Permissions = SharedAccessTablePermissions.Query, SharedAccessStartTime = DateTimeOffset.Now - TimeSpan.FromHours(1), SharedAccessExpiryTime = DateTimeOffset.Now + TimeSpan.FromHours(1) }); string key2 = Guid.NewGuid().ToString(); KeyValuePair<String, SharedAccessTablePolicy> policy2 = new KeyValuePair<string, SharedAccessTablePolicy>(key2, new SharedAccessTablePolicy { Permissions = SharedAccessTablePermissions.Query, SharedAccessStartTime = DateTimeOffset.Now - TimeSpan.FromHours(1), SharedAccessExpiryTime = DateTimeOffset.Now + TimeSpan.FromHours(1) }); expectedPermissions.SharedAccessPolicies.Add(policy); expectedPermissions.SharedAccessPolicies.Add(policy2); KeyValuePair<String, SharedAccessTablePolicy>[] sharedAccessPolicyArray = new KeyValuePair<string, SharedAccessTablePolicy>[2]; expectedPermissions.SharedAccessPolicies.CopyTo(sharedAccessPolicyArray, 0); Assert.AreEqual(2, sharedAccessPolicyArray.Length); Assert.AreEqual(policy, sharedAccessPolicyArray[0]); Assert.AreEqual(policy2, sharedAccessPolicyArray[1]); } finally { table.DeleteIfExists(); } }
public void TableContainsAndClearPermissionsSync() { CloudTableClient tableClient = GenerateCloudTableClient(); CloudTable table = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N")); try { table.Create(); TableServiceContext context = tableClient.GetTableServiceContext(); context.AddObject(table.Name, new BaseEntity("PK", "RK")); context.SaveChangesWithRetries(); TablePermissions expectedPermissions = new TablePermissions(); TablePermissions testPermissions = table.GetPermissions(); AssertPermissionsEqual(expectedPermissions, testPermissions); string key = Guid.NewGuid().ToString(); KeyValuePair<String, SharedAccessTablePolicy> policy = new KeyValuePair<string, SharedAccessTablePolicy>(key, new SharedAccessTablePolicy { Permissions = SharedAccessTablePermissions.Query, SharedAccessStartTime = DateTimeOffset.Now - TimeSpan.FromHours(1), SharedAccessExpiryTime = DateTimeOffset.Now + TimeSpan.FromHours(1) }); // Add a policy, check setting and getting. expectedPermissions.SharedAccessPolicies.Add(policy); table.SetPermissions(expectedPermissions); Thread.Sleep(30 * 1000); testPermissions = table.GetPermissions(); AssertPermissionsEqual(expectedPermissions, testPermissions); Assert.AreEqual(true, expectedPermissions.SharedAccessPolicies.Contains(policy)); Assert.AreEqual(true, expectedPermissions.SharedAccessPolicies.ContainsKey(key)); expectedPermissions.SharedAccessPolicies.Clear(); table.SetPermissions(expectedPermissions); Thread.Sleep(30 * 1000); testPermissions = table.GetPermissions(); Assert.AreEqual(0, expectedPermissions.SharedAccessPolicies.Count); AssertPermissionsEqual(new TablePermissions(), testPermissions); } finally { table.DeleteIfExists(); } }
internal static void AssertPermissionsEqual(TablePermissions permissions1, TablePermissions permissions2) { Assert.AreEqual(permissions1.SharedAccessPolicies.Count, permissions2.SharedAccessPolicies.Count); foreach (KeyValuePair<string, SharedAccessTablePolicy> pair in permissions1.SharedAccessPolicies) { SharedAccessTablePolicy policy1 = pair.Value; SharedAccessTablePolicy policy2 = permissions2.SharedAccessPolicies[pair.Key]; Assert.IsNotNull(policy1); Assert.IsNotNull(policy2); Assert.AreEqual(policy1.Permissions, policy2.Permissions); if (policy1.SharedAccessStartTime != null) { Assert.IsTrue(Math.Floor((policy1.SharedAccessStartTime.Value - policy2.SharedAccessStartTime.Value).TotalSeconds) == 0); } if (policy1.SharedAccessExpiryTime != null) { Assert.IsTrue(Math.Floor((policy1.SharedAccessExpiryTime.Value - policy2.SharedAccessExpiryTime.Value).TotalSeconds) == 0); } } }
public void TableGetSetPermissionTestSync() { CloudTableClient tableClient = GenerateCloudTableClient(); CloudTable table = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N")); try { table.Create(); table.Execute(TableOperation.Insert(new BaseEntity("PK", "RK"))); TablePermissions expectedPermissions; TablePermissions testPermissions; // Test new table permissions. expectedPermissions = new TablePermissions(); testPermissions = table.GetPermissions(); AssertPermissionsEqual(expectedPermissions, testPermissions); // Test setting empty permissions. table.SetPermissions(expectedPermissions); Thread.Sleep(30 * 1000); testPermissions = table.GetPermissions(); AssertPermissionsEqual(expectedPermissions, testPermissions); // Add a policy, check setting and getting. expectedPermissions.SharedAccessPolicies.Add(Guid.NewGuid().ToString(), new SharedAccessTablePolicy { Permissions = SharedAccessTablePermissions.Query, SharedAccessStartTime = DateTimeOffset.Now - TimeSpan.FromHours(1), SharedAccessExpiryTime = DateTimeOffset.Now + TimeSpan.FromHours(1) }); table.SetPermissions(expectedPermissions); Thread.Sleep(30 * 1000); testPermissions = table.GetPermissions(); AssertPermissionsEqual(expectedPermissions, testPermissions); // Add a policy, check setting and getting. expectedPermissions.SharedAccessPolicies.Add(Guid.NewGuid().ToString(), new SharedAccessTablePolicy { Permissions = SharedAccessTablePermissions.Delete | SharedAccessTablePermissions.Add, SharedAccessStartTime = DateTimeOffset.Now + TimeSpan.FromHours(1), SharedAccessExpiryTime = DateTimeOffset.Now + TimeSpan.FromDays(1) }); table.SetPermissions(expectedPermissions); Thread.Sleep(30 * 1000); testPermissions = table.GetPermissions(); AssertPermissionsEqual(expectedPermissions, testPermissions); // Add a null policy, check setting and getting. expectedPermissions.SharedAccessPolicies.Add(Guid.NewGuid().ToString(), new SharedAccessTablePolicy { Permissions = SharedAccessTablePermissions.None, }); table.SetPermissions(expectedPermissions); Thread.Sleep(30 * 1000); testPermissions = table.GetPermissions(); AssertPermissionsEqual(expectedPermissions, testPermissions); // Add a policy, check setting and getting. expectedPermissions.SharedAccessPolicies.Add(Guid.NewGuid().ToString(), new SharedAccessTablePolicy { Permissions = SharedAccessTablePermissions.Add | SharedAccessTablePermissions.Query | SharedAccessTablePermissions.Update | SharedAccessTablePermissions.Delete, SharedAccessStartTime = DateTimeOffset.Now + TimeSpan.FromDays(0.5), SharedAccessExpiryTime = DateTimeOffset.Now + TimeSpan.FromDays(1) }); table.SetPermissions(expectedPermissions); Thread.Sleep(30 * 1000); testPermissions = table.GetPermissions(); AssertPermissionsEqual(expectedPermissions, testPermissions); // Add a policy, check setting and getting. expectedPermissions.SharedAccessPolicies.Add(Guid.NewGuid().ToString(), new SharedAccessTablePolicy { Permissions = SharedAccessTablePermissions.Update, SharedAccessStartTime = DateTimeOffset.Now + TimeSpan.FromHours(6), SharedAccessExpiryTime = DateTimeOffset.Now + TimeSpan.FromHours(6.5) }); table.SetPermissions(expectedPermissions); Thread.Sleep(30 * 1000); testPermissions = table.GetPermissions(); AssertPermissionsEqual(expectedPermissions, testPermissions); } finally { table.DeleteIfExists(); } }
public void SetPermissions(TablePermissions permissions, TableRequestOptions requestOptions = null, OperationContext operationContext = null) { _permissions = permissions; }
public void TableSetGetPermissionsAPM() { CloudTableClient tableClient = GenerateCloudTableClient(); CloudTable table = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N")); try { table.Create(); TableServiceContext context = tableClient.GetTableServiceContext(); context.AddObject(table.Name, new BaseEntity("PK", "RK")); context.SaveChangesWithRetries(); TablePermissions expectedPermissions = new TablePermissions(); TablePermissions testPermissions = table.GetPermissions(); AssertPermissionsEqual(expectedPermissions, testPermissions); // Add a policy, check setting and getting. expectedPermissions.SharedAccessPolicies.Add(Guid.NewGuid().ToString(), new SharedAccessTablePolicy { Permissions = SharedAccessTablePermissions.Query, SharedAccessStartTime = DateTimeOffset.Now - TimeSpan.FromHours(1), SharedAccessExpiryTime = DateTimeOffset.Now + TimeSpan.FromHours(1) }); using (ManualResetEvent evt = new ManualResetEvent(false)) { IAsyncResult result = null; table.BeginSetPermissions(expectedPermissions, (res) => { result = res; evt.Set(); }, null); evt.WaitOne(); table.EndSetPermissions(result); } Thread.Sleep(30 * 1000); using (ManualResetEvent evt = new ManualResetEvent(false)) { IAsyncResult result = null; table.BeginGetPermissions((res) => { result = res; evt.Set(); }, null); evt.WaitOne(); testPermissions = table.EndGetPermissions(result); } AssertPermissionsEqual(expectedPermissions, testPermissions); } finally { table.DeleteIfExists(); } }