From 5f3dbbd2cf27ee66370b248e85b5b65eb64392a1 Mon Sep 17 00:00:00 2001 From: Sam Harwell Date: Wed, 9 Apr 2014 10:06:45 -0500 Subject: [PATCH] Implement preliminary support for the TempURL feature (fixes #337) --- .../Providers/Rackspace/CloudFilesProvider.cs | 101 +++++++++++++ .../Rackspace/UserObjectStorageTests.cs | 138 ++++++++++++++++++ 2 files changed, 239 insertions(+) diff --git a/src/corelib/Providers/Rackspace/CloudFilesProvider.cs b/src/corelib/Providers/Rackspace/CloudFilesProvider.cs index 66bbc8cd0..58b899830 100644 --- a/src/corelib/Providers/Rackspace/CloudFilesProvider.cs +++ b/src/corelib/Providers/Rackspace/CloudFilesProvider.cs @@ -18,6 +18,7 @@ using net.openstack.Providers.Rackspace.Exceptions; using net.openstack.Providers.Rackspace.Objects; using net.openstack.Providers.Rackspace.Objects.Mapping; +using net.openstack.Providers.Rackspace.Objects.Monitoring; using net.openstack.Providers.Rackspace.Objects.Response; using net.openstack.Providers.Rackspace.Validators; using Newtonsoft.Json; @@ -1564,6 +1565,95 @@ public void UpdateAccountMetadata(Dictionary metadata, string re ExecuteRESTRequest(identity, urlPath, HttpMethod.POST, headers: headers); } + /// + /// Construct a which allows public access to an object hosted in Cloud Files. + /// + /// The HTTP method that will be used to access the object. This is typically or . + /// The container name. + /// The object name. Example image_name.jpeg + /// The account key to use with the TempURL feature, as specified in the account metadata. + /// The expiration time for the generated URI. + /// The region in which to access the object. If not specified, the user's default region will be used. + /// to use the endpoint's ; otherwise to use the endpoint's . + /// The cloud identity to use for this request. If not specified, the default identity for the current provider instance will be used. + /// An absolute which allows unauthenticated (public) access to the specified object until the time passes or the account key is changed. + /// + /// If is . + /// -or- + /// If is . + /// -or- + /// If is . + /// + /// + /// If is empty. + /// -or- + /// If is empty. + /// -or- + /// If is empty. + /// + /// If is not a valid container name. + /// If is not a valid object name. + /// + /// If the provider does not support the given type. + /// -or- + /// The specified is not supported. + /// + /// + /// If is and no default identity is available for the provider. + /// -or- + /// If is and no default region is available for the provider. + /// + /// If the REST API request failed. + /// + /// Temporary URL middleware (OpenStack Object Storage API v1 Reference) + /// Create the TempURL (Rackspace Cloud Files Developer Guide - API v1) + /// + public Uri CreateTemporaryPublicUri(HttpMethod method, string container, string objectName, string key, DateTimeOffset expiration, string region = null, bool useInternalUrl = false, CloudIdentity identity = null) + { + if (container == null) + throw new ArgumentNullException("container"); + if (objectName == null) + throw new ArgumentNullException("objectName"); + if (key == null) + throw new ArgumentNullException("key"); + if (string.IsNullOrEmpty(container)) + throw new ArgumentException("container cannot be empty"); + if (string.IsNullOrEmpty(objectName)) + throw new ArgumentException("objectName cannot be empty"); + if (string.IsNullOrEmpty(key)) + throw new ArgumentException("key cannot be empty"); + CheckIdentity(identity); + + _cloudFilesValidator.ValidateContainerName(container); + _cloudFilesValidator.ValidateObjectName(objectName); + + Uri baseAddress = new Uri(GetServiceEndpointCloudFiles(identity, region, useInternalUrl), UriKind.Absolute); + + StringBuilder body = new StringBuilder(); + body.Append(method.ToString().ToUpperInvariant()).Append('\n'); + body.Append(expiration.ToTimestamp() / 1000).Append('\n'); + body.Append(baseAddress.PathAndQuery).Append('/').Append(container).Append('/').Append(objectName); + + using (HMAC hmac = HMAC.Create()) + { + hmac.HashName = "SHA1"; + hmac.Key = Encoding.UTF8.GetBytes(key); + byte[] hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(body.ToString())); + string sig = string.Join(string.Empty, Array.ConvertAll(hash, i => i.ToString("x2"))); + + UriTemplate uriTemplate = new UriTemplate("{container}/{objectName}?temp_url_sig={sig}&temp_url_expires={expires}"); + Dictionary parameters = new Dictionary() + { + { "container", container }, + { "objectName", objectName }, + { "sig", sig }, + { "expires", (expiration.ToTimestamp() / 1000).ToString() }, + }; + + return uriTemplate.BindByName(baseAddress, parameters); + } + } + private static string EncodeUnicodeValue(string value) { if (value == null) @@ -1914,6 +2004,17 @@ protected void VerifyContainerIsCDNEnabled(string container, string region, Clou /// Show Account Details and List Containers (Rackspace Cloud Files Developer Guide - API v1) public const string AccountObjectCount = "x-account-object-count"; + /// + /// The Temp-Url-Key account metadata key for use with . + /// + /// + /// This account metadata value is passed as the key parameter to . + /// + /// + /// + /// Set Account TempURL Metadata Key (Rackspace Cloud Files Developer Guide - API v1) + public const string TempUrlKey = "Temp-Url-Key"; + #endregion #region Container Constants diff --git a/src/testing/integration/Providers/Rackspace/UserObjectStorageTests.cs b/src/testing/integration/Providers/Rackspace/UserObjectStorageTests.cs index 55d2baa3c..778386629 100644 --- a/src/testing/integration/Providers/Rackspace/UserObjectStorageTests.cs +++ b/src/testing/integration/Providers/Rackspace/UserObjectStorageTests.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; using System.Linq; + using System.Net; using System.Text; using ICSharpCode.SharpZipLib.BZip2; using ICSharpCode.SharpZipLib.GZip; @@ -20,6 +21,7 @@ using Container = net.openstack.Core.Domain.Container; using File = System.IO.File; using FileInfo = System.IO.FileInfo; + using HttpMethod = JSIStudios.SimpleRESTServices.Client.HttpMethod; using HttpWebRequest = System.Net.HttpWebRequest; using MD5 = System.Security.Cryptography.MD5; using MemoryStream = System.IO.MemoryStream; @@ -780,6 +782,142 @@ public void TestStaticWebOnContainer() provider.DeleteContainer(containerName, deleteObjects: true); } + [TestMethod] + [TestCategory(TestCategories.User)] + [TestCategory(TestCategories.ObjectStorage)] + public void TestTempUrlValid() + { + IObjectStorageProvider provider = Bootstrapper.CreateObjectStorageProvider(); + Assert.IsInstanceOfType(provider, typeof(CloudFilesProvider), "Temp URLs are a Rackspace-specific extension to the Object Storage service."); + + string containerName = TestContainerPrefix + Path.GetRandomFileName(); + string objectName = Path.GetRandomFileName(); + string fileContents = "File contents!"; + + Dictionary accountMetadata = provider.GetAccountMetaData(); + string tempUrlKey; + if (!accountMetadata.TryGetValue(CloudFilesProvider.TempUrlKey, out tempUrlKey)) + { + tempUrlKey = Guid.NewGuid().ToString("N"); + accountMetadata = new Dictionary(StringComparer.OrdinalIgnoreCase); + accountMetadata[CloudFilesProvider.TempUrlKey] = tempUrlKey; + provider.UpdateAccountMetadata(accountMetadata); + } + + ObjectStore result = provider.CreateContainer(containerName); + Assert.AreEqual(ObjectStore.ContainerCreated, result); + + Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(fileContents)); + provider.CreateObject(containerName, stream, objectName); + + // verify a future time works + DateTimeOffset expirationTime = DateTimeOffset.Now + TimeSpan.FromSeconds(10); + Uri uri = ((CloudFilesProvider)provider).CreateTemporaryPublicUri(HttpMethod.GET, containerName, objectName, tempUrlKey, expirationTime); + WebRequest request = HttpWebRequest.Create(uri); + using (WebResponse response = request.GetResponse()) + { + Stream cdnStream = response.GetResponseStream(); + StreamReader reader = new StreamReader(cdnStream, Encoding.UTF8); + string text = reader.ReadToEnd(); + Assert.AreEqual(fileContents, text); + } + + provider.DeleteContainer(containerName, deleteObjects: true); + } + + [TestMethod] + [TestCategory(TestCategories.User)] + [TestCategory(TestCategories.ObjectStorage)] + public void TestTempUrlExpired() + { + IObjectStorageProvider provider = Bootstrapper.CreateObjectStorageProvider(); + Assert.IsInstanceOfType(provider, typeof(CloudFilesProvider), "Temp URLs are a Rackspace-specific extension to the Object Storage service."); + + string containerName = TestContainerPrefix + Path.GetRandomFileName(); + string objectName = Path.GetRandomFileName(); + string fileContents = "File contents!"; + + Dictionary accountMetadata = provider.GetAccountMetaData(); + string tempUrlKey; + if (!accountMetadata.TryGetValue(CloudFilesProvider.TempUrlKey, out tempUrlKey)) + { + tempUrlKey = Guid.NewGuid().ToString("N"); + accountMetadata = new Dictionary(StringComparer.OrdinalIgnoreCase); + accountMetadata[CloudFilesProvider.TempUrlKey] = tempUrlKey; + provider.UpdateAccountMetadata(accountMetadata); + } + + ObjectStore result = provider.CreateContainer(containerName); + Assert.AreEqual(ObjectStore.ContainerCreated, result); + + Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(fileContents)); + provider.CreateObject(containerName, stream, objectName); + + // verify a past time does not work + try + { + DateTimeOffset expirationTime = DateTimeOffset.Now - TimeSpan.FromSeconds(3); + Uri uri = ((CloudFilesProvider)provider).CreateTemporaryPublicUri(HttpMethod.GET, containerName, objectName, tempUrlKey, expirationTime); + WebRequest request = HttpWebRequest.Create(uri); + using (WebResponse response = request.GetResponse()) + { + Stream cdnStream = response.GetResponseStream(); + StreamReader reader = new StreamReader(cdnStream, Encoding.UTF8); + string text = reader.ReadToEnd(); + Assert.Fail("Expected an exception"); + } + } + catch (WebException ex) + { + Assert.AreEqual(HttpStatusCode.Unauthorized, ((HttpWebResponse)ex.Response).StatusCode); + } + + provider.DeleteContainer(containerName, deleteObjects: true); + } + + [TestMethod] + [TestCategory(TestCategories.User)] + [TestCategory(TestCategories.ObjectStorage)] + public void TestTempUrlWithSpecialCharactersInObjectName() + { + IObjectStorageProvider provider = Bootstrapper.CreateObjectStorageProvider(); + Assert.IsInstanceOfType(provider, typeof(CloudFilesProvider), "Temp URLs are a Rackspace-specific extension to the Object Storage service."); + + string containerName = TestContainerPrefix + Path.GetRandomFileName(); + string objectName = "§ / 你好"; + string fileContents = "File contents!"; + + Dictionary accountMetadata = provider.GetAccountMetaData(); + string tempUrlKey; + if (!accountMetadata.TryGetValue(CloudFilesProvider.TempUrlKey, out tempUrlKey)) + { + tempUrlKey = Guid.NewGuid().ToString("N"); + accountMetadata = new Dictionary(StringComparer.OrdinalIgnoreCase); + accountMetadata[CloudFilesProvider.TempUrlKey] = tempUrlKey; + provider.UpdateAccountMetadata(accountMetadata); + } + + ObjectStore result = provider.CreateContainer(containerName); + Assert.AreEqual(ObjectStore.ContainerCreated, result); + + Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(fileContents)); + provider.CreateObject(containerName, stream, objectName); + + // verify a future time works + DateTimeOffset expirationTime = DateTimeOffset.Now + TimeSpan.FromSeconds(10); + Uri uri = ((CloudFilesProvider)provider).CreateTemporaryPublicUri(HttpMethod.GET, containerName, objectName, tempUrlKey, expirationTime); + WebRequest request = HttpWebRequest.Create(uri); + using (WebResponse response = request.GetResponse()) + { + Stream cdnStream = response.GetResponseStream(); + StreamReader reader = new StreamReader(cdnStream, Encoding.UTF8); + string text = reader.ReadToEnd(); + Assert.AreEqual(fileContents, text); + } + + provider.DeleteContainer(containerName, deleteObjects: true); + } + private static IEnumerable ListAllContainers(IObjectStorageProvider provider, int? blockSize = null, string region = null, bool useInternalUrl = false, CloudIdentity identity = null) { if (blockSize <= 0)