Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 101 additions & 0 deletions src/corelib/Providers/Rackspace/CloudFilesProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -1564,6 +1565,95 @@ public void UpdateAccountMetadata(Dictionary<string, string> metadata, string re
ExecuteRESTRequest(identity, urlPath, HttpMethod.POST, headers: headers);
}

/// <summary>
/// Construct a <see cref="Uri"/> which allows public access to an object hosted in Cloud Files.
/// </summary>
/// <param name="method">The HTTP method that will be used to access the object. This is typically <see cref="HttpMethod.GET"/> or <see cref="HttpMethod.PUT"/>.</param>
/// <param name="container">The container name.</param>
/// <param name="objectName">The object name. Example <localUri>image_name.jpeg</localUri></param>
/// <param name="key">The account key to use with the TempURL feature, as specified in the account <see cref="TempUrlKey"/> metadata.</param>
/// <param name="expiration">The expiration time for the generated URI.</param>
/// <param name="region">The region in which to access the object. If not specified, the user's default region will be used.</param>
/// <param name="useInternalUrl"><see langword="true"/> to use the endpoint's <see cref="Endpoint.InternalURL"/>; otherwise <see langword="false"/> to use the endpoint's <see cref="Endpoint.PublicURL"/>.</param>
/// <param name="identity">The cloud identity to use for this request. If not specified, the default identity for the current provider instance will be used.</param>
/// <returns>An absolute <see cref="Uri"/> which allows unauthenticated (public) access to the specified object until the <paramref name="expiration"/> time passes or the account key is changed.</returns>
/// <exception cref="ArgumentNullException">
/// If <paramref name="container"/> is <see langword="null"/>.
/// <para>-or-</para>
/// <para>If <paramref name="objectName"/> is <see langword="null"/>.</para>
/// <para>-or-</para>
/// <para>If <paramref name="key"/> is <see langword="null"/>.</para>
/// </exception>
/// <exception cref="ArgumentException">
/// If <paramref name="container"/> is empty.
/// <para>-or-</para>
/// <para>If <paramref name="objectName"/> is empty.</para>
/// <para>-or-</para>
/// <para>If <paramref name="key"/> is empty.</para>
/// </exception>
/// <exception cref="ContainerNameException">If <paramref name="container"/> is not a valid container name.</exception>
/// <exception cref="ObjectNameException">If <paramref name="objectName"/> is not a valid object name.</exception>
/// <exception cref="NotSupportedException">
/// If the provider does not support the given <paramref name="identity"/> type.
/// <para>-or-</para>
/// <para>The specified <paramref name="region"/> is not supported.</para>
/// </exception>
/// <exception cref="InvalidOperationException">
/// If <paramref name="identity"/> is <see langword="null"/> and no default identity is available for the provider.
/// <para>-or-</para>
/// <para>If <paramref name="region"/> is <see langword="null"/> and no default region is available for the provider.</para>
/// </exception>
/// <exception cref="ResponseException">If the REST API request failed.</exception>
/// <seealso cref="TempUrlKey"/>
/// <seealso href="http://docs.openstack.org/api/openstack-object-storage/1.0/content/tempurl.html">Temporary URL middleware (OpenStack Object Storage API v1 Reference)</seealso>
/// <seealso href="http://docs.rackspace.com/files/api/v1/cf-devguide/content/Create_TempURL-d1a444.html">Create the TempURL (Rackspace Cloud Files Developer Guide - API v1)</seealso>
/// <preliminary/>
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<string, string> parameters = new Dictionary<string, string>()
{
{ "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)
Expand Down Expand Up @@ -1914,6 +2004,17 @@ protected void VerifyContainerIsCDNEnabled(string container, string region, Clou
/// <seealso href="http://docs.rackspace.com/files/api/v1/cf-devguide/content/GET_listcontainers_v1__account__accountServicesOperations_d1e000.html">Show Account Details and List Containers (Rackspace Cloud Files Developer Guide - API v1)</seealso>
public const string AccountObjectCount = "x-account-object-count";

/// <summary>
/// The <strong>Temp-Url-Key</strong> account metadata key for use with <see cref="CreateTemporaryPublicUri"/>.
/// </summary>
/// <remarks>
/// This account metadata value is passed as the <em>key</em> parameter to <see cref="CreateTemporaryPublicUri"/>.
/// </remarks>
/// <seealso cref="GetAccountMetaData"/>
/// <seealso cref="UpdateAccountMetadata"/>
/// <seealso href="http://docs.rackspace.com/files/api/v1/cf-devguide/content/Set_Account_Metadata-d1a4460.html">Set Account TempURL Metadata Key (Rackspace Cloud Files Developer Guide - API v1)</seealso>
public const string TempUrlKey = "Temp-Url-Key";

#endregion

#region Container Constants
Expand Down
138 changes: 138 additions & 0 deletions src/testing/integration/Providers/Rackspace/UserObjectStorageTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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<string, string> accountMetadata = provider.GetAccountMetaData();
string tempUrlKey;
if (!accountMetadata.TryGetValue(CloudFilesProvider.TempUrlKey, out tempUrlKey))
{
tempUrlKey = Guid.NewGuid().ToString("N");
accountMetadata = new Dictionary<string, string>(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<string, string> accountMetadata = provider.GetAccountMetaData();
string tempUrlKey;
if (!accountMetadata.TryGetValue(CloudFilesProvider.TempUrlKey, out tempUrlKey))
{
tempUrlKey = Guid.NewGuid().ToString("N");
accountMetadata = new Dictionary<string, string>(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<string, string> accountMetadata = provider.GetAccountMetaData();
string tempUrlKey;
if (!accountMetadata.TryGetValue(CloudFilesProvider.TempUrlKey, out tempUrlKey))
{
tempUrlKey = Guid.NewGuid().ToString("N");
accountMetadata = new Dictionary<string, string>(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<Container> ListAllContainers(IObjectStorageProvider provider, int? blockSize = null, string region = null, bool useInternalUrl = false, CloudIdentity identity = null)
{
if (blockSize <= 0)
Expand Down