internal string CreateAzureQueueStoredAccessPolicy(IStorageQueueManagement localChannel, string queueName, 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
            CloudQueue queue = Channel.GetQueueReference(queueName);
            QueuePermissions queuePermissions = localChannel.GetPermissions(queue);

            //Add new policy
            if (queuePermissions.SharedAccessPolicies.Keys.Contains(policyName))
            {
                throw new ResourceAlreadyExistException(String.Format(CultureInfo.CurrentCulture, Resources.PolicyAlreadyExists, policyName));
            }

            SharedAccessQueuePolicy policy = new SharedAccessQueuePolicy();
            AccessPolicyHelper.SetupAccessPolicy<SharedAccessQueuePolicy>(policy, startTime, expiryTime, permission);
            queuePermissions.SharedAccessPolicies.Add(policyName, policy);

            //Set permissions back to queue
            localChannel.SetPermissions(queue, queuePermissions); 
            return policyName;
        }
 public void SetupAccessPolicyPermissionTest()
 {
     SharedAccessQueuePolicy accessPolicy = new SharedAccessQueuePolicy();
     command.SetupAccessPolicyPermission(accessPolicy, "");
     Assert.AreEqual(accessPolicy.Permissions, SharedAccessQueuePermissions.None);
     accessPolicy.Permissions = SharedAccessQueuePermissions.Read;
     command.SetupAccessPolicyPermission(accessPolicy, "");
     Assert.AreEqual(accessPolicy.Permissions, SharedAccessQueuePermissions.Read);
     command.SetupAccessPolicyPermission(accessPolicy, "a");
     Assert.AreEqual(accessPolicy.Permissions, SharedAccessQueuePermissions.Add);
     command.SetupAccessPolicyPermission(accessPolicy, "aAaaa");
     Assert.AreEqual(accessPolicy.Permissions, SharedAccessQueuePermissions.Add);
     command.SetupAccessPolicyPermission(accessPolicy, "ru");
     Assert.AreEqual(accessPolicy.Permissions, SharedAccessQueuePermissions.Update | SharedAccessQueuePermissions.Read);
     command.SetupAccessPolicyPermission(accessPolicy, "ur");
     Assert.AreEqual(accessPolicy.Permissions, SharedAccessQueuePermissions.Update | SharedAccessQueuePermissions.Read);
     command.SetupAccessPolicyPermission(accessPolicy, "raUP");
     Assert.AreEqual(accessPolicy.Permissions, SharedAccessQueuePermissions.Add
         | SharedAccessQueuePermissions.Read | SharedAccessQueuePermissions.Update | SharedAccessQueuePermissions.ProcessMessages);
     command.SetupAccessPolicyPermission(accessPolicy, "UPrrrra");
     Assert.AreEqual(accessPolicy.Permissions, SharedAccessQueuePermissions.Add
         | SharedAccessQueuePermissions.Read | SharedAccessQueuePermissions.Update | SharedAccessQueuePermissions.ProcessMessages);
     AssertThrows<ArgumentException>(() => command.SetupAccessPolicyPermission(accessPolicy, "rwDl"));
     AssertThrows<ArgumentException>(() => command.SetupAccessPolicyPermission(accessPolicy, "x"));
     AssertThrows<ArgumentException>(() => command.SetupAccessPolicyPermission(accessPolicy, "rwx"));
     AssertThrows<ArgumentException>(() => command.SetupAccessPolicyPermission(accessPolicy, "ABC"));
 }
        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 static string GetAddSasForQueues()
        {
            var cloudQueueClient = StorageAccount.CreateCloudQueueClient();
            var policy = new SharedAccessQueuePolicy()
            {
                Permissions = SharedAccessQueuePermissions.Add | SharedAccessQueuePermissions.Read,
                SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(15)
            };

            var sasToken = cloudQueueClient.GetQueueReference("messagequeue").GetSharedAccessSignature(policy, null);
            return sasToken;
        }
        /// <summary>
        /// Manage stored access policies specified on the queue
        /// </summary>
        /// <param name="cloudQueueClient"></param>
        /// <returns></returns>
        private static async Task QueueAclSample(CloudQueueClient cloudQueueClient)
        {
            // Create the queue name -- use a guid in the name so it's unique.
            string queueName = "demotest-" + Guid.NewGuid();

            // Create the queue with this name.
            Console.WriteLine("Creating queue with name {0}", queueName);
            CloudQueue queue = cloudQueueClient.GetQueueReference(queueName);
            try
            {
                await queue.CreateIfNotExistsAsync();
                Console.WriteLine("    Queue created successfully.");
            }
            catch (StorageException exStorage)
            {
                Common.WriteException(exStorage);
                Console.WriteLine(
                    "Please make sure your storage account is specified correctly in the app.config - then restart the sample.");
                Console.WriteLine("Press any key to exit");
                Console.ReadLine();
                throw;
            }
            catch (Exception ex)
            {
                Console.WriteLine("    Exception thrown creating queue.");
                Common.WriteException(ex);
                throw;
            }

            // Set queue permissions
            SharedAccessQueuePolicy accessQueuePolicy = new SharedAccessQueuePolicy();
            accessQueuePolicy.SharedAccessStartTime = new DateTimeOffset(DateTime.Now);
            accessQueuePolicy.SharedAccessExpiryTime = new DateTimeOffset(DateTime.Now.AddMinutes(10));
            accessQueuePolicy.Permissions = SharedAccessQueuePermissions.Update;
            QueuePermissions permissions = new QueuePermissions();
            permissions.SharedAccessPolicies.Add("key1", accessQueuePolicy);
            Console.WriteLine("Set queue permissions");
            await queue.SetPermissionsAsync(permissions);

            // Get queue permissions
            Console.WriteLine("Get queue permissions:");
            permissions = await queue.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);
            }

            // Delete queue
            Console.WriteLine("Deleting queue with name {0}", queueName);
            queue.DeleteIfExists();
        }
        public void CloudQueueSASSharedProtocolsQueryParam()
        {
            CloudQueueClient client = GenerateCloudQueueClient();
            CloudQueue queue = client.GetQueueReference(GenerateNewQueueName());
            try
            {
                queue.Create();
                SharedAccessQueuePolicy policy = new SharedAccessQueuePolicy()
                {
                    Permissions = SharedAccessQueuePermissions.Read,
                    SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5),
                    SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                };

                string sampleMessageContent = "sample content";
                CloudQueueMessage message = new CloudQueueMessage(sampleMessageContent);
                queue.AddMessage(message);

                foreach (SharedAccessProtocol? protocol in new SharedAccessProtocol?[] { null, SharedAccessProtocol.HttpsOrHttp, SharedAccessProtocol.HttpsOnly })
                {
                    string queueToken = queue.GetSharedAccessSignature(policy, null, protocol, null);
                    StorageCredentials queueSAS = new StorageCredentials(queueToken);
                    Uri queueSASUri = new Uri(queue.Uri + queueSAS.SASToken);
                    StorageUri queueSASStorageUri = new StorageUri(new Uri(queue.StorageUri.PrimaryUri + queueSAS.SASToken), new Uri(queue.StorageUri.SecondaryUri + queueSAS.SASToken));

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

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

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

                    CloudQueue queueWithSAS;
                    CloudQueueMessage resultMessage;

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

                        if (protocol.HasValue && protocol == SharedAccessProtocol.HttpsOnly && string.CompareOrdinal(item.scheme, Uri.UriSchemeHttp) == 0)
                        {
                            queueWithSAS = new CloudQueue(queueSASUri);
                            TestHelper.ExpectedException(() => queueWithSAS.PeekMessage(), "Access a queue using SAS with a shared protocols that does not match", HttpStatusCode.Unused);

                            queueWithSAS = new CloudQueue(queueSASStorageUri, null);
                            TestHelper.ExpectedException(() => queueWithSAS.PeekMessage(), "Access a queue using SAS with a shared protocols that does not match", HttpStatusCode.Unused);
                        }
                        else
                        {
                            queueWithSAS = new CloudQueue(queueSASUri);
                            resultMessage = queueWithSAS.PeekMessage();
                            Assert.AreEqual(sampleMessageContent, resultMessage.AsString);

                            queueWithSAS = new CloudQueue(queueSASStorageUri, null);
                            resultMessage = queueWithSAS.PeekMessage();
                            Assert.AreEqual(sampleMessageContent, resultMessage.AsString);
                        }
                    }
                }
            }
            finally
            {
                queue.DeleteIfExists();
            }
        }
Esempio n. 7
0
 public string GetSharedAccessSignature(SharedAccessQueuePolicy policy)
 {
     return _cloudQueue.GetSharedAccessSignature(policy);
 }
Esempio n. 8
0
 public string GetSharedAccessSignature(SharedAccessQueuePolicy policy, string accessPolicyIdentifier, SharedAccessProtocol?protocols, IPAddressOrRange ipAddressOrRange)
 {
     throw new System.NotImplementedException();
 }
        /// <summary>
        /// Generates the queue SAS URL.
        /// </summary>
        /// <param name="storageAccount">The storage account.</param>
        /// <param name="dto">The data transfer object.</param>
        private static void GenerateQueueSasUrl(CloudStorageAccount storageAccount, DataDto dto)
        {
            CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();

            // Retrieve a reference to a queue
            CloudQueue queue = queueClient.GetQueueReference("dataqueue");

            // Create the queue if it doesn't already exist
            // TODO: Avoid the next line of code in productive systems, since it makes call to azure queue storage.
            // It's better to make sure the queue always exists from the beginning.
            queue.CreateIfNotExists();

            var accessQueuePolicy = new SharedAccessQueuePolicy();
            accessQueuePolicy.SharedAccessExpiryTime = DateTime.UtcNow.AddHours(1);
            accessQueuePolicy.Permissions = SharedAccessQueuePermissions.Add;

            // Generate the SAS token. No access policy identifier is used which makes it non revocable.
            // The token is generated without issuing any calls against the Windows Azure Storage.
            string sasToken = queue.GetSharedAccessSignature(accessQueuePolicy, null);

            dto.QueueUrl = queue.Uri;
            dto.QueueSasToken = sasToken;
        }
        internal static string GetHash(
            SharedAccessQueuePolicy policy,
            string accessPolicyIdentifier,
            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 = SharedAccessQueuePolicy.PermissionsToString(policy.Permissions);
                startTime = policy.SharedAccessStartTime;
                expiryTime = policy.SharedAccessExpiryTime;
            }

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

            string stringToSign = string.Format(
                                     CultureInfo.InvariantCulture,
                                     "{0}\n{1}\n{2}\n{3}\n{4}\n{5}",
                                     permissions,
                                     GetDateTimeOrEmpty(startTime),
                                     GetDateTimeOrEmpty(expiryTime),
                                     resourceName,
                                     accessPolicyIdentifier,
                                     sasVersion);

            return CryptoUtility.ComputeHmac256(keyValue, stringToSign);
        }
 /// <summary>
 /// Set up access policy permission
 /// </summary>
 /// <param name="policy">SharedAccessBlobPolicy object</param>
 /// <param name="permission">Permisson</param>
 internal void SetupAccessPolicyPermission(SharedAccessQueuePolicy policy, string permission)
 {
     if (string.IsNullOrEmpty(permission)) return;
     policy.Permissions = SharedAccessQueuePermissions.None;
     permission = permission.ToLower();
     foreach (char op in permission)
     {
         switch(op)
         {
             case StorageNouns.Permission.Read:
                 policy.Permissions |= SharedAccessQueuePermissions.Read;
                 break;
             case StorageNouns.Permission.Add:
                 policy.Permissions |= SharedAccessQueuePermissions.Add;
                 break;
             case StorageNouns.Permission.Update:
                 policy.Permissions |= SharedAccessQueuePermissions.Update;
                 break;
             case StorageNouns.Permission.Process:
                 policy.Permissions |= SharedAccessQueuePermissions.ProcessMessages;
                 break;
             default:
                 throw new ArgumentException(string.Format(Resources.InvalidAccessPermission, op));
         }
     }
 }
 /// <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="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(
     SharedAccessQueuePolicy policy,
     string accessPolicyIdentifier,
     string resourceName,
     byte[] keyValue)
 {
     if (policy == null)
     {
         return GetSharedAccessSignatureHashImpl(
             null /*SharedAccessQueuePolicy.Permissions */,
             null /*policy.SharedAccessStartTime*/,
             null /*policy.SharedAccessExpiryTime*/,
             null /* startPartitionKey (table only) */,
             null /* startRowKey (table only) */,
             null /* endPartitionKey (table only) */,
             null /* endRowKey (table only) */,
             false /* not using table SAS */,
             accessPolicyIdentifier,
             resourceName,
             keyValue);
     }
     else
     {
         return GetSharedAccessSignatureHashImpl(
             SharedAccessQueuePolicy.PermissionsToString(policy.Permissions),
             policy.SharedAccessStartTime,
             policy.SharedAccessExpiryTime,
             null /* startPartitionKey (table only) */,
             null /* startRowKey (table only) */,
             null /* endPartitionKey (table only) */,
             null /* endRowKey (table only) */,
             false /* not using table SAS */,
             accessPolicyIdentifier,
             resourceName,
             keyValue);
     }
 }
        /// <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="accessPolicyIdentifier">An optional identifier for the policy.</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(
            SharedAccessQueuePolicy policy,
            string accessPolicyIdentifier,
            string signature,
            string accountKeyName)
        {
            CommonUtility.AssertNotNull("signature", signature);

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

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

            return GetSharedAccessSignatureImpl(
                permissions,
                policy.SharedAccessStartTime,
                policy.SharedAccessExpiryTime,
                null /* startPartitionKey (table only) */,
                null /* startRowKey (table only) */,
                null /* endPartitionKey (table only) */,
                null /* endRowKey (table only) */,
                accessPolicyIdentifier,
                null /* resourceType (blob only) */,
                null /* tableName (table only) */,
                signature,
                accountKeyName);
        }
        public void CloudQueueSASWithAbsoluteUri()
        {
            CloudQueueClient queueClient = GenerateCloudQueueClient();

            CloudQueue queue = queueClient.GetQueueReference(queueClient.BaseUri + GenerateNewQueueName());
            try
            {
                queue.CreateIfNotExists();

                SharedAccessQueuePolicy policy = new SharedAccessQueuePolicy()
                {
                    Permissions = SharedAccessQueuePermissions.Read,
                    SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5),
                    SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(10)
                };

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

                CloudQueue sasQueue = new CloudQueue(queue.Uri, creds);
                sasQueue.PeekMessage();
            }
            finally
            {
                queue.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 SharedAccessQueuePolicy GetQueueSasConstraints(ResourcePermissions permissions, DateTime? expiration)
        {
            SharedAccessQueuePolicy sasConstraints = new SharedAccessQueuePolicy();

            // 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 = SharedAccessQueuePermissions.None;
            if ((permissions & ResourcePermissions.Read) == ResourcePermissions.Read)
            {
                sasConstraints.Permissions |= SharedAccessQueuePermissions.Read;
            }

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

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

            if ((permissions & ResourcePermissions.Process) == ResourcePermissions.Process)
            {
                sasConstraints.Permissions |= SharedAccessQueuePermissions.ProcessMessages;
            }

            return sasConstraints;
        }
Esempio n. 16
0
		static string RequestSasToken(CloudQueue queue)
		{
			// 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.
			SharedAccessQueuePolicy policy = new SharedAccessQueuePolicy()
			{
				SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-15),
				SharedAccessExpiryTime = DateTime.UtcNow.AddDays(1.0),
				Permissions = SharedAccessQueuePermissions.Add |
					SharedAccessQueuePermissions.Read |
					SharedAccessQueuePermissions.Update |
					SharedAccessQueuePermissions.ProcessMessages
			};

			// 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 = queue.GetSharedAccessSignature(policy);

			return sasToken;
		}
Esempio n. 17
0
        public string GetSharedAccessSignature(SharedAccessQueuePolicy policy)
        {
            if (policy == null)
            {
                throw new ArgumentNullException("policy");
            }

            return string.Format(
                CultureInfo.InvariantCulture,
                "?sv={0:yyyy-MM-dd}&sr=c&sig=s&sp={1}",
                DateTime.Today,
                policy.Permissions.DeterminePermissionsString());
        }
Esempio n. 18
0
        /// <summary>
        /// Returns a shared access signature for the queue.
        /// </summary>
        /// <param name="policy">The access policy for the shared access signature.</param>
        /// <param name="accessPolicyIdentifier">A queue-level access policy.</param>
        /// <returns>A shared access signature.</returns>
        public string GetSharedAccessSignature(SharedAccessQueuePolicy policy, string accessPolicyIdentifier)
        {
            if (!this.ServiceClient.Credentials.IsSharedKey)
            {
                string errorMessage = string.Format(CultureInfo.CurrentCulture, SR.CannotCreateSASWithoutAccountKey);
                throw new InvalidOperationException(errorMessage);
            }

            string resourceName = this.GetCanonicalName();

            string signature = SharedAccessSignatureHelper.GetSharedAccessSignatureHashImpl(
                policy,
                accessPolicyIdentifier,
                resourceName,
                this.ServiceClient.Credentials);

            string accountKeyName = this.ServiceClient.Credentials.IsSharedKey ? this.ServiceClient.Credentials.KeyName : null;

            UriQueryBuilder builder = SharedAccessSignatureHelper.GetSharedAccessSignatureImpl(
                 policy,
                accessPolicyIdentifier,
                signature,
                accountKeyName);

            return builder.ToString();
        }
 /// <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(SharedAccessQueuePolicy 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);
 }
Esempio n. 20
0
 /// <summary>
 /// Returns a shared access signature for the queue.
 /// </summary>
 /// <param name="policy">A <see cref="SharedAccessQueuePolicy"/> object specifying the access policy for the shared access signature.</param>
 /// <returns>A shared access signature, as a URI query string.</returns>
 /// <remarks>The query string returned includes the leading question mark.</remarks>
 public string GetSharedAccessSignature(SharedAccessQueuePolicy policy)
 {
     return(this.GetSharedAccessSignature(policy, null /* accessPolicyIdentifier */));
 }
        public override void ExecuteCmdlet()
        {
            if (String.IsNullOrEmpty(Name)) return;
            CloudQueue queue = Channel.GetQueueReference(Name);
            SharedAccessQueuePolicy policy = new SharedAccessQueuePolicy();
            bool shouldSetExpiryTime = SasTokenHelper.ValidateQueueAccessPolicy(Channel, queue.Name, policy, accessPolicyIdentifier);
            SetupAccessPolicy(policy, shouldSetExpiryTime);
            string sasToken = queue.GetSharedAccessSignature(policy, accessPolicyIdentifier);

            if (FullUri)
            {
                string fullUri = queue.Uri.ToString() + sasToken;
                WriteObject(fullUri);
            }
            else
            {
                WriteObject(sasToken);
            }
        }
Esempio n. 22
0
 /// <summary>
 /// Returns a shared access signature for the queue.
 /// </summary>
 /// <param name="policy">A <see cref="SharedAccessQueuePolicy"/> 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>
 public string GetSharedAccessSignature(SharedAccessQueuePolicy policy, string accessPolicyIdentifier)
 {
     return(this.GetSharedAccessSignature(policy, accessPolicyIdentifier, null, null));
 }
        /// <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="accessPolicyIdentifier">An optional identifier for the policy.</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(
            SharedAccessQueuePolicy policy,
            string accessPolicyIdentifier,
            string signature,
            string accountKeyName,
            string sasVersion)
        {
            CommonUtility.AssertNotNull("signature", signature);

            UriQueryBuilder builder = new UriQueryBuilder();

            AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedVersion, sasVersion);
            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 = SharedAccessQueuePolicy.PermissionsToString(policy.Permissions);
                if (!string.IsNullOrEmpty(permissions))
                {
                    AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedPermissions, permissions);
                }
            }

            return builder;
        }
        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 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="resourceName">The canonical resource string, unescaped.</param>
        /// <param name="sasVersion">A string indicating the desired SAS version to use, in storage service version format.</param>
        /// <param name="protocols">The HTTP/HTTPS protocols for Account SAS.</param>
        /// <param name="ipAddressOrRange">The IP range for IPSAS.</param>
        /// <param name="keyValue">The key value retrieved as an atomic operation used for signing.</param>
        /// <returns>The signed hash.</returns>
        internal static string GetHash(
            SharedAccessQueuePolicy policy,
            string accessPolicyIdentifier,
            string resourceName,
            string sasVersion,
            SharedAccessProtocol? protocols,
            IPAddressOrRange ipAddressOrRange,
            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 = SharedAccessQueuePolicy.PermissionsToString(policy.Permissions);
                startTime = policy.SharedAccessStartTime;
                expiryTime = policy.SharedAccessExpiryTime;
            }

            //// StringToSign =      signedpermissions + "\n" +
            ////                     signedstart + "\n" +
            ////                     signedexpiry + "\n" +
            ////                     canonicalizedresource + "\n" +
            ////                     signedidentifier + "\n" +
            ////                     signedIP + "\n" + 
            ////                     signedProtocol + "\n" + 
            ////                     signedversion
            ////
            //// 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}",
                                     permissions,
                                     GetDateTimeOrEmpty(startTime),
                                     GetDateTimeOrEmpty(expiryTime),
                                     resourceName,
                                     accessPolicyIdentifier,
                                     ipAddressOrRange == null ? string.Empty : ipAddressOrRange.ToString(),
                                     GetProtocolString(protocols),
                                     sasVersion);

            Logger.LogVerbose(null /* operationContext */, SR.TraceStringToSign, stringToSign);

            return CryptoUtility.ComputeHmac256(keyValue, stringToSign);
        }
Esempio n. 26
0
 public string GetSharedAccessSignature(SharedAccessQueuePolicy policy, string accessPolicyIdentifier)
 {
     throw new System.NotImplementedException();
 }
        /// <summary>
        /// Returns a shared access signature for the queue.
        /// </summary>
        /// <param name="policy">A <see cref="SharedAccessQueuePolicy"/> object specifying the access policy for the shared access signature.</param>
        /// <param name="accessPolicyIdentifier">A string identifying a stored access policy.</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>
        public string GetSharedAccessSignature(SharedAccessQueuePolicy policy, string accessPolicyIdentifier, 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;

            string signature = SharedAccessSignatureHelper.GetHash(
                policy,
                accessPolicyIdentifier,
                resourceName,
                Constants.HeaderConstants.TargetStorageVersion,
                protocols,
                ipAddressOrRange,
                accountKey.KeyValue);

            string accountKeyName = accountKey.KeyName;

            UriQueryBuilder builder = SharedAccessSignatureHelper.GetSignature(
                policy,
                accessPolicyIdentifier,
                signature,
                accountKeyName,
                Constants.HeaderConstants.TargetStorageVersion,
                protocols,
                ipAddressOrRange);

            return builder.ToString();
        }
        /// <summary>
        /// Helper function for testing the IPAddressOrRange funcitonality for queues
        /// </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 CloudQueueSASIPAddressHelper(Func<IPAddressOrRange> generateInitialIPAddressOrRange, Func<IPAddress, IPAddressOrRange> generateFinalIPAddressOrRange)
        {
            CloudQueueClient client = GenerateCloudQueueClient();
            CloudQueue queue = client.GetQueueReference(GenerateNewQueueName());

            try
            {
                queue.Create();
                SharedAccessQueuePolicy policy = new SharedAccessQueuePolicy()
                {
                    Permissions = SharedAccessQueuePermissions.Read,
                    SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5),
                    SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                };

                string sampleMessageContent = "sample content";
                CloudQueueMessage message = new CloudQueueMessage(sampleMessageContent);
                queue.AddMessage(message);

                // 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 queueToken = queue.GetSharedAccessSignature(policy, null, null, ipAddressOrRange);
                StorageCredentials queueSAS = new StorageCredentials(queueToken);
                Uri queueSASUri = queueSAS.TransformUri(queue.Uri);
                StorageUri queueSASStorageUri = queueSAS.TransformUri(queue.StorageUri);

                CloudQueue queueWithSAS = new CloudQueue(queueSASUri);
                OperationContext opContext = new OperationContext();
                IPAddress actualIP = null;
                opContext.ResponseReceived += (sender, e) =>
                {
                    Stream stream = e.Response.GetResponseStream();
                    stream.Seek(0, SeekOrigin.Begin);
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        string text = reader.ReadToEnd();
                        XDocument xdocument = XDocument.Parse(text);
                        actualIP = IPAddress.Parse(xdocument.Descendants("SourceIP").First().Value);
                    }
                };

                bool exceptionThrown = false;
                CloudQueueMessage resultMessage;
                try
                {
                    resultMessage = queueWithSAS.PeekMessage(null, opContext);
                }
                catch (StorageException)
                {
                    exceptionThrown = true;
                    Assert.IsNotNull(actualIP);
                }

                Assert.IsTrue(exceptionThrown);
                ipAddressOrRange = generateFinalIPAddressOrRange(actualIP);
                queueToken = queue.GetSharedAccessSignature(policy, null, null, ipAddressOrRange);
                queueSAS = new StorageCredentials(queueToken);
                queueSASUri = queueSAS.TransformUri(queue.Uri);
                queueSASStorageUri = queueSAS.TransformUri(queue.StorageUri);

                queueWithSAS = new CloudQueue(queueSASUri);
                resultMessage = queue.PeekMessage();
                Assert.AreEqual(sampleMessageContent, resultMessage.AsString);
                Assert.IsTrue(queueWithSAS.StorageUri.PrimaryUri.Equals(queue.Uri));
                Assert.IsNull(queueWithSAS.StorageUri.SecondaryUri);

                queueWithSAS = new CloudQueue(queueSASStorageUri, null);
                resultMessage = queue.PeekMessage();
                Assert.AreEqual(sampleMessageContent, resultMessage.AsString);
                Assert.IsTrue(queueWithSAS.StorageUri.Equals(queue.StorageUri));

            }
            finally
            {
                queue.DeleteIfExists();
            }
        }
 /// <summary>
 /// Returns a shared access signature for the queue.
 /// </summary>
 /// <param name="policy">A <see cref="SharedAccessQueuePolicy"/> 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>
 public string GetSharedAccessSignature(SharedAccessQueuePolicy policy, string accessPolicyIdentifier)
 {
     return this.GetSharedAccessSignature(policy, accessPolicyIdentifier, null, null);
 }
        /// <summary>
        /// Returns a shared access signature for the queue.
        /// </summary>
        /// <param name="policy">A <see cref="SharedAccessQueuePolicy"/> object specifying the access policy for the shared access signature.</param>
        /// <param name="accessPolicyIdentifier">A string identifying a stored access policy.</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>
        public string GetSharedAccessSignature(SharedAccessQueuePolicy policy, string accessPolicyIdentifier, 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,
                resourceName,
                validatedSASVersion,
                accountKey.KeyValue);

            string accountKeyName = accountKey.KeyName;

            UriQueryBuilder builder = SharedAccessSignatureHelper.GetSignature(
                policy,
                accessPolicyIdentifier,
                signature,
                accountKeyName,
                validatedSASVersion);

            return builder.ToString();
        }
 /// <summary>
 /// Returns a shared access signature for the queue.
 /// </summary>
 /// <param name="policy">A <see cref="SharedAccessQueuePolicy"/> object specifying the access policy for the shared access signature.</param>
 /// <returns>A shared access signature, as a URI query string.</returns>
 /// <remarks>The query string returned includes the leading question mark.</remarks>
 public string GetSharedAccessSignature(SharedAccessQueuePolicy policy)
 {
     return this.GetSharedAccessSignature(policy, null /* accessPolicyIdentifier */);
 }
Esempio n. 32
-1
        public async Task UpdateQueueSASTestAsync()
        {
            CloudQueueClient client = GenerateCloudQueueClient();
            CloudQueue queue = client.GetQueueReference(GenerateNewQueueName());

            try
            {
                await queue.CreateAsync();
                string messageContent = Guid.NewGuid().ToString();
                CloudQueueMessage message = new CloudQueueMessage(messageContent);
                await queue.AddMessageAsync(message);
                SharedAccessQueuePolicy policy = new SharedAccessQueuePolicy()
                {
                    SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5),
                    SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                    Permissions = SharedAccessQueuePermissions.Add | SharedAccessQueuePermissions.ProcessMessages,
                };
                string id = Guid.NewGuid().ToString();
                string sasToken = queue.GetSharedAccessSignature(policy, null);

                StorageCredentials sasCreds = new StorageCredentials(sasToken);
                CloudQueue sasQueue = new CloudQueue(queue.Uri, sasCreds);
                OperationContext context = new OperationContext();

                await TestHelper.ExpectedExceptionAsync(
                    async () => await sasQueue.PeekMessageAsync(null, context),
                    context,
                    "Peek when Sas does not allow Read access on the queue",
                    HttpStatusCode.Forbidden);

                await sasQueue.AddMessageAsync(message);

                SharedAccessQueuePolicy policy2 = new SharedAccessQueuePolicy()
                {
                    SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5),
                    SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                    Permissions = SharedAccessQueuePermissions.Add | SharedAccessQueuePermissions.ProcessMessages | SharedAccessQueuePermissions.Read,
                };

                string sasToken2 = queue.GetSharedAccessSignature(policy2, null);
                sasCreds.UpdateSASToken(sasToken2);
                sasQueue = new CloudQueue(queue.Uri, sasCreds);

                await sasQueue.PeekMessageAsync();
            }
            finally
            {
                queue.DeleteIfExistsAsync().AsTask().Wait();
            }
        }