Skip to content

Commit

Permalink
Get/Set/Remove Bucket Policy with Args/Response object
Browse files Browse the repository at this point in the history
  • Loading branch information
BigUstad committed Sep 16, 2020
2 parents 4c30621 + dd1342c commit 7091d65
Show file tree
Hide file tree
Showing 5 changed files with 73 additions and 69 deletions.
24 changes: 14 additions & 10 deletions Docs/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -786,8 +786,8 @@ catch (MinioException e)
```

<a name="getBucketPolicy"></a>
### GetPolicyAsync(string bucketName)
`Task<String> GetPolicyAsync(string bucketName, CancellationToken cancellationToken = default(CancellationToken))`
### GetPolicyAsync(GetPolicyArgs args)
`Task<String> GetPolicyAsync(GetPolicyArgs args, CancellationToken cancellationToken = default(CancellationToken))`

Get bucket policy.

Expand All @@ -796,7 +796,7 @@ __Parameters__

|Param | Type | Description |
|:--- |:--- |:--- |
| ``bucketName`` | _string_ | Name of the bucket. |
| ``args`` | _GetPolicyArgs_ | GetPolicyArgs object encapsulating bucket name. |
| ``cancellationToken``| _System.Threading.CancellationToken_ | Optional parameter. Defaults to default(CancellationToken) |


Expand All @@ -817,8 +817,10 @@ __Example__
```cs
try
{
String policyJson = await minioClient.GetPolicyAsync("myBucket");
Console.WriteLine("Current policy: " + policy.GetType().ToString());
GetPolicyArgs args = new GetPolicyArgs()
.WithBucket("myBucket");
String policyJson = await minioClient.GetPolicyAsync(args);
Console.WriteLine("Current policy: " + policyJson);
}
catch (MinioException e)
{
Expand All @@ -827,17 +829,16 @@ catch (MinioException e)
```

<a name="setBucketPolicy"></a>
### SetPolicyAsync(string bucketName, string policyJson)
`Task SetPolicyAsync(string bucketName, string policyJson, CancellationToken cancellationToken = default(CancellationToken))`
### SetPolicyAsync(SetPolicyArgs args)
`Task SetPolicyAsync(SetPolicyArgs args, CancellationToken cancellationToken = default(CancellationToken))`

Set policy on bucket.

__Parameters__

|Param | Type | Description |
|:--- |:--- |:--- |
| ``bucketName`` | _string_ | Name of the bucket |
| ``policyJson`` | _string_ | Policy as a json string |
| ``args`` | _SetPolicyArgs_ | SetPolicyArgs object encapsulating bucket name, Policy as a json string. |
| ``cancellationToken``| _System.Threading.CancellationToken_ | Optional parameter. Defaults to default(CancellationToken) |


Expand All @@ -858,7 +859,10 @@ __Example__
try
{
string policyJson = $@"{{""Version"":""2012-10-17"",""Statement"":[{{""Action"":[""s3:GetBucketLocation""],""Effect"":""Allow"",""Principal"":{{""AWS"":[""*""]}},""Resource"":[""arn:aws:s3:::{bucketName}""],""Sid"":""""}},{{""Action"":[""s3:ListBucket""],""Condition"":{{""StringEquals"":{{""s3:prefix"":[""foo"",""prefix/""]}}}},""Effect"":""Allow"",""Principal"":{{""AWS"":[""*""]}},""Resource"":[""arn:aws:s3:::{bucketName}""],""Sid"":""""}},{{""Action"":[""s3:GetObject""],""Effect"":""Allow"",""Principal"":{{""AWS"":[""*""]}},""Resource"":[""arn:aws:s3:::{bucketName}/foo*"",""arn:aws:s3:::{bucketName}/prefix/*""],""Sid"":""""}}]}}";
await minioClient.SetPolicyAsync("myBucket", policyJson);
SetPolicyArgs args = new SetPolicyArgs()
.WithBucket("myBucket")
.WithPolicy(policyJson);
await minioClient.SetPolicyAsync(args);
}
catch (MinioException e)
{
Expand Down
15 changes: 13 additions & 2 deletions Minio.Examples/Cases/DeleteBucketPolicy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

using System;
using System.Threading.Tasks;
using Minio.Exceptions;

namespace Minio.Examples.Cases
{
Expand All @@ -27,11 +28,21 @@ public async static Task Run(MinioClient minio,
{
try
{
Console.WriteLine("Running example for API: SetPolicyAsync");
Console.WriteLine("Running example for API: DeletePolicyAsync");
var args = new RemovePolicyArgs()
.WithBucket(bucketName);
await minio.RemovePolicyAsync(args);
Console.WriteLine($"Policy previously set for the bucket {bucketName} successfully");
Console.WriteLine($"Policy previously set for the bucket {bucketName} removed.");
try
{
var getArgs = new GetPolicyArgs()
.WithBucket(bucketName);
string policy = await minio.GetPolicyAsync(getArgs);
}
catch(UnexpectedMinioException e)
{
Console.WriteLine($"GetPolicy operation for {bucketName} result: {e.ServerMessage}");
}
Console.WriteLine();
}
catch (Exception e)
Expand Down
3 changes: 3 additions & 0 deletions Minio.Functional.Tests/FunctionalTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2717,8 +2717,11 @@ await minio.PutObjectAsync(bucketName,
.WithPolicy(policyJson);
var getPolicyArgs = new GetPolicyArgs()
.WithBucket(bucketName);
var rmPolicyArgs = new RemovePolicyArgs()
.WithBucket(bucketName);
await minio.SetPolicyAsync(setPolicyArgs);
string policy = await minio.GetPolicyAsync(getPolicyArgs);
await minio.RemovePolicyAsync(rmPolicyArgs);
await minio.RemoveObjectAsync(bucketName, objectName);

await TearDown(minio, bucketName);
Expand Down
59 changes: 20 additions & 39 deletions Minio/ApiEndpoints/BucketOperations.cs
Original file line number Diff line number Diff line change
Expand Up @@ -142,13 +142,14 @@ public partial class MinioClient : IBucketOperations
await this.ExecuteTaskAsync(this.NoErrorHandlers, request, cancellationToken).ConfigureAwait(false);
}


/// <summary>
/// Returns current policy stored on the server for this bucket
/// </summary>
/// <param name="args">GetPolicyArgs object has information like Bucket name.</param>
/// <param name="cancellationToken">Optional cancellation token to cancel the operation</param>
/// <returns>Task that returns the Bucket policy as a json string</returns>
/// <exception cref="InvalidBucketNameException">When bucketName is invalid</exception>
/// <exception cref="UnexpectedMinioException">When a policy is not set</exception>
public async Task<string> GetPolicyAsync(GetPolicyArgs args, CancellationToken cancellationToken = default(CancellationToken))
{
RestRequest request = await this.CreateRequest(args).ConfigureAwait(false);
Expand All @@ -161,51 +162,46 @@ public partial class MinioClient : IBucketOperations
/// <summary>
/// Sets the current bucket policy
/// </summary>
/// <param name="args">SetPolicyArgs object has information like Bucket name & the policy to set in Json format</param>
/// <param name="args">SetPolicyArgs object has information like Bucket name and the policy to set in Json format</param>
/// <param name="cancellationToken">Optional cancellation token to cancel the operation</param>
/// <returns>Task to set a policy</returns>
public async Task SetPolicyAsync(SetPolicyArgs args, CancellationToken cancellationToken = default(CancellationToken))
{
RestRequest request = await this.CreateRequest(args).ConfigureAwait(false);
IRestResponse response = await this.ExecuteTaskAsync(this.NoErrorHandlers, request, cancellationToken).ConfigureAwait(false);
SetPolicyResponse getPolicyResponse = new SetPolicyResponse(response.StatusCode, response.Content);
await this.ExecuteTaskAsync(this.NoErrorHandlers, request, cancellationToken).ConfigureAwait(false);
}


/// <summary>
/// Sets the current bucket policy
/// Removes the current bucket policy
/// </summary>
/// <param name="args">SetPolicyArgs object has information like Bucket name & the policy to set in Json format</param>
/// <param name="args">RemovePolicyArgs object has information like Bucket name</param>
/// <param name="cancellationToken">Optional cancellation token to cancel the operation</param>
/// <returns>Task to set a policy</returns>
/// <exception cref="InvalidBucketNameException">When bucketName is invalid</exception>
/// <exception cref="UnexpectedMinioException">When a policy is not set</exception>
public async Task RemovePolicyAsync(RemovePolicyArgs args, CancellationToken cancellationToken = default(CancellationToken))
{
RestRequest request = await this.CreateRequest(args).ConfigureAwait(false);
IRestResponse response = await this.ExecuteTaskAsync(this.NoErrorHandlers, request, cancellationToken).ConfigureAwait(false);
await this.ExecuteTaskAsync(this.NoErrorHandlers, request, cancellationToken).ConfigureAwait(false);
}


/// <summary>
/// List all objects in a bucket
/// List all the buckets for the current Endpoint URL
/// </summary>
/// <param name="cancellationToken">Optional cancellation token to cancel the operation</param>
/// <returns>Task with an iterator lazily populated with objects</returns>
public async Task<ListAllMyBucketsResult> ListBucketsAsync(CancellationToken cancellationToken = default(CancellationToken))
{
var request = await this.CreateRequest(Method.GET, resourcePath: "/").ConfigureAwait(false);
var response = await this.ExecuteTaskAsync(this.NoErrorHandlers, request, cancellationToken).ConfigureAwait(false);

ListAllMyBucketsResult bucketList = new ListAllMyBucketsResult();
if (HttpStatusCode.OK.Equals(response.StatusCode))
{
var contentBytes = System.Text.Encoding.UTF8.GetBytes(response.Content);
using (var stream = new MemoryStream(contentBytes))
bucketList = (ListAllMyBucketsResult)new XmlSerializer(typeof(ListAllMyBucketsResult)).Deserialize(stream);
return bucketList;
}
return bucketList;
ListBucketsResponse listBucketsResponse = new ListBucketsResponse(response.StatusCode, response.Content);
return listBucketsResponse.BucketsResult;
}


/// <summary>
/// Create a private bucket with the given name.
/// </summary>
Expand Down Expand Up @@ -396,22 +392,9 @@ public partial class MinioClient : IBucketOperations
/// <returns>Task that returns the Bucket policy as a json string</returns>
public async Task<string> GetPolicyAsync(string bucketName, CancellationToken cancellationToken = default(CancellationToken))
{
IRestResponse response = null;

var request = await this.CreateRequest(Method.GET, bucketName,
contentType: "application/json")
.ConfigureAwait(false);
request.AddQueryParameter("policy","");
string policyString = null;
response = await this.ExecuteTaskAsync(this.NoErrorHandlers, request, cancellationToken).ConfigureAwait(false);
var contentBytes = System.Text.Encoding.UTF8.GetBytes(response.Content);

using (var stream = new MemoryStream(contentBytes))
using (var streamReader = new StreamReader(stream))
{
policyString = await streamReader.ReadToEndAsync().ConfigureAwait(false);
}
return policyString;
GetPolicyArgs args = new GetPolicyArgs()
.WithBucket(bucketName);
return await this.GetPolicyAsync(args, cancellationToken);
}


Expand All @@ -424,12 +407,10 @@ public partial class MinioClient : IBucketOperations
/// <returns>Task to set a policy</returns>
public async Task SetPolicyAsync(string bucketName, string policyJson, CancellationToken cancellationToken = default(CancellationToken))
{
var request = await this.CreateRequest(Method.PUT, bucketName,
contentType: "application/json")
.ConfigureAwait(false);
request.AddQueryParameter("policy","");
request.AddJsonBody(policyJson);
IRestResponse response = await this.ExecuteTaskAsync(this.NoErrorHandlers, request, cancellationToken).ConfigureAwait(false);
SetPolicyArgs args = new SetPolicyArgs()
.WithBucket(bucketName)
.WithPolicy(policyJson);
await this.SetPolicyAsync(args, cancellationToken);
}

/// <summary>
Expand Down
41 changes: 23 additions & 18 deletions Minio/DataModel/BucketOperationsReponse.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 +25,34 @@ internal class GetVersioningResponse : GenericResponse
{
internal VersioningConfiguration VersioningConfig { get; set; }
internal GetVersioningResponse(HttpStatusCode statusCode, string responseContent)
: base(statusCode, responseContent)
: base(statusCode, responseContent)
{
if (string.IsNullOrEmpty(responseContent) ||
!HttpStatusCode.OK.Equals(statusCode))
{
return;
}
using (var stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(responseContent)))
{
this.VersioningConfig = (VersioningConfiguration)new XmlSerializer(typeof(VersioningConfiguration)).Deserialize(stream);
}
}
}

internal class ListBucketsResponse : GenericResponse
{
internal ListAllMyBucketsResult BucketsResult;
internal ListBucketsResponse(HttpStatusCode statusCode, string responseContent)
: base(statusCode, responseContent)
{
if ( string.IsNullOrEmpty(responseContent) )
if (string.IsNullOrEmpty(responseContent) ||
!HttpStatusCode.OK.Equals(statusCode))
{
return;
}
if (HttpStatusCode.OK.Equals(statusCode))
using (var stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(responseContent)))
{
using (var stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(responseContent)))
{
this.VersioningConfig = (VersioningConfiguration)new XmlSerializer(typeof(VersioningConfiguration)).Deserialize(stream);
}
this.BucketsResult = (ListAllMyBucketsResult)new XmlSerializer(typeof(ListAllMyBucketsResult)).Deserialize(stream);
}
}
}
Expand Down Expand Up @@ -65,15 +81,4 @@ internal GetPolicyResponse(HttpStatusCode statusCode, string responseContent)
Initialize();
}
}

internal class SetPolicyResponse : GenericResponse
{
internal string PolicyJsonString { get; private set; }

internal SetPolicyResponse(HttpStatusCode statusCode, string responseContent)
: base(statusCode, responseContent)
{
}

}
}

0 comments on commit 7091d65

Please sign in to comment.