Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Get/Set Bucket Policy with Args/Response object. #460

Merged
merged 2 commits into from
Sep 17, 2020
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
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
54 changes: 54 additions & 0 deletions Minio.Examples/Cases/DeleteBucketPolicy.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/*
* MinIO .NET Library for Amazon S3 Compatible Cloud Storage, (C) 2020 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

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

namespace Minio.Examples.Cases
{
class DeleteBucketPolicy
{
// Set bucket policy
public async static Task Run(MinioClient minio,
string bucketName = "my-bucket-name")
{
try
{
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} 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)
{
Console.WriteLine($"[Bucket] Exception: {e}");
}
}
}
}
6 changes: 4 additions & 2 deletions Minio.Examples/Cases/GetBucketPolicy.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* MinIO .NET Library for Amazon S3 Compatible Cloud Storage, (C) 2017 MinIO, Inc.
* MinIO .NET Library for Amazon S3 Compatible Cloud Storage, (C) 2017-2020 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -28,8 +28,10 @@ public async static Task Run(MinioClient minio,
{
try
{
var args = new GetPolicyArgs()
.WithBucket(bucketName);
Console.WriteLine("Running example for API: GetPolicyAsync");
string policyJson = await minio.GetPolicyAsync(bucketName);
string policyJson = await minio.GetPolicyAsync(args);
Console.WriteLine($"Current Policy is {policyJson} for bucket {bucketName}");
Console.WriteLine();
}
Expand Down
7 changes: 5 additions & 2 deletions Minio.Examples/Cases/SetBucketPolicy.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* MinIO .NET Library for Amazon S3 Compatible Cloud Storage, (C) 2017 MinIO, Inc.
* MinIO .NET Library for Amazon S3 Compatible Cloud Storage, (C) 2017-2020 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -30,7 +30,10 @@ public async static Task Run(MinioClient minio,
Console.WriteLine("Running example for API: SetPolicyAsync");
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"":""""}}]}}";
// Change policy type parameter
await minio.SetPolicyAsync(bucketName, policyJson);
var args = new SetPolicyArgs()
.WithBucket(bucketName)
.WithPolicy(policyJson);
await minio.SetPolicyAsync(args);
Console.WriteLine($"Policy {policyJson} set for the bucket {bucketName} successfully");
Console.WriteLine();
}
Expand Down
21 changes: 15 additions & 6 deletions Minio.Functional.Tests/FunctionalTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,8 @@ public class FunctionalTest
private const string presignedGetObjectSignature = "Task<string> PresignedGetObjectAsync(string bucketName, string objectName, int expiresInt, Dictionary<string, string> reqParams = null)";
private const string presignedPutObjectSignature = "Task<string> PresignedPutObjectAsync(string bucketName, string objectName, int expiresInt)";
private const string presignedPostPolicySignature = "Task<Dictionary<string, string>> PresignedPostPolicyAsync(PostPolicy policy)";
private const string getBucketPolicySignature = "Task<string> GetPolicyAsync(string bucketName, CancellationToken cancellationToken = default(CancellationToken))";
private const string setBucketPolicySignature = "Task SetPolicyAsync(string bucketName, string policyJson, CancellationToken cancellationToken = default(CancellationToken))";
private const string getBucketPolicySignature = "Task<string> GetPolicyAsync(GetPolicyArgs args, CancellationToken cancellationToken = default(CancellationToken))";
private const string setBucketPolicySignature = "Task SetPolicyAsync(SetPolicyArgs args, CancellationToken cancellationToken = default(CancellationToken))";
private const string getBucketNotificationSignature = "Task<BucketNotification> GetBucketNotificationAsync(string bucketName, CancellationToken cancellationToken = default(CancellationToken))";
private const string setBucketNotificationSignature = "Task SetBucketNotificationAsync(string bucketName, BucketNotification notification, CancellationToken cancellationToken = default(CancellationToken))";
private const string removeAllBucketsNotificationSignature = "Task RemoveAllBucketNotificationsAsync(string bucketName, CancellationToken cancellationToken = default(CancellationToken))";
Expand Down Expand Up @@ -2424,7 +2424,9 @@ await minio.PutObjectAsync(bucketName,
}

// Validate
string policy = await minio.GetPolicyAsync(bucketName);
var policyArgs = new GetPolicyArgs()
.WithBucket(bucketName);
string policy = await minio.GetPolicyAsync(policyArgs);
await minio.RemoveObjectAsync(bucketName, objectName);
await TearDown(minio, bucketName);
new MintLogger("PresignedPostPolicy_Test1", presignedPostPolicySignature, "Tests whether PresignedPostPolicy url applies policy on server", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log();
Expand Down Expand Up @@ -2710,9 +2712,16 @@ internal async static Task GetBucketPolicy_Test1(MinioClient minio)
await minio.PutObjectAsync(bucketName,
objectName,
filestream, filestream.Length, null);
await minio.SetPolicyAsync(bucketName,
policyJson);
string policy = await minio.GetPolicyAsync(bucketName);
var setPolicyArgs = new SetPolicyArgs()
.WithBucket(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
79 changes: 55 additions & 24 deletions Minio/ApiEndpoints/BucketOperations.cs
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,52 @@ public partial class MinioClient : IBucketOperations
}

/// <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);
IRestResponse response = await this.ExecuteTaskAsync(this.NoErrorHandlers, request, cancellationToken).ConfigureAwait(false);
GetPolicyResponse getPolicyResponse = new GetPolicyResponse(response.StatusCode, response.Content);
return getPolicyResponse.PolicyJsonString;
}


/// <summary>
/// Sets the current bucket policy
/// </summary>
/// <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);
await this.ExecuteTaskAsync(this.NoErrorHandlers, request, cancellationToken).ConfigureAwait(false);
}


/// <summary>
/// Removes the current bucket policy
/// </summary>
/// <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);
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>
Expand Down Expand Up @@ -337,6 +383,7 @@ public partial class MinioClient : IBucketOperations
return Tuple.Create(listBucketResult, items.ToList());
}


/// <summary>
/// Returns current policy stored on the server for this bucket
/// </summary>
Expand All @@ -345,24 +392,12 @@ 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);
}


/// <summary>
/// Sets the current bucket policy
/// </summary>
Expand All @@ -372,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 Expand Up @@ -499,9 +532,7 @@ public partial class MinioClient : IBucketOperations
cts.Token.ThrowIfCancellationRequested();
}
}

});

}
}
}
51 changes: 51 additions & 0 deletions Minio/DataModel/BucketOperationsArgs.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
*/

using Minio.DataModel;
using Minio.Exceptions;
using RestSharp;

namespace Minio
Expand Down Expand Up @@ -74,4 +75,54 @@ public override RestRequest BuildRequest(RestRequest request)
return request;
}
}

public class GetPolicyArgs : BucketArgs<GetPolicyArgs>
{
public GetPolicyArgs()
{
this.RequestMethod = Method.GET;
}
public override RestRequest BuildRequest(RestRequest request)
{
request.AddQueryParameter("policy","");
return request;
}
}

public class SetPolicyArgs : BucketArgs<SetPolicyArgs>
{
internal string PolicyJsonString { get; private set; }
public SetPolicyArgs()
{
this.RequestMethod = Method.PUT;
}
public override RestRequest BuildRequest(RestRequest request)
{
if (string.IsNullOrEmpty(this.PolicyJsonString))
{
new MinioException("SetPolicyArgs needs the policy to be set to the right JSON contents.");
}
request.AddQueryParameter("policy","");
request.AddJsonBody(this.PolicyJsonString);
return request;
}
public SetPolicyArgs WithPolicy(string policy)
{
this.PolicyJsonString = policy;
return this;
}
}

public class RemovePolicyArgs : BucketArgs<RemovePolicyArgs>
{
public RemovePolicyArgs()
{
this.RequestMethod = Method.DELETE;
}
public override RestRequest BuildRequest(RestRequest request)
{
request.AddQueryParameter("policy","");
return request;
}
}
}
Loading