public void ValidateSetupAccessPolicyPermissionTest()
        {
            SharedAccessBlobPolicy blobAccessPolicy = new SharedAccessBlobPolicy();
            AccessPolicyHelper.SetupAccessPolicyPermission(blobAccessPolicy, null);
            Assert.AreEqual(blobAccessPolicy.Permissions, SharedAccessBlobPermissions.None);
            AccessPolicyHelper.SetupAccessPolicyPermission(blobAccessPolicy, "");
            Assert.AreEqual(blobAccessPolicy.Permissions, SharedAccessBlobPermissions.None);
            AccessPolicyHelper.SetupAccessPolicyPermission(blobAccessPolicy, "D");
            Assert.AreEqual(blobAccessPolicy.Permissions, SharedAccessBlobPermissions.Delete);

            SharedAccessTablePolicy tableAccessPolicy = new SharedAccessTablePolicy();
            AccessPolicyHelper.SetupAccessPolicyPermission(tableAccessPolicy, null);
            Assert.AreEqual(tableAccessPolicy.Permissions, SharedAccessTablePermissions.None);
            AccessPolicyHelper.SetupAccessPolicyPermission(tableAccessPolicy, "");
            Assert.AreEqual(tableAccessPolicy.Permissions, SharedAccessTablePermissions.None);
            AccessPolicyHelper.SetupAccessPolicyPermission(tableAccessPolicy, "ar");
            Assert.AreEqual(tableAccessPolicy.Permissions, SharedAccessTablePermissions.Add | SharedAccessTablePermissions.Query);

            SharedAccessQueuePolicy queueAccessPolicy = new SharedAccessQueuePolicy();
            AccessPolicyHelper.SetupAccessPolicyPermission(queueAccessPolicy, null);
            Assert.AreEqual(queueAccessPolicy.Permissions, SharedAccessQueuePermissions.None);
            AccessPolicyHelper.SetupAccessPolicyPermission(queueAccessPolicy, "");
            Assert.AreEqual(queueAccessPolicy.Permissions, SharedAccessQueuePermissions.None);
            AccessPolicyHelper.SetupAccessPolicyPermission(queueAccessPolicy, "p");
            Assert.AreEqual(queueAccessPolicy.Permissions, SharedAccessQueuePermissions.ProcessMessages);

            SharedAccessFilePolicy fileAccessPolicy = new SharedAccessFilePolicy();
            AccessPolicyHelper.SetupAccessPolicyPermission(fileAccessPolicy, null);
            Assert.AreEqual(fileAccessPolicy.Permissions, SharedAccessFilePermissions.None);
            AccessPolicyHelper.SetupAccessPolicyPermission(fileAccessPolicy, "");
            Assert.AreEqual(fileAccessPolicy.Permissions, SharedAccessFilePermissions.None);
            AccessPolicyHelper.SetupAccessPolicyPermission(fileAccessPolicy, "lwc");
            Assert.AreEqual(fileAccessPolicy.Permissions, SharedAccessFilePermissions.List | SharedAccessFilePermissions.Write | SharedAccessFilePermissions.Create); 

        }
 public void SetupAccessPolicyPermissionTest()
 {
     SharedAccessTablePolicy accessPolicy = new SharedAccessTablePolicy();
     command.SetupAccessPolicyPermission(accessPolicy, "");
     Assert.AreEqual(accessPolicy.Permissions, SharedAccessTablePermissions.None);
     accessPolicy.Permissions = SharedAccessTablePermissions.Add;
     command.SetupAccessPolicyPermission(accessPolicy, "");
     Assert.AreEqual(accessPolicy.Permissions, SharedAccessTablePermissions.Add);
     command.SetupAccessPolicyPermission(accessPolicy, "u");
     Assert.AreEqual(accessPolicy.Permissions, SharedAccessTablePermissions.Update);
     command.SetupAccessPolicyPermission(accessPolicy, "uUUU");
     Assert.AreEqual(accessPolicy.Permissions, SharedAccessTablePermissions.Update);
     command.SetupAccessPolicyPermission(accessPolicy, "drrq");
     Assert.AreEqual(accessPolicy.Permissions, SharedAccessTablePermissions.Delete | SharedAccessTablePermissions.Query);
     command.SetupAccessPolicyPermission(accessPolicy, "rq");
     Assert.AreEqual(accessPolicy.Permissions, SharedAccessTablePermissions.Query);
     command.SetupAccessPolicyPermission(accessPolicy, "q");
     Assert.AreEqual(accessPolicy.Permissions, SharedAccessTablePermissions.Query);
     command.SetupAccessPolicyPermission(accessPolicy, "r");
     Assert.AreEqual(accessPolicy.Permissions, SharedAccessTablePermissions.Query);
     command.SetupAccessPolicyPermission(accessPolicy, "qd");
     Assert.AreEqual(accessPolicy.Permissions, SharedAccessTablePermissions.Delete | SharedAccessTablePermissions.Query);
     command.SetupAccessPolicyPermission(accessPolicy, "audq");
     Assert.AreEqual(accessPolicy.Permissions, SharedAccessTablePermissions.Add 
         | SharedAccessTablePermissions.Query | SharedAccessTablePermissions.Update | SharedAccessTablePermissions.Delete);
     command.SetupAccessPolicyPermission(accessPolicy, "dqaaaau");
     Assert.AreEqual(accessPolicy.Permissions, SharedAccessTablePermissions.Add
         | SharedAccessTablePermissions.Query | SharedAccessTablePermissions.Update | SharedAccessTablePermissions.Delete);
     AssertThrows<ArgumentException>(() => command.SetupAccessPolicyPermission(accessPolicy, "rwDl"));
     AssertThrows<ArgumentException>(() => command.SetupAccessPolicyPermission(accessPolicy, "x"));
     AssertThrows<ArgumentException>(() => command.SetupAccessPolicyPermission(accessPolicy, "rwx"));
     AssertThrows<ArgumentException>(() => command.SetupAccessPolicyPermission(accessPolicy, "ABC"));
 }
 /// <summary>
 /// Returns a shared access signature for the table.
 /// </summary>
 /// <param name="policy">A <see cref="SharedAccessTablePolicy"/> object specifying the access policy for the shared access signature.</param>
 /// <param name="accessPolicyIdentifier">A string identifying a stored access policy.</param>
 /// <param name="startPartitionKey">A string specifying the start partition key, or <c>null</c>.</param>
 /// <param name="startRowKey">A string specifying the start row key, or <c>null</c>.</param>
 /// <param name="endPartitionKey">A string specifying the end partition key, or <c>null</c>.</param>
 /// <param name="endRowKey">A string specifying the end row key, or <c>null</c>.</param>
 /// <returns>A shared access signature, as a URI query string.</returns>
 /// <remarks>The query string returned includes the leading question mark.</remarks>
 /// <exception cref="InvalidOperationException">Thrown if the current credentials don't support creating a shared access signature.</exception>
 public string GetSharedAccessSignature(
     SharedAccessTablePolicy policy,
     string accessPolicyIdentifier,
     string startPartitionKey,
     string startRowKey,
     string endPartitionKey,
     string endRowKey)
 {
     return(this.GetSharedAccessSignature(policy, accessPolicyIdentifier, startPartitionKey, startRowKey, endPartitionKey, endRowKey, null, null));
 }
 /// <summary>
 /// Returns a shared access signature for the table.
 /// </summary>
 /// <param name="policy">A <see cref="SharedAccessTablePolicy"/> object specifying the access policy for the shared access signature.</param>
 /// <param name="accessPolicyIdentifier">A string identifying a stored access policy.</param>
 /// <returns>A shared access signature, as a URI query string.</returns>
 /// <remarks>The query string returned includes the leading question mark.</remarks>
 /// <exception cref="InvalidOperationException">Thrown if the current credentials don't support creating a shared access signature.</exception>
 public string GetSharedAccessSignature(SharedAccessTablePolicy policy, string accessPolicyIdentifier)
 {
     return(this.GetSharedAccessSignature(
                policy,
                accessPolicyIdentifier,
                null /* startPartitionKey */,
                null /* startRowKey */,
                null /* endPartitionKey */,
                null /* endRowKey */));
 }
        /// <summary>
        /// Returns a shared access signature for the table.
        /// </summary>
        /// <param name="policy">A <see cref="SharedAccessTablePolicy"/> object specifying the access policy for the shared access signature.</param>
        /// <param name="accessPolicyIdentifier">A string identifying a stored access policy.</param>
        /// <param name="startPartitionKey">A string specifying the start partition key, or <c>null</c>.</param>
        /// <param name="startRowKey">A string specifying the start row key, or <c>null</c>.</param>
        /// <param name="endPartitionKey">A string specifying the end partition key, or <c>null</c>.</param>
        /// <param name="endRowKey">A string specifying the end row key, or <c>null</c>.</param>
        /// <param name="protocols">The allowed protocols (https only, or http and https). Null if you don't want to restrict protocol.</param>
        /// <param name="ipAddressOrRange">The allowed IP address or IP address range. Null if you don't want to restrict based on IP address.</param>
        /// <returns>A shared access signature, as a URI query string.</returns>
        /// <remarks>The query string returned includes the leading question mark.</remarks>
        /// <exception cref="InvalidOperationException">Thrown if the current credentials don't support creating a shared access signature.</exception>
        public string GetSharedAccessSignature(
            SharedAccessTablePolicy policy,
            string accessPolicyIdentifier,
            string startPartitionKey,
            string startRowKey,
            string endPartitionKey,
            string endRowKey,
            SharedAccessProtocol?protocols,
            IPAddressOrRange ipAddressOrRange)
        {
            if (!this.ServiceClient.Credentials.IsSharedKey)
            {
                string errorMessage = string.Format(CultureInfo.CurrentCulture, SR.CannotCreateSASWithoutAccountKey);
                throw new InvalidOperationException(errorMessage);
            }

            string            resourceName = this.GetCanonicalName();
            StorageAccountKey accountKey   = this.ServiceClient.Credentials.Key;

#if ALL_SERVICES
            string signature = SharedAccessSignatureHelper.GetHash(
#else
            string signature = TableSharedAccessSignatureHelper.GetHash(
#endif
                policy,
                accessPolicyIdentifier,
                startPartitionKey,
                startRowKey,
                endPartitionKey,
                endRowKey,
                resourceName,
                OperationContext.StorageVersion ?? Constants.HeaderConstants.TargetStorageVersion,
                protocols,
                ipAddressOrRange,
                accountKey.KeyValue);
#if ALL_SERVICES
            UriQueryBuilder builder = SharedAccessSignatureHelper.GetSignature(
#else
            UriQueryBuilder builder = TableSharedAccessSignatureHelper.GetSignature(
#endif
                policy,
                this.Name,
                accessPolicyIdentifier,
                startPartitionKey,
                startRowKey,
                endPartitionKey,
                endRowKey,
                signature,
                accountKey.KeyName,
                OperationContext.StorageVersion ?? Constants.HeaderConstants.TargetStorageVersion,
                protocols,
                ipAddressOrRange);

            return(builder.ToString());
        }
Beispiel #6
0
        public async Task TableUpdateSasTestAsync()
        {
            CloudTableClient tableClient = GenerateCloudTableClient();
            CloudTable       table       = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N"));

            try
            {
                await table.CreateAsync();

                BaseEntity entity = new BaseEntity("PK", "RK");
                await table.ExecuteAsync(TableOperation.Insert(entity));

                SharedAccessTablePolicy policy = new SharedAccessTablePolicy()
                {
                    SharedAccessStartTime  = DateTimeOffset.UtcNow.AddMinutes(-5),
                    SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                    Permissions            = SharedAccessTablePermissions.Delete,
                };

                string             sasToken = table.GetSharedAccessSignature(policy, null, null, null, null, null);
                StorageCredentials creds    = new StorageCredentials(sasToken);
                CloudTable         sasTable = new CloudTable(table.Uri, creds);
                OperationContext   context  = new OperationContext();
                await TestHelper.ExpectedExceptionAsync(
                    async() => await sasTable.ExecuteAsync(TableOperation.Insert(new BaseEntity("PK", "RK2")), null, context),
                    context,
                    "Try to insert an entity when SAS doesn't allow inserts",
                    HttpStatusCode.NotFound);

                await sasTable.ExecuteAsync(TableOperation.Delete(entity));

                SharedAccessTablePolicy policy2 = new SharedAccessTablePolicy()
                {
                    SharedAccessStartTime  = DateTimeOffset.UtcNow.AddMinutes(-5),
                    SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                    Permissions            = SharedAccessTablePermissions.Delete | SharedAccessTablePermissions.Add,
                };

                string sasToken2 = table.GetSharedAccessSignature(policy2, null, null, null, null, null);
                creds.UpdateSASToken(sasToken2);

                sasTable = new CloudTable(table.Uri, creds);

                await sasTable.ExecuteAsync(TableOperation.Insert(new BaseEntity("PK", "RK2")));
            }
            finally
            {
                table.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
Beispiel #7
0
        static void Main(string[] args)
        {
            const string PolicyName = "TableSasGenPolicy";

            try
            {
                if (args.Length < 3)
                {
                    Console.WriteLine("Usage: TableSasGen.exe <storageAccount> <tableName> <storageKey>");
                    return;
                }

                var storageAccount = args[0];
                var tableName = args[1];
                var storageKey = args[2];

                var storageUri = new Uri(String.Format("https://{0}.table.core.windows.net/", storageAccount));

                CloudTableClient client = new CloudTableClient(storageUri, new StorageCredentials(storageAccount, storageKey));
                CloudTable table = client.GetTableReference(tableName);
                TablePermissions permissions = table.GetPermissions();
                SharedAccessTablePolicy policy = null;
                if (!permissions.SharedAccessPolicies.ContainsKey(PolicyName))
                {
                    policy = new SharedAccessTablePolicy()
                    {
                        Permissions = SharedAccessTablePermissions.Add | SharedAccessTablePermissions.Delete | SharedAccessTablePermissions.Query | SharedAccessTablePermissions.Update,
                        SharedAccessExpiryTime = DateTimeOffset.MaxValue,
                    };

                    permissions.SharedAccessPolicies.Add(PolicyName, policy);

                    table.SetPermissions(permissions);

                }
                else
                {
                    policy = permissions.SharedAccessPolicies[PolicyName];
                }

                var sasToken = table.GetSharedAccessSignature(policy);
                Console.WriteLine("{0}{1}", storageUri, sasToken);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
        public string GetSas(string partition, SharedAccessTablePermissions permissions)
        {
            SharedAccessTablePolicy policy = new SharedAccessTablePolicy()
            {
                SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(15),
                Permissions = permissions
            };

            string sasToken = this.ServiceClient.GetTableReference("Photos").GetSharedAccessSignature(
                policy   /* access policy */,
                null     /* access policy identifier */,
                partition /* start partition key */,
                null     /* start row key */,
                partition /* end partition key */,
                null     /* end row key */);

            return sasToken;
        }
        public void AddTestStoredAccessPolicy()
        {
            tableMock.tablePermissions.SharedAccessPolicies.Clear();

            SharedAccessTablePolicy testPolicy1 = new SharedAccessTablePolicy();
            testPolicy1.Permissions = SharedAccessTablePermissions.None;
            testPolicy1.Permissions |= SharedAccessTablePermissions.Query;
            testPolicy1.SharedAccessStartTime = DateTime.Today.ToUniversalTime();
            testPolicy1.SharedAccessExpiryTime = DateTime.Today.AddDays(1).ToUniversalTime();
            tableMock.tablePermissions.SharedAccessPolicies.Add(TestPolicy1, testPolicy1);

            SharedAccessTablePolicy testPolicy2 = new SharedAccessTablePolicy();
            testPolicy1.Permissions = SharedAccessTablePermissions.None;
            testPolicy1.Permissions |= SharedAccessTablePermissions.Query;
            testPolicy1.SharedAccessStartTime = DateTime.Today.ToUniversalTime();
            testPolicy1.SharedAccessExpiryTime = DateTime.Today.AddDays(1).ToUniversalTime();
            tableMock.tablePermissions.SharedAccessPolicies.Add(TestPolicy2, testPolicy2);
        }
        /// <summary>
        /// Returns a shared access signature for the table.
        /// </summary>
        /// <param name="policy">A <see cref="SharedAccessTablePolicy"/> object specifying the access policy for the shared access signature.</param>
        /// <param name="accessPolicyIdentifier">A string identifying a stored access policy.</param>
        /// <param name="startPartitionKey">A string specifying the start partition key, or <c>null</c>.</param>
        /// <param name="startRowKey">A string specifying the start row key, or <c>null</c>.</param>
        /// <param name="endPartitionKey">A string specifying the end partition key, or <c>null</c>.</param>
        /// <param name="endRowKey">A string specifying the end row key, or <c>null</c>.</param>
        /// <param name="sasVersion">A string indicating the desired SAS version to use, in storage service version format. Value must be <c>2012-02-12</c> or later.</param>
        /// <returns>A shared access signature, as a URI query string.</returns>
        /// <remarks>The query string returned includes the leading question mark.</remarks>
        /// <exception cref="InvalidOperationException">Thrown if the current credentials don't support creating a shared access signature.</exception>
        public string GetSharedAccessSignature(
            SharedAccessTablePolicy policy,
            string accessPolicyIdentifier,
            string startPartitionKey,
            string startRowKey,
            string endPartitionKey,
            string endRowKey,
            string sasVersion)
        {
            if (!this.ServiceClient.Credentials.IsSharedKey)
            {
                string errorMessage = string.Format(CultureInfo.CurrentCulture, SR.CannotCreateSASWithoutAccountKey);
                throw new InvalidOperationException(errorMessage);
            }

            string            resourceName        = this.GetCanonicalName();
            StorageAccountKey accountKey          = this.ServiceClient.Credentials.Key;
            string            validatedSASVersion = SharedAccessSignatureHelper.ValidateSASVersionString(sasVersion);

            string signature = SharedAccessSignatureHelper.GetHash(
                policy,
                accessPolicyIdentifier,
                startPartitionKey,
                startRowKey,
                endPartitionKey,
                endRowKey,
                resourceName,
                validatedSASVersion,
                accountKey.KeyValue);

            UriQueryBuilder builder = SharedAccessSignatureHelper.GetSignature(
                policy,
                this.Name,
                accessPolicyIdentifier,
                startPartitionKey,
                startRowKey,
                endPartitionKey,
                endRowKey,
                signature,
                accountKey.KeyName,
                validatedSASVersion);

            return(builder.ToString());
        }
        public static string GetSasForTable(string username)
        {
            var cloudTableClient = StorageAccount.CreateCloudTableClient();
            var policy = new SharedAccessTablePolicy()
            {
                SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(15),
                Permissions = SharedAccessTablePermissions.Add | SharedAccessTablePermissions.Delete | SharedAccessTablePermissions.Query | SharedAccessTablePermissions.Update
            };

            var sasToken = cloudTableClient.GetTableReference("Photos").GetSharedAccessSignature(
                policy: policy,
                accessPolicyIdentifier: null,
                startPartitionKey: username,
                startRowKey: null,
                endPartitionKey: username,
                endRowKey: null);

            return sasToken;
        }
Beispiel #12
0
        public async Task TableSasUriTestAsync()
        {
            CloudTableClient tableClient = GenerateCloudTableClient();
            CloudTable       table       = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N"));

            try
            {
                await table.CreateAsync();

                BaseEntity entity  = new BaseEntity("PK", "RK");
                BaseEntity entity1 = new BaseEntity("PK", "RK1");
                await table.ExecuteAsync(TableOperation.Insert(entity));

                await table.ExecuteAsync(TableOperation.Insert(entity1));

                SharedAccessTablePolicy policy = new SharedAccessTablePolicy()
                {
                    SharedAccessStartTime  = DateTimeOffset.UtcNow.AddMinutes(-5),
                    SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                    Permissions            = SharedAccessTablePermissions.Delete,
                };

                string              sasToken = table.GetSharedAccessSignature(policy, null, null, null, null, null);
                StorageCredentials  creds    = new StorageCredentials(sasToken);
                CloudStorageAccount sasAcc   = new CloudStorageAccount(creds, null /* blobEndpoint */, null /* queueEndpoint */, new Uri(TestBase.TargetTenantConfig.TableServiceEndpoint), null /* fileEndpoint */);
                CloudTableClient    client   = sasAcc.CreateCloudTableClient();

                CloudTable sasTable = new CloudTable(client.Credentials.TransformUri(table.Uri));
                await sasTable.ExecuteAsync(TableOperation.Delete(entity));

                CloudTable sasTable2 = new CloudTable(new Uri(table.Uri.ToString() + sasToken));
                await sasTable2.ExecuteAsync(TableOperation.Delete(entity1));
            }
            finally
            {
                table.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
Beispiel #13
0
        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 async Task TableSasUriTestAsync()
        {
            CloudTableClient tableClient = GenerateCloudTableClient();
            CloudTable table = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N"));

            try
            {
                await table.CreateAsync();

                BaseEntity entity = new BaseEntity("PK", "RK");
                BaseEntity entity1 = new BaseEntity("PK", "RK1");
                await table.ExecuteAsync(TableOperation.Insert(entity));
                await table.ExecuteAsync(TableOperation.Insert(entity1));

                SharedAccessTablePolicy policy = new SharedAccessTablePolicy()
                {
                    SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5),
                    SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                    Permissions = SharedAccessTablePermissions.Delete,
                };

                string sasToken = table.GetSharedAccessSignature(policy, null, null, null, null, null);
                StorageCredentials creds = new StorageCredentials(sasToken);
                CloudStorageAccount sasAcc = new CloudStorageAccount(creds, null /* blobEndpoint */, null /* queueEndpoint */, new Uri(TestBase.TargetTenantConfig.TableServiceEndpoint), null /* fileEndpoint */);
                CloudTableClient client = sasAcc.CreateCloudTableClient();

                CloudTable sasTable = new CloudTable(client.Credentials.TransformUri(table.Uri));
                await sasTable.ExecuteAsync(TableOperation.Delete(entity));

                CloudTable sasTable2 = new CloudTable(new Uri(table.Uri.ToString() + sasToken));
                await sasTable2.ExecuteAsync(TableOperation.Delete(entity1));
            }
            finally
            {
                table.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
        /// <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);
            }
        }
        internal static string GetHash(
            SharedAccessTablePolicy policy,
            string accessPolicyIdentifier,
            string startPartitionKey,
            string startRowKey,
            string endPartitionKey,
            string endRowKey,
            string resourceName,
            string sasVersion,
            byte[] keyValue)
        {
            CommonUtility.AssertNotNullOrEmpty("resourceName", resourceName);
            CommonUtility.AssertNotNull("keyValue", keyValue);
            CommonUtility.AssertNotNullOrEmpty("sasVersion", sasVersion);

            string permissions = null;
            DateTimeOffset? startTime = null;
            DateTimeOffset? expiryTime = null;
            if (policy != null)
            {
                permissions = SharedAccessTablePolicy.PermissionsToString(policy.Permissions);
                startTime = policy.SharedAccessStartTime;
                expiryTime = policy.SharedAccessExpiryTime;
            }

            //// StringToSign =      signedpermissions + "\n" +
            ////                     signedstart + "\n" +
            ////                     signedexpiry + "\n" +
            ////                     canonicalizedresource + "\n" +
            ////                     signedidentifier + "\n" +
            ////                     signedversion + "\n" +
            ////                     startpk + "\n" +
            ////                     startrk + "\n" +
            ////                     endpk + "\n" +
            ////                     endrk
            ////
            //// HMAC-SHA256(UTF8.Encode(StringToSign))

            string stringToSign = string.Format(
                                     CultureInfo.InvariantCulture,
                                     "{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n{6}\n{7}\n{8}\n{9}",
                                     permissions,
                                     GetDateTimeOrEmpty(startTime),
                                     GetDateTimeOrEmpty(expiryTime),
                                     resourceName,
                                     accessPolicyIdentifier,
                                     sasVersion,
                                     startPartitionKey,
                                     startRowKey,
                                     endPartitionKey,
                                     endRowKey);

            return CryptoUtility.ComputeHmac256(keyValue, stringToSign);
        }
        public async Task TableUpdateSasTestAsync()
        {
            CloudTableClient tableClient = GenerateCloudTableClient();
            CloudTable table = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N"));

            try
            {
                await table.CreateAsync();

                BaseEntity entity = new BaseEntity("PK", "RK");
                await table.ExecuteAsync(TableOperation.Insert(entity));

                SharedAccessTablePolicy policy = new SharedAccessTablePolicy()
                {
                    SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5),
                    SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                    Permissions = SharedAccessTablePermissions.Delete,
                };

                string sasToken = table.GetSharedAccessSignature(policy, null, null, null, null, null);
                StorageCredentials creds = new StorageCredentials(sasToken);
                CloudTable sasTable = new CloudTable(table.Uri, creds);
                OperationContext context = new OperationContext();
                await TestHelper.ExpectedExceptionAsync(
                    async () => await sasTable.ExecuteAsync(TableOperation.Insert(new BaseEntity("PK", "RK2")), null, context),
                    context,
                    "Try to insert an entity when SAS doesn't allow inserts",
                    HttpStatusCode.Forbidden);

                await sasTable.ExecuteAsync(TableOperation.Delete(entity));

                SharedAccessTablePolicy policy2 = new SharedAccessTablePolicy()
                {
                    SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5),
                    SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                    Permissions = SharedAccessTablePermissions.Delete | SharedAccessTablePermissions.Add,
                };

                string sasToken2 = table.GetSharedAccessSignature(policy2, null, null, null, null, null);
                creds.UpdateSASToken(sasToken2);

                sasTable = new CloudTable(table.Uri, creds);

                await sasTable.ExecuteAsync(TableOperation.Insert(new BaseEntity("PK", "RK2")));

            }
            finally
            {
                table.DeleteIfExistsAsync().AsTask().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;
        }
        /// <summary>
        /// Get the complete query builder for creating the Shared Access Signature query.
        /// </summary>
        /// <param name="policy">The shared access policy to hash.</param>
        /// <param name="tableName">The name of the table associated with this shared access signature.</param>
        /// <param name="accessPolicyIdentifier">An optional identifier for the policy.</param>
        /// <param name="startPartitionKey">The start partition key, or <c>null</c>.</param>
        /// <param name="startRowKey">The start row key, or <c>null</c>.</param>
        /// <param name="endPartitionKey">The end partition key, or <c>null</c>.</param>
        /// <param name="endRowKey">The end row key, or <c>null</c>.</param>
        /// <param name="signature">The signature to use.</param>
        /// <param name="accountKeyName">The name of the key used to create the signature, or <c>null</c> if the key is implicit.</param>
        /// <param name="sasVersion">A string indicating the desired SAS version to use, in storage service version format. Value must be <c>2012-02-12</c> or later.</param>
        /// <returns>The finished query builder.</returns>
        internal static UriQueryBuilder GetSignature(
            SharedAccessTablePolicy policy,
            string tableName,
            string accessPolicyIdentifier,
            string startPartitionKey,
            string startRowKey,
            string endPartitionKey,
            string endRowKey,
            string signature,
            string accountKeyName,
            string sasVersion)
        {          
            CommonUtility.AssertNotNull("signature", signature);

            UriQueryBuilder builder = new UriQueryBuilder();
 
            AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedVersion, sasVersion);
            AddEscapedIfNotNull(builder, Constants.QueryConstants.SasTableName, tableName);
            AddEscapedIfNotNull(builder, Constants.QueryConstants.StartPartitionKey, startPartitionKey);
            AddEscapedIfNotNull(builder, Constants.QueryConstants.StartRowKey, startRowKey);
            AddEscapedIfNotNull(builder, Constants.QueryConstants.EndPartitionKey, endPartitionKey);
            AddEscapedIfNotNull(builder, Constants.QueryConstants.EndRowKey, endRowKey);
            AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedIdentifier, accessPolicyIdentifier);
            AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedKey, accountKeyName);
            AddEscapedIfNotNull(builder, Constants.QueryConstants.Signature, signature);

            if (policy != null)
            {
                AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedStart, GetDateTimeOrNull(policy.SharedAccessStartTime));
                AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedExpiry, GetDateTimeOrNull(policy.SharedAccessExpiryTime));

                string permissions = SharedAccessTablePolicy.PermissionsToString(policy.Permissions);
                if (!string.IsNullOrEmpty(permissions))
                {
                    AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedPermissions, permissions);
                }
            }

            return builder;
        }
Beispiel #20
0
		static string RequestSasToken(CloudTable table, string customerId)
		{
			// Omitting any authentication code since this is beyond the scope of
			// this sample code

			// creating a shared access policy that expires in 1 day.
			// No start time is specified, which means that the token is valid immediately.
			// The policy specifies full permissions.
			SharedAccessTablePolicy policy = new SharedAccessTablePolicy()
			{
				SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-15),
				SharedAccessExpiryTime = DateTime.UtcNow.AddDays(1.0),
				Permissions = SharedAccessTablePermissions.Add
					| SharedAccessTablePermissions.Query
					| SharedAccessTablePermissions.Update
					| SharedAccessTablePermissions.Delete
			};

			// Generate the SAS token. No access policy identifier is used which
			// makes it a non-revocable token
			// limiting the table SAS access to only the request customer's id
			string sasToken = table.GetSharedAccessSignature(
				policy   /* access policy */,
				null     /* access policy identifier */,
				customerId /* start partition key */,
				null     /* start row key */,
				customerId /* end partition key */,
				null     /* end row key */);

			return sasToken;
		}
        public void CloudTableSASWithAbsoluteUri()
        {
            CloudTableClient tableClient = GenerateCloudTableClient();

            CloudTable table = tableClient.GetTableReference(tableClient.BaseUri + GenerateRandomTableName());
            try
            {
                table.CreateIfNotExists();

                BaseEntity entity = new BaseEntity("PK", "RK");
                table.Execute(TableOperation.Insert(entity));

                SharedAccessTablePolicy policy = new SharedAccessTablePolicy()
                {
                    Permissions = SharedAccessTablePermissions.Delete,
                    SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5),
                    SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(10)
                };

                string sasToken = table.GetSharedAccessSignature(policy);
                StorageCredentials creds = new StorageCredentials(sasToken);

                CloudTable sasTable = new CloudTable(table.Uri, creds);
                sasTable.Execute(TableOperation.Delete(entity));
            }
            finally
            {
                table.DeleteIfExists();
            }
        }
        public Url UsersUrl()
        {
            var policy = new SharedAccessTablePolicy
            {
                Permissions = SharedAccessTablePermissions.Query,
                SharedAccessExpiryTime = DateTime.UtcNow.AddDays(2)
            };

            var table =
                new CloudStorageAccount(
                    new StorageCredentials(
                        CloudConfigurationManager.GetSetting("storageAccountName"),
                        CloudConfigurationManager.GetSetting("storageAccountKey")),
                    true).CreateCloudTableClient().GetTableReference(ApplicationUserStore.UsersTableName);

            var token = table.GetSharedAccessSignature(policy);

            return new Url(table.Uri.AbsoluteUri + token);
        }
        public void SetupAccessPolicyTest()
        {
            DateTime? start = DateTime.Now;
            DateTime? end = start.Value.AddHours(1.0);

            SharedAccessBlobPolicy blobAccessPolicy = new SharedAccessBlobPolicy();
            AccessPolicyHelper.SetupAccessPolicy(blobAccessPolicy, start, end, "a");
            Assert.AreEqual(blobAccessPolicy.SharedAccessStartTime.Value.UtcDateTime.ToString(), start.Value.ToUniversalTime().ToString());
            Assert.AreEqual(blobAccessPolicy.SharedAccessExpiryTime.Value.UtcDateTime.ToString(), end.Value.ToUniversalTime().ToString());
            Assert.AreEqual(blobAccessPolicy.Permissions, SharedAccessBlobPermissions.Add);

            SharedAccessTablePolicy tableAccessPolicy = new SharedAccessTablePolicy();
            AccessPolicyHelper.SetupAccessPolicy(tableAccessPolicy, null, end, "d", true);
            Assert.AreEqual(tableAccessPolicy.SharedAccessStartTime, null);
            Assert.AreEqual(tableAccessPolicy.SharedAccessExpiryTime.Value.UtcDateTime.ToString(), end.Value.ToUniversalTime().ToString());
            Assert.AreEqual(tableAccessPolicy.Permissions, SharedAccessTablePermissions.Delete);

            SharedAccessQueuePolicy queueAccessPolicy = new SharedAccessQueuePolicy();
            AccessPolicyHelper.SetupAccessPolicy(queueAccessPolicy, start, null, "", noExpiryTime: true);
            Assert.AreEqual(queueAccessPolicy.SharedAccessStartTime.Value.UtcDateTime.ToString(), start.Value.ToUniversalTime().ToString());
            Assert.AreEqual(queueAccessPolicy.SharedAccessExpiryTime, null);
            Assert.AreEqual(queueAccessPolicy.Permissions, SharedAccessQueuePermissions.None);

            SharedAccessFilePolicy fileAccessPolicy = new SharedAccessFilePolicy();
            AccessPolicyHelper.SetupAccessPolicy(fileAccessPolicy, null, null, "dl", true, true);
            Assert.AreEqual(fileAccessPolicy.SharedAccessStartTime, null);
            Assert.AreEqual(fileAccessPolicy.SharedAccessExpiryTime, null);
            Assert.AreEqual(fileAccessPolicy.Permissions, SharedAccessFilePermissions.List| SharedAccessFilePermissions.Delete);
        }
        /// <summary>
        /// Get the complete query builder for creating the Shared Access Signature query.
        /// </summary>
        /// <param name="policy">The shared access policy to hash.</param>
        /// <param name="tableName">The name of the table associated with this shared access signature.</param>
        /// <param name="accessPolicyIdentifier">An optional identifier for the policy.</param>
        /// <param name="startPartitionKey">The start partition key, or null.</param>
        /// <param name="startRowKey">The start row key, or null.</param>
        /// <param name="endPartitionKey">The end partition key, or null.</param>
        /// <param name="endRowKey">The end row key, or null.</param>
        /// <param name="signature">The signature to use.</param>
        /// <param name="accountKeyName">The name of the key used to create the signature, or null if the key is implicit.</param>
        /// <returns>The finished query builder.</returns>
        internal static UriQueryBuilder GetSharedAccessSignatureImpl(
            SharedAccessTablePolicy policy,
            string tableName,
            string accessPolicyIdentifier,
            string startPartitionKey,
            string startRowKey,
            string endPartitionKey,
            string endRowKey,
            string signature,
            string accountKeyName)
        {          
            CommonUtility.AssertNotNull("signature", signature);

            if (policy == null)
            {
                return GetSharedAccessSignatureImpl(
                    null /* policy.Permissions */,
                    null /* policy.SharedAccessStartTime */,
                    null /* policy.SharedAccessExpiryTime */,
                    startPartitionKey,
                    startRowKey,
                    endPartitionKey,
                    endRowKey,
                    accessPolicyIdentifier,
                    null /* resourceType (blob only) */,
                    tableName,
                    signature,
                    accountKeyName);
            }

            string permissions = SharedAccessTablePolicy.PermissionsToString(policy.Permissions);
            if (string.IsNullOrEmpty(permissions))
            {
                permissions = null;
            }

            return GetSharedAccessSignatureImpl(
                permissions,
                policy.SharedAccessStartTime,
                policy.SharedAccessExpiryTime,
                startPartitionKey,
                startRowKey,
                endPartitionKey,
                endRowKey,
                accessPolicyIdentifier,
                null /* resourceType (blob only) */,
                tableName,
                signature,
                accountKeyName);
        }
        /// <summary>
        /// Get the signature hash embedded inside the Shared Access Signature.
        /// </summary>
        /// <param name="policy">The shared access policy to hash.</param>
        /// <param name="accessPolicyIdentifier">An optional identifier for the policy.</param>
        /// <param name="startPartitionKey">The start partition key, or null.</param>
        /// <param name="startRowKey">The start row key, or null.</param>
        /// <param name="endPartitionKey">The end partition key, or null.</param>
        /// <param name="endRowKey">The end row key, or null.</param>
        /// <param name="resourceName">The canonical resource string, unescaped.</param>
        /// <param name="keyValue">The key value retrieved as an atomic operation used for signing.</param>
        /// <returns>The signed hash.</returns>
        internal static string GetSharedAccessSignatureHashImpl(
            SharedAccessTablePolicy policy,
            string accessPolicyIdentifier,
            string startPartitionKey,
            string startRowKey,
            string endPartitionKey,
            string endRowKey,
            string resourceName,
            byte[] keyValue)
        {
            if (policy == null)
            {
                return GetSharedAccessSignatureHashImpl(
                    null /* policy.Permissions */,
                    null /* policy.SharedAccessStartTime */,
                    null /* policy.SharedAccessExpiryTime */,
                    startPartitionKey,
                    startRowKey,
                    endPartitionKey,
                    endRowKey,
                    true /* using table SAS */,
                    accessPolicyIdentifier,
                    resourceName,
                    keyValue);
            }

            return GetSharedAccessSignatureHashImpl(
                SharedAccessTablePolicy.PermissionsToString(policy.Permissions),
                policy.SharedAccessStartTime,
                policy.SharedAccessExpiryTime,
                startPartitionKey,
                startRowKey,
                endPartitionKey,
                endRowKey,
                true /* using table SAS */,
                accessPolicyIdentifier,
                resourceName,
                keyValue);
        }
 /// <summary>
 /// Returns a shared access signature for the table.
 /// </summary>
 /// <param name="policy">A <see cref="SharedAccessTablePolicy"/> object specifying the access policy for the shared access signature.</param>
 /// <param name="accessPolicyIdentifier">A string identifying a stored access policy.</param>
 /// <returns>A shared access signature, as a URI query string.</returns>
 /// <remarks>The query string returned includes the leading question mark.</remarks>
 /// <exception cref="InvalidOperationException">Thrown if the current credentials don't support creating a shared access signature.</exception>
 public string GetSharedAccessSignature(SharedAccessTablePolicy policy, string accessPolicyIdentifier)
 {
     return this.GetSharedAccessSignature(
         policy,
         accessPolicyIdentifier,
         null /* startPartitionKey */,
         null /* startRowKey */,
         null /* endPartitionKey */,
         null /* endRowKey */);
 }
        /// <summary>
        /// Returns a URI containing a SAS for the table.
        /// </summary>
        /// <param name="table">A CloudTable object.</param>
        /// <param name="storedPolicyName">A string containing the name of the stored access policy. If null, an ad-hoc SAS is created.</param>
        /// <returns>A string containing the URI for the table, with the SAS token appended.</returns>
        private static string GetTableSasUri(CloudTable table, string storedPolicyName = null)
        {
            string sasTableToken;

            // If no stored policy is specified, create a new access policy and define its constraints.
            if (storedPolicyName == null)
            {
                // Note that the SharedAccessTablePolicy class is used both to define the parameters of an ad-hoc SAS, and 
                // to construct a shared access policy that is saved to the table's shared access policies. 
                SharedAccessTablePolicy adHocPolicy = 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
                };

                // Generate the shared access signature on the table, setting the constraints directly on the signature.
                sasTableToken = table.GetSharedAccessSignature(adHocPolicy, null);

                Console.WriteLine("SAS for table (ad hoc): {0}", sasTableToken);
                Console.WriteLine();
            }
            else
            {
                // Generate the shared access signature on the table. In this case, all of the constraints for the
                // shared access signature are specified on the stored access policy, which is provided by name.
                // It is also possible to specify some constraints on an ad-hoc SAS and others on the stored access policy.
                // However, a constraint must be specified on one or the other; it cannot be specified on both.
                sasTableToken = table.GetSharedAccessSignature(null, storedPolicyName);

                Console.WriteLine("SAS for table (stored access policy): {0}", sasTableToken);
                Console.WriteLine();
            }

            // Return the URI string for the table, including the SAS token.
            return table.Uri + sasTableToken;
        }
 /// <summary>
 /// Returns a shared access signature for the table.
 /// </summary>
 /// <param name="policy">A <see cref="SharedAccessTablePolicy"/> object specifying the access policy for the shared access signature.</param>
 /// <param name="accessPolicyIdentifier">A string identifying a stored access policy.</param>
 /// <param name="startPartitionKey">A string specifying the start partition key, or <c>null</c>.</param>
 /// <param name="startRowKey">A string specifying the start row key, or <c>null</c>.</param>
 /// <param name="endPartitionKey">A string specifying the end partition key, or <c>null</c>.</param>
 /// <param name="endRowKey">A string specifying the end row key, or <c>null</c>.</param>
 /// <returns>A shared access signature, as a URI query string.</returns>
 /// <remarks>The query string returned includes the leading question mark.</remarks>
 /// <exception cref="InvalidOperationException">Thrown if the current credentials don't support creating a shared access signature.</exception>
 public string GetSharedAccessSignature(
     SharedAccessTablePolicy policy,
     string accessPolicyIdentifier,
     string startPartitionKey,
     string startRowKey,
     string endPartitionKey,
     string endRowKey)
 {
     return this.GetSharedAccessSignature(
         policy,
         accessPolicyIdentifier,
         startPartitionKey,
         startRowKey,
         endPartitionKey,
         endRowKey,
         null /* sasVersion */);
 }
 /// <summary>
 /// Update the access policy
 /// </summary>
 /// <param name="policy">Access policy object</param>
 /// <param name="shouldSetExpiryTime">Should set the default expiry time</param>
 private void SetupAccessPolicy(SharedAccessTablePolicy policy, bool shouldSetExpiryTime)
 {
     DateTimeOffset? accessStartTime;
     DateTimeOffset? accessEndTime;
     SasTokenHelper.SetupAccessPolicyLifeTime(StartTime, ExpiryTime,
         out accessStartTime, out accessEndTime, shouldSetExpiryTime);
     policy.SharedAccessStartTime = accessStartTime;
     policy.SharedAccessExpiryTime = accessEndTime;
     SetupAccessPolicyPermission(policy, Permission);
 }
        public void TableUpdateSasTestSync()
        {
            CloudTableClient tableClient = GenerateCloudTableClient();
            CloudTable table = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N"));

            try
            {
                table.Create();

                BaseEntity entity = new BaseEntity("PK", "RK");
                table.Execute(TableOperation.Insert(entity));

                SharedAccessTablePolicy policy = new SharedAccessTablePolicy()
                {
                    SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5),
                    SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                    Permissions = SharedAccessTablePermissions.Delete,
                };

                string sasToken = table.GetSharedAccessSignature(policy);
                StorageCredentials creds = new StorageCredentials(sasToken);
                CloudTable sasTable = new CloudTable(table.Uri, creds);
                TestHelper.ExpectedException(
                    () => sasTable.Execute(TableOperation.Insert(new BaseEntity("PK", "RK2"))),
                    "Try to insert an entity when SAS doesn't allow inserts",
                    HttpStatusCode.NotFound);

                sasTable.Execute(TableOperation.Delete(entity));

                SharedAccessTablePolicy policy2 = new SharedAccessTablePolicy()
                {
                    SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5),
                    SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                    Permissions = SharedAccessTablePermissions.Delete | SharedAccessTablePermissions.Add,
                };

                string sasToken2 = table.GetSharedAccessSignature(policy2);
                creds.UpdateSASToken(sasToken2);

                sasTable = new CloudTable(table.Uri, creds);

                sasTable.Execute(TableOperation.Insert(new BaseEntity("PK", "RK2")));

            }
            finally
            {
                table.DeleteIfExists();
            }
        }
 public string GetSharedAccessSignature(SharedAccessTablePolicy policy, string accessPolicyIdentifier, string startPartitionKey, string startRowKey, string endPartitionKey, string endRowKey, SharedAccessProtocol?protocols, IPAddressOrRange ipAddressOrRange)
 {
     throw new System.NotImplementedException();
 }
 public string GetSharedAccessSignature(SharedAccessTablePolicy policy, string accessPolicyIdentifier, string startPartitionKey, string startRowKey, string endPartitionKey, string endRowKey)
 {
     throw new System.NotImplementedException();
 }
        public void TableSasUriPkRkTestSync()
        {
            CloudTableClient tableClient = GenerateCloudTableClient();
            CloudTable table = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N"));

            try
            {
                table.Create();

                SharedAccessTablePolicy policy = new SharedAccessTablePolicy()
                {
                    SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5),
                    SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                    Permissions = SharedAccessTablePermissions.Add,
                };

                string sasTokenPkRk = table.GetSharedAccessSignature(policy, null, "tables_batch_0", "00",
                    "tables_batch_1", "04");
                StorageCredentials credsPkRk = new StorageCredentials(sasTokenPkRk);

                // transform uri from credentials
                CloudTable sasTableTransformed = new CloudTable(credsPkRk.TransformUri(table.Uri));

                // create uri by appending sas
                CloudTable sasTableDirect = new CloudTable(new Uri(table.Uri.ToString() + sasTokenPkRk));

                BaseEntity pkrkEnt = new BaseEntity("tables_batch_0", "00");
                sasTableTransformed.Execute(TableOperation.Insert(pkrkEnt));

                pkrkEnt = new BaseEntity("tables_batch_0", "01");
                sasTableDirect.Execute(TableOperation.Insert(pkrkEnt));

                Action<BaseEntity, CloudTable, OperationContext> insertDelegate = (tableEntity, sasTable1, ctx) =>
                {
                    sasTable1.Execute(TableOperation.Insert(tableEntity), null, ctx);
                };

                pkrkEnt = new BaseEntity("tables_batch_2", "00");
                TestHelper.ExpectedException(
                    (ctx) => insertDelegate(pkrkEnt, sasTableTransformed, ctx),
                    string.Format("Inserted entity without appropriate SAS permissions."),
                    (int)HttpStatusCode.Forbidden);
                TestHelper.ExpectedException(
                     (ctx) => insertDelegate(pkrkEnt, sasTableDirect, ctx),
                    string.Format("Inserted entity without appropriate SAS permissions."),
                     (int)HttpStatusCode.Forbidden);

                pkrkEnt = new BaseEntity("tables_batch_1", "05");
                TestHelper.ExpectedException(
                    (ctx) => insertDelegate(pkrkEnt, sasTableTransformed, ctx),
                    string.Format("Inserted entity without appropriate SAS permissions."),
                    (int)HttpStatusCode.Forbidden);
                TestHelper.ExpectedException(
                     (ctx) => insertDelegate(pkrkEnt, sasTableDirect, ctx),
                    string.Format("Inserted entity without appropriate SAS permissions."),
                     (int)HttpStatusCode.Forbidden);
            }
            finally
            {
                table.DeleteIfExists();
            }
        }
        /// <summary>
        /// Creates SAS constraints from the given parameters.
        /// </summary>
        /// <param name="permissions">The permission set.</param>
        /// <param name="expiration">The expiration time.</param>
        /// <returns>Returns the access policy.</returns>
        private static SharedAccessTablePolicy GetTableSasConstraints(ResourcePermissions permissions, DateTime? expiration)
        {
            SharedAccessTablePolicy sasConstraints = new SharedAccessTablePolicy();

            // Set the start time to five minutes in the past.
            sasConstraints.SharedAccessStartTime = DateTimeOffset.Now - TimeSpan.FromMinutes(5);

            // Expiration.
            if (expiration != null)
            {
                sasConstraints.SharedAccessExpiryTime = expiration.Value;
            }

            // Permissions.
            sasConstraints.Permissions = SharedAccessTablePermissions.None;
            if ((permissions & ResourcePermissions.Read) == ResourcePermissions.Read)
            {
                sasConstraints.Permissions |= SharedAccessTablePermissions.Query;
            }

            if ((permissions & ResourcePermissions.Add) == ResourcePermissions.Add)
            {
                sasConstraints.Permissions |= SharedAccessTablePermissions.Add;
            }

            if ((permissions & ResourcePermissions.Update) == ResourcePermissions.Update)
            {
                sasConstraints.Permissions |= SharedAccessTablePermissions.Update;
            }

            if ((permissions & ResourcePermissions.Delete) == ResourcePermissions.Delete)
            {
                sasConstraints.Permissions |= SharedAccessTablePermissions.Delete;
            }

            return sasConstraints;
        }
        /// <summary>
        /// Returns a shared access signature for the table.
        /// </summary>
        /// <param name="policy">The access policy for the shared access signature.</param>
        /// <param name="accessPolicyIdentifier">An access policy identifier.</param>
        /// <param name="startPartitionKey">The start partition key, or null.</param>
        /// <param name="startRowKey">The start row key, or null.</param>
        /// <param name="endPartitionKey">The end partition key, or null.</param>
        /// <param name="endRowKey">The end row key, or null.</param>
        /// <returns>A shared access signature, as a URI query string.</returns>
        /// <remarks>The query string returned includes the leading question mark.</remarks>
        /// <exception cref="InvalidOperationException">Thrown if the current credentials don't support creating a shared access signature.</exception>
        public string GetSharedAccessSignature(
            SharedAccessTablePolicy policy,
            string accessPolicyIdentifier,
            string startPartitionKey,
            string startRowKey,
            string endPartitionKey,
            string endRowKey)
        {
            if (!this.ServiceClient.Credentials.IsSharedKey)
            {
                string errorMessage = string.Format(CultureInfo.CurrentCulture, SR.CannotCreateSASWithoutAccountKey);
                throw new InvalidOperationException(errorMessage);
            }

            string resourceName = this.GetCanonicalName();
            StorageAccountKey accountKey = this.ServiceClient.Credentials.Key;

            string signature = SharedAccessSignatureHelper.GetSharedAccessSignatureHashImpl(
                policy,
                accessPolicyIdentifier,
                startPartitionKey,
                startRowKey,
                endPartitionKey,
                endRowKey,
                resourceName,
                accountKey.KeyValue);

            UriQueryBuilder builder = SharedAccessSignatureHelper.GetSharedAccessSignatureImpl(
                policy,
                this.Name,
                accessPolicyIdentifier,
                startPartitionKey,
                startRowKey,
                endPartitionKey,
                endRowKey,
                signature,
                accountKey.KeyName);

            return builder.ToString();
        }
        /// <summary>
        /// Helper function for testing the IPAddressOrRange funcitonality for tables
        /// </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 CloudTableSASIPAddressHelper(Func<IPAddressOrRange> generateInitialIPAddressOrRange, Func<IPAddress, IPAddressOrRange> generateFinalIPAddressOrRange)
        {
            CloudTableClient tableClient = GenerateCloudTableClient();
            CloudTable table = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N"));

            try
            {
                table.Create();
                SharedAccessTablePolicy policy = new SharedAccessTablePolicy()
                {
                    Permissions = SharedAccessTablePermissions.Query,
                    SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5),
                    SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                };

                DynamicTableEntity entity = new DynamicTableEntity("PK", "RK", null, new Dictionary<string, EntityProperty>() {{"prop", new EntityProperty(4)}});
                table.Execute(new TableOperation(entity, TableOperationType.Insert));

                // 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 tableToken = table.GetSharedAccessSignature(policy, null, null, null, null, null, null, ipAddressOrRange);
                StorageCredentials tableSAS = new StorageCredentials(tableToken);
                Uri tableSASUri = tableSAS.TransformUri(table.Uri);
                StorageUri tableSASStorageUri = tableSAS.TransformUri(table.StorageUri);

                CloudTable tableWithSAS = new CloudTable(tableSASUri);
                OperationContext opContext = new OperationContext();
                IPAddress actualIP = null;

                bool exceptionThrown = false;
                TableResult result = null;
                DynamicTableEntity resultEntity = new DynamicTableEntity();
                TableOperation retrieveOp = new TableOperation(resultEntity, TableOperationType.Retrieve);
                retrieveOp.RetrievePartitionKey = entity.PartitionKey;
                retrieveOp.RetrieveRowKey = entity.RowKey;
                try
                {
                    result = tableWithSAS.Execute(retrieveOp, null, opContext);
                }
                catch (StorageException e)
                {
                    string[] parts = e.RequestInformation.HttpStatusMessage.Split(' ');
                    actualIP = IPAddress.Parse(parts[parts.Length - 1].Trim('.'));
                    exceptionThrown = true;
                    Assert.IsNotNull(actualIP);
                }

                Assert.IsTrue(exceptionThrown);
                ipAddressOrRange = generateFinalIPAddressOrRange(actualIP);
                tableToken = table.GetSharedAccessSignature(policy, null, null, null, null, null, null, ipAddressOrRange);
                tableSAS = new StorageCredentials(tableToken);
                tableSASUri = tableSAS.TransformUri(table.Uri);
                tableSASStorageUri = tableSAS.TransformUri(table.StorageUri);


                tableWithSAS = new CloudTable(tableSASUri);
                resultEntity = new DynamicTableEntity();
                retrieveOp = new TableOperation(resultEntity, TableOperationType.Retrieve);
                retrieveOp.RetrievePartitionKey = entity.PartitionKey;
                retrieveOp.RetrieveRowKey = entity.RowKey;
                resultEntity = (DynamicTableEntity)tableWithSAS.Execute(retrieveOp).Result;
    
                Assert.AreEqual(entity.Properties["prop"].PropertyType, resultEntity.Properties["prop"].PropertyType);
                Assert.AreEqual(entity.Properties["prop"].Int32Value.Value, resultEntity.Properties["prop"].Int32Value.Value);
                Assert.IsTrue(table.StorageUri.PrimaryUri.Equals(tableWithSAS.Uri));
                Assert.IsNull(tableWithSAS.StorageUri.SecondaryUri);

                tableWithSAS = new CloudTable(tableSASStorageUri, null);
                resultEntity = new DynamicTableEntity();
                retrieveOp = new TableOperation(resultEntity, TableOperationType.Retrieve);
                retrieveOp.RetrievePartitionKey = entity.PartitionKey;
                retrieveOp.RetrieveRowKey = entity.RowKey;
                resultEntity = (DynamicTableEntity)tableWithSAS.Execute(retrieveOp).Result;
                Assert.AreEqual(entity.Properties["prop"].PropertyType, resultEntity.Properties["prop"].PropertyType);
                Assert.AreEqual(entity.Properties["prop"].Int32Value.Value, resultEntity.Properties["prop"].Int32Value.Value);
                Assert.IsTrue(table.StorageUri.Equals(tableWithSAS.StorageUri));
            }
            finally
            {
                table.DeleteIfExists();
            }
        }
        public override void ExecuteCmdlet()
        {
            if (String.IsNullOrEmpty(Name)) return;
            CloudTable table = Channel.GetTableReference(Name);
            SharedAccessTablePolicy policy = new SharedAccessTablePolicy();
            bool shouldSetExpiryTime = SasTokenHelper.ValidateTableAccessPolicy(Channel, table.Name, policy, accessPolicyIdentifier);
            SetupAccessPolicy(policy, shouldSetExpiryTime);
            ValidatePkAndRk(StartPartitionKey, StartRowKey, EndPartitionKey, EndRowKey);
            string sasToken = table.GetSharedAccessSignature(policy, accessPolicyIdentifier, StartPartitionKey,
                                StartRowKey, EndPartitionKey, EndRowKey);

            if (FullUri)
            {
                string fullUri = table.Uri.ToString() + sasToken;
                WriteObject(fullUri);
            }
            else
            {
                WriteObject(sasToken);
            }
        }
        public void CloudTableSASSharedProtocolsQueryParam()
        {
            CloudTableClient tableClient = GenerateCloudTableClient();
            CloudTable table = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N"));
            try
            {
                table.Create();
                SharedAccessTablePolicy policy = new SharedAccessTablePolicy()
                {
                    Permissions = SharedAccessTablePermissions.Query,
                    SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5),
                    SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                };

                DynamicTableEntity entity = new DynamicTableEntity("PK", "RK", null, new Dictionary<string, EntityProperty>() { { "prop", new EntityProperty(4) } });
                table.Execute(new TableOperation(entity, TableOperationType.Insert));

                foreach (SharedAccessProtocol? protocol in new SharedAccessProtocol?[] { null, SharedAccessProtocol.HttpsOrHttp, SharedAccessProtocol.HttpsOnly })
                {
                    string tableToken = table.GetSharedAccessSignature(policy, null, null, null, null, null, protocol, null);
                    StorageCredentials tableSAS = new StorageCredentials(tableToken);
                    Uri tableSASUri = new Uri(table.Uri + tableSAS.SASToken);
                    StorageUri tableSASStorageUri = new StorageUri(new Uri(table.StorageUri.PrimaryUri + tableSAS.SASToken), new Uri(table.StorageUri.SecondaryUri + tableSAS.SASToken));

                    int httpPort = tableSASUri.Port;
                    int securePort = 443;

                    if (!string.IsNullOrEmpty(TestBase.TargetTenantConfig.TableSecurePortOverride))
                    {
                        securePort = Int32.Parse(TestBase.TargetTenantConfig.TableSecurePortOverride);
                    }

                    var schemesAndPorts = new[] {
                        new { scheme = Uri.UriSchemeHttp, port = httpPort},
                        new { scheme = Uri.UriSchemeHttps, port = securePort}
                    };

                    CloudTable tableWithSAS = null;
                    TableOperation retrieveOp = TableOperation.Retrieve(entity.PartitionKey, entity.RowKey);

                    foreach (var item in schemesAndPorts)
                    {
                        tableSASUri = TransformSchemeAndPort(tableSASUri, item.scheme, item.port);
                        tableSASStorageUri = new StorageUri(TransformSchemeAndPort(tableSASStorageUri.PrimaryUri, item.scheme, item.port), TransformSchemeAndPort(tableSASStorageUri.SecondaryUri, item.scheme, item.port));

                        if (protocol.HasValue && protocol.Value == SharedAccessProtocol.HttpsOnly && string.CompareOrdinal(item.scheme, Uri.UriSchemeHttp) == 0)
                        {
                            tableWithSAS = new CloudTable(tableSASUri);
                            TestHelper.ExpectedException(() => tableWithSAS.Execute(retrieveOp), "Access a table using SAS with a shared protocols that does not match", HttpStatusCode.Unused);

                            tableWithSAS = new CloudTable(tableSASStorageUri, null);
                            TestHelper.ExpectedException(() => tableWithSAS.Execute(retrieveOp), "Access a table using SAS with a shared protocols that does not match", HttpStatusCode.Unused);
                        }
                        else
                        {
                            tableWithSAS = new CloudTable(tableSASUri);
                            TableResult result = tableWithSAS.Execute(retrieveOp);
                            Assert.AreEqual(entity.Properties["prop"], ((DynamicTableEntity)result.Result).Properties["prop"]);

                            tableWithSAS = new CloudTable(tableSASStorageUri, null);
                            result = tableWithSAS.Execute(retrieveOp);
                            Assert.AreEqual(entity.Properties["prop"], ((DynamicTableEntity)result.Result).Properties["prop"]);
                        }
                    }
                }
            }
            finally
            {
                table.DeleteIfExists();
            }
        }
 /// <summary>
 /// Set up access policy permission
 /// </summary>
 /// <param name="policy">SharedAccessBlobPolicy object</param>
 /// <param name="permission">Permission</param>
 internal void SetupAccessPolicyPermission(SharedAccessTablePolicy policy, string permission)
 {
     if (string.IsNullOrEmpty(permission)) return;
     policy.Permissions = SharedAccessTablePermissions.None;
     permission = permission.ToLower();
     foreach (char op in permission)
     {
         switch (op)
         {
             case StorageNouns.Permission.Add:
                 policy.Permissions |= SharedAccessTablePermissions.Add;
                 break;
             case StorageNouns.Permission.Update:
                 policy.Permissions |= SharedAccessTablePermissions.Update;
                 break;
             case StorageNouns.Permission.Delete:
                 policy.Permissions |= SharedAccessTablePermissions.Delete;
                 break;
             case StorageNouns.Permission.Read:
             case StorageNouns.Permission.Query:
                 policy.Permissions |= SharedAccessTablePermissions.Query;
                 break;
             default:
                 throw new ArgumentException(string.Format(Resources.InvalidAccessPermission, op));
         }
     }
 }
 public string GetSharedAccessSignature(SharedAccessTablePolicy policy, string accessPolicyIdentifier)
 {
     throw new System.NotImplementedException();
 }