From ef88bcc98b6139ce3df554e0998d795e65ea92cd Mon Sep 17 00:00:00 2001 From: poornas Date: Mon, 19 Mar 2018 17:44:07 -0700 Subject: [PATCH] Simplify SetPolicyAsync and GetPolicyAsync api calls (#217) --- Docs/API.md | 22 +- Minio.Core/Minio.Core.csproj | 15 +- Minio.Examples/Cases/GetBucketPolicy.cs | 4 +- Minio.Examples/Cases/SetBucketPolicy.cs | 11 +- Minio.Examples/Program.cs | 8 +- Minio.Functional.Tests/FunctionalTest.cs | 20 +- Minio.Net452/Minio.Net452.csproj | 39 - Minio.Net452/Properties/AssemblyInfo.cs | 4 +- Minio.Tests/AuthenticatorTest.cs | 1 - Minio.Tests/Minio.Tests.csproj | 2 - Minio.Tests/PolicyConditionTests.cs | 293 ------- Minio.Tests/PolicyTests.cs | 746 ------------------ Minio.Tests/TestHelper.cs | 53 -- Minio.core.nuspec | 2 +- Minio.nuspec | 2 +- Minio/ApiEndpoints/BucketOperations.cs | 85 +- Minio/ApiEndpoints/IBucketOperations.cs | 12 +- Minio/DataModel/Policy/ActionJsonConverter.cs | 60 -- Minio/DataModel/Policy/BucketPolicy.cs | 572 -------------- Minio/DataModel/Policy/ConditionKeyMap.cs | 85 -- .../Policy/ConditionKeyMapConverter.cs | 83 -- Minio/DataModel/Policy/ConditionMap.cs | 61 -- Minio/DataModel/Policy/Constants.cs | 69 -- Minio/DataModel/Policy/PolicyConstants.cs | 69 -- Minio/DataModel/Policy/PolicyType.cs | 49 -- Minio/DataModel/Policy/Principal.cs | 57 -- .../Policy/PrincipalJsonConverter.cs | 65 -- .../DataModel/Policy/ResourceJsonConverter.cs | 71 -- Minio/DataModel/Policy/Resources.cs | 90 --- .../Policy/SingleOrArrayConverter.cs | 53 -- Minio/DataModel/Policy/Statement.cs | 299 ------- 31 files changed, 51 insertions(+), 2951 deletions(-) delete mode 100644 Minio.Tests/PolicyConditionTests.cs delete mode 100644 Minio.Tests/PolicyTests.cs delete mode 100644 Minio/DataModel/Policy/ActionJsonConverter.cs delete mode 100644 Minio/DataModel/Policy/BucketPolicy.cs delete mode 100644 Minio/DataModel/Policy/ConditionKeyMap.cs delete mode 100644 Minio/DataModel/Policy/ConditionKeyMapConverter.cs delete mode 100644 Minio/DataModel/Policy/ConditionMap.cs delete mode 100644 Minio/DataModel/Policy/Constants.cs delete mode 100644 Minio/DataModel/Policy/PolicyConstants.cs delete mode 100644 Minio/DataModel/Policy/PolicyType.cs delete mode 100644 Minio/DataModel/Policy/Principal.cs delete mode 100644 Minio/DataModel/Policy/PrincipalJsonConverter.cs delete mode 100644 Minio/DataModel/Policy/ResourceJsonConverter.cs delete mode 100644 Minio/DataModel/Policy/Resources.cs delete mode 100644 Minio/DataModel/Policy/SingleOrArrayConverter.cs delete mode 100644 Minio/DataModel/Policy/Statement.cs diff --git a/Docs/API.md b/Docs/API.md index 8f037ff2a..055ce4155 100644 --- a/Docs/API.md +++ b/Docs/API.md @@ -393,10 +393,10 @@ catch (MinioException e) ``` -### GetPolicyAsync(string bucketName, string objectPrefix) -`Task GetPolicyAsync(string bucketName, string objectPrefix, CancellationToken cancellationToken = default(CancellationToken))` +### GetPolicyAsync(string bucketName) +`Task GetPolicyAsync(string bucketName, CancellationToken cancellationToken = default(CancellationToken))` -Get bucket policy at given objectPrefix. +Get bucket policy. __Parameters__ @@ -404,13 +404,12 @@ __Parameters__ |Param | Type | Description | |:--- |:--- |:--- | | ``bucketName`` | _string_ | Name of the bucket. | -| ``objectPrefix`` | _string_ | Policy applies to objects with prefix | | ``cancellationToken``| _System.Threading.CancellationToken_ | Optional parameter. Defaults to default(CancellationToken) | | Return Type | Exceptions | |:--- |:--- | -| ``Task``: The current bucket policy for given bucket and objectPrefix. | Listed Exceptions: | +| ``Task``: The current bucket policy for given bucket as a json string. | Listed Exceptions: | | | ``InvalidBucketNameException `` : upon invalid bucket name. | | | ``InvalidObjectPrefixException`` : upon invalid object prefix. | | | ``ConnectionException`` : upon connection error. | @@ -425,7 +424,7 @@ __Example__ ```cs try { - PolicyType policy = await minioClient.GetPolicyAsync("myBucket", objectPrefix:"downloads"); + String policyJson = await minioClient.GetPolicyAsync("myBucket"); Console.Out.WriteLine("Current policy: " + policy.GetType().ToString()); } catch (MinioException e) @@ -435,18 +434,17 @@ catch (MinioException e) ``` -### SetPolicyAsync(string bucketName, string objectPrefix, PolicyType policyType) -`Task SetPolicyAsync(string bucketName, string objectPrefix, PolicyType policyType, CancellationToken cancellationToken = default(CancellationToken))` +### SetPolicyAsync(string bucketName, string policyJson) +`Task SetPolicyAsync(string bucketName, string policyJson, CancellationToken cancellationToken = default(CancellationToken))` -Set policy on bucket and object prefix. +Set policy on bucket. __Parameters__ |Param | Type | Description | |:--- |:--- |:--- | | ``bucketName`` | _string_ | Name of the bucket | -| ``objectPrefix`` | _string_ | Policy applies to objects with prefix | -| ``PolicyType`` | _PolicyType_ | Policy to apply | +| ``policyJson`` | _string_ | Policy as a json string | | ``cancellationToken``| _System.Threading.CancellationToken_ | Optional parameter. Defaults to default(CancellationToken) | @@ -466,7 +464,7 @@ __Example__ ```cs try { - await minioClient.SetPolicyAsync("myBucket", "uploads",PolicyType.WRITE_ONLY); + await minioClient.SetPolicyAsync("myBucket"); } catch (MinioException e) { diff --git a/Minio.Core/Minio.Core.csproj b/Minio.Core/Minio.Core.csproj index 0314161ab..b53b1a6be 100644 --- a/Minio.Core/Minio.Core.csproj +++ b/Minio.Core/Minio.Core.csproj @@ -5,7 +5,7 @@ Minio False Minio - 1.0.8 + 1.1.0 @@ -58,19 +58,6 @@ - - - - - - - - - - - - - diff --git a/Minio.Examples/Cases/GetBucketPolicy.cs b/Minio.Examples/Cases/GetBucketPolicy.cs index ad4e50c16..8b62d0e8a 100644 --- a/Minio.Examples/Cases/GetBucketPolicy.cs +++ b/Minio.Examples/Cases/GetBucketPolicy.cs @@ -30,8 +30,8 @@ public async static Task Run(Minio.MinioClient minio, try { Console.Out.WriteLine("Running example for API: GetPolicyAsync"); - PolicyType policy = await minio.GetPolicyAsync(bucketName); - Console.Out.WriteLine("Current Policy is " + policy.ToString() + " for bucket " + bucketName); + String policyJson = await minio.GetPolicyAsync(bucketName); + Console.Out.WriteLine("Current Policy is " + policyJson + " for bucket " + bucketName); Console.Out.WriteLine(); } catch (Exception e) diff --git a/Minio.Examples/Cases/SetBucketPolicy.cs b/Minio.Examples/Cases/SetBucketPolicy.cs index 2e2ac0127..4301069f6 100644 --- a/Minio.Examples/Cases/SetBucketPolicy.cs +++ b/Minio.Examples/Cases/SetBucketPolicy.cs @@ -24,18 +24,15 @@ class SetBucketPolicy { // Set bucket policy public async static Task Run(Minio.MinioClient minio, - PolicyType policy, - string bucketName = "my-bucket-name", - string objectPrefix="") + string bucketName = "my-bucket-name") { try { Console.Out.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, - objectPrefix, - policy); - Console.Out.WriteLine("Policy " + policy.ToString() + " set for the bucket " + bucketName + " successfully"); + await minio.SetPolicyAsync(bucketName, policyJson); + Console.Out.WriteLine("Policy " + policyJson + " set for the bucket " + bucketName + " successfully"); Console.Out.WriteLine(); } catch (Exception e) diff --git a/Minio.Examples/Program.cs b/Minio.Examples/Program.cs index 9d5a4969a..6cdfa64eb 100644 --- a/Minio.Examples/Program.cs +++ b/Minio.Examples/Program.cs @@ -114,13 +114,12 @@ public static void Main(string[] args) // Set HTTP Tracing Off // minioClient.SetTraceOff(); - // Check if bucket exists Cases.BucketExists.Run(minioClient, bucketName).Wait(); // Create a new bucket Cases.MakeBucket.Run(minioClient, bucketName).Wait(); - + Cases.MakeBucket.Run(minioClient, destBucketName).Wait(); @@ -161,11 +160,10 @@ public static void Main(string[] args) Cases.RemoveIncompleteUpload.Run(minioClient, bucketName, objectName).Wait(); // Set a policy for given bucket - Cases.SetBucketPolicy.Run(minioClient, PolicyType.READ_ONLY, bucketName).Wait(); - + Cases.SetBucketPolicy.Run(minioClient, bucketName).Wait(); // Get the policy for given bucket Cases.GetBucketPolicy.Run(minioClient, bucketName).Wait(); - + // Set bucket notifications Cases.SetBucketNotification.Run(minioClient, bucketName).Wait(); diff --git a/Minio.Functional.Tests/FunctionalTest.cs b/Minio.Functional.Tests/FunctionalTest.cs index cdc674b6d..70f4e3009 100644 --- a/Minio.Functional.Tests/FunctionalTest.cs +++ b/Minio.Functional.Tests/FunctionalTest.cs @@ -57,8 +57,8 @@ class FunctionalTest private static string presignedGetObjectSignature = "Task PresignedGetObjectAsync(string bucketName, string objectName, int expiresInt, Dictionary reqParams = null)"; private static string presignedPutObjectSignature = "Task PresignedPutObjectAsync(string bucketName, string objectName, int expiresInt)"; private static string presignedPostPolicySignature = "Task> PresignedPostPolicyAsync(PostPolicy policy)"; - private static string getBucketPolicySignature = "Task GetPolicyAsync(string bucketName, string objectPrefix, CancellationToken cancellationToken = default(CancellationToken))"; - private static string setBucketPolicySignature = "Task SetPolicyAsync(string bucketName, string objectPrefix, PolicyType policyType, CancellationToken cancellationToken = default(CancellationToken))"; + private static string getBucketPolicySignature = "Task GetPolicyAsync(string bucketName,CancellationToken cancellationToken = default(CancellationToken))"; + private static string setBucketPolicySignature = "Task SetPolicyAsync(string bucketName, string policyJson, CancellationToken cancellationToken = default(CancellationToken))"; private static string getBucketNotificationSignature = "Task GetBucketNotificationAsync(string bucketName, CancellationToken cancellationToken = default(CancellationToken))"; private static string setBucketNotificationSignature = "Task SetBucketNotificationAsync(string bucketName, BucketNotification notification, CancellationToken cancellationToken = default(CancellationToken))"; private static string removeAllBucketsNotificationSignature = "Task RemoveAllBucketNotificationsAsync(string bucketName, CancellationToken cancellationToken = default(CancellationToken))"; @@ -1957,8 +1957,7 @@ await minio.PutObjectAsync(bucketName, } // Validate - PolicyType policy = await minio.GetPolicyAsync(bucketName, objectName.Substring(5)); - Assert.AreEqual(policy.GetType(), PolicyType.READ_ONLY); + String policy = await minio.GetPolicyAsync(bucketName); 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(); @@ -2196,9 +2195,9 @@ private async static Task SetBucketPolicy_Test1(MinioClient minio) await minio.PutObjectAsync(bucketName, objectName, filestream, filestream.Length, null); + string policyJson = $@"{{""Version"":""2012-10-17"",""Statement"":[{{""Action"":[""s3:GetObject""],""Effect"":""Allow"",""Principal"":{{""AWS"":[""*""]}},""Resource"":[""arn:aws:s3:::{bucketName}/foo*"",""arn:aws:s3:::{bucketName}/prefix/*""],""Sid"":""""}}]}}"; await minio.SetPolicyAsync(bucketName, - objectName.Substring(5), - PolicyType.READ_ONLY); + policyJson); await minio.RemoveObjectAsync(bucketName, objectName); await TearDown(minio, bucketName); @@ -2219,20 +2218,19 @@ private async static Task GetBucketPolicy_Test1(MinioClient minio) Dictionary args = new Dictionary { {"bucketName", bucketName}, - {"objectPrefix", objectName.Substring(5)}, }; try { await Setup_Test(minio, bucketName); + String policyJson=""; using (MemoryStream filestream = rsg.GenerateStreamFromSeed(1 * MB)) await minio.PutObjectAsync(bucketName, objectName, filestream, filestream.Length, null); await minio.SetPolicyAsync(bucketName, - objectName.Substring(5), - PolicyType.READ_ONLY); - PolicyType policy = await minio.GetPolicyAsync(bucketName, objectName.Substring(5)); - Assert.IsTrue(policy.Equals(PolicyType.READ_ONLY)); + policyJson); + String policy = await minio.GetPolicyAsync(bucketName); + Assert.IsTrue(policy.Equals(policyJson)); await minio.RemoveObjectAsync(bucketName, objectName); await TearDown(minio, bucketName); diff --git a/Minio.Net452/Minio.Net452.csproj b/Minio.Net452/Minio.Net452.csproj index 084060dde..5d1bd3e5e 100644 --- a/Minio.Net452/Minio.Net452.csproj +++ b/Minio.Net452/Minio.Net452.csproj @@ -183,45 +183,6 @@ DataModel\Part.cs - - DataModel\Policy\ActionJsonConverter.cs - - - DataModel\Policy\BucketPolicy.cs - - - DataModel\Policy\ConditionKeyMap.cs - - - DataModel\Policy\ConditionKeyMapConverter.cs - - - DataModel\Policy\ConditionMap.cs - - - DataModel\Policy\PolicyConstants.cs - - - DataModel\Policy\PolicyType.cs - - - DataModel\Policy\Principal.cs - - - DataModel\Policy\PrincipalJsonConverter.cs - - - DataModel\Policy\ResourceJsonConverter.cs - - - DataModel\Policy\Resources.cs - - - DataModel\Policy\SingleOrArrayConverter.cs - - - DataModel\Policy\Statement.cs - DataModel\PostPolicy.cs diff --git a/Minio.Net452/Properties/AssemblyInfo.cs b/Minio.Net452/Properties/AssemblyInfo.cs index a4249edd6..d8e6a65c6 100644 --- a/Minio.Net452/Properties/AssemblyInfo.cs +++ b/Minio.Net452/Properties/AssemblyInfo.cs @@ -30,6 +30,6 @@ // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.8.0")] -[assembly: AssemblyFileVersion("1.0.8.0")] +[assembly: AssemblyVersion("1.1.0.0")] +[assembly: AssemblyFileVersion("1.1.0.0")] diff --git a/Minio.Tests/AuthenticatorTest.cs b/Minio.Tests/AuthenticatorTest.cs index 7fb17441d..bd9f72065 100644 --- a/Minio.Tests/AuthenticatorTest.cs +++ b/Minio.Tests/AuthenticatorTest.cs @@ -15,7 +15,6 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using Minio.DataModel; -using Minio.DataModel.Policy; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; diff --git a/Minio.Tests/Minio.Tests.csproj b/Minio.Tests/Minio.Tests.csproj index dcaad808d..88227884b 100644 --- a/Minio.Tests/Minio.Tests.csproj +++ b/Minio.Tests/Minio.Tests.csproj @@ -83,11 +83,9 @@ - - diff --git a/Minio.Tests/PolicyConditionTests.cs b/Minio.Tests/PolicyConditionTests.cs deleted file mode 100644 index 78727a0d5..000000000 --- a/Minio.Tests/PolicyConditionTests.cs +++ /dev/null @@ -1,293 +0,0 @@ -/* - * Minio .NET Library for Amazon S3 Compatible Cloud Storage, (C) 2017 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 Microsoft.VisualStudio.TestTools.UnitTesting; -using Minio.DataModel; -using Minio.DataModel.Policy; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using System; -using System.Collections.Generic; -using System.IO; -using System.Runtime.Serialization.Json; -using System.Text; - -namespace Minio.Tests -{ - [TestClass] - public class PolicyConditionTests - { - - [TestMethod] - public void TestConditionKeyMapAdd() - { - var testCases = new List>, string>>() - { - // Add new k-v pair - new KeyValuePair>, string>(new Tuple>("s3:prefix",new HashSet(){"hello" }), @"{""s3:prefix"":[""hello""]}" ), - // Add existing k-v pair - new KeyValuePair>, string>(new Tuple>("s3:prefix",new HashSet(){"hello" }), @"{""s3:prefix"":[""hello""]}" ), - // Add existing key and not value - new KeyValuePair>, string>(new Tuple>("s3:prefix",new HashSet(){"world" }), @"{""s3:prefix"":[""hello"", ""world""]}" ), - - }; - ConditionKeyMap cmap = new ConditionKeyMap(); - int index = 0; - foreach (KeyValuePair>, string> pair in testCases) - { - try - { - index += 1; - var testcase = pair.Key; - string prefix = testcase.Item1; - HashSet stringSet = testcase.Item2; - string expectedConditionKMap = pair.Value; - cmap.Add(prefix, stringSet); - string cmpstring = JsonConvert.SerializeObject(cmap, Formatting.None, - new JsonSerializerSettings - { - NullValueHandling = NullValueHandling.Ignore - }); - - Assert.AreEqual(cmpstring, expectedConditionKMap); - } - catch (ArgumentException) - { - Assert.AreNotEqual(index, 1); - } - - - } - } - - [TestMethod] - public void TestConditionKeyMapRemove() - { - var testCases = new List>, string>>() - { - // Add new k-v pair - new KeyValuePair>, string>(new Tuple>("s3:myprefix",new HashSet(){"hello" }), @"{""s3:prefix"":[""hello"",""world""]}" ), - // Add existing k-v pair - new KeyValuePair>, string>(new Tuple>("s3:prefix",new HashSet(){"hello" }), @"{""s3:prefix"":[""world""]}" ), - // Add existing key and not value - new KeyValuePair>, string>(new Tuple>("s3:prefix",new HashSet(){"world" }), @"{}" ), - - }; - ConditionKeyMap cmap = new ConditionKeyMap(); - cmap.Add("s3:prefix", new HashSet() { "hello", "world" }); - - int index = 0; - foreach (KeyValuePair>, string> pair in testCases) - { - try - { - index += 1; - var testcase = pair.Key; - string prefix = testcase.Item1; - HashSet stringSet = testcase.Item2; - string expectedConditionKMap = pair.Value; - cmap.remove(prefix, stringSet); - string cmpstring = JsonConvert.SerializeObject(cmap, Formatting.None, - new JsonSerializerSettings - { - NullValueHandling = NullValueHandling.Ignore - }); - - Assert.AreEqual(cmpstring, expectedConditionKMap); - } - catch (ArgumentException) - { - Assert.AreNotEqual(index, 1); - } - - - } - } - - [TestMethod] - // Tests if condition key map merges existing values - public void TestConditionKeyMapPut() - { - ConditionKeyMap cmap1 = new ConditionKeyMap(); - cmap1.Add("s3:prefix", new HashSet() { "hello" }); - - ConditionKeyMap cmap2 = new ConditionKeyMap(); - cmap2.Add("s3:prefix", new HashSet() { "world" }); - - ConditionKeyMap cmap3 = new ConditionKeyMap(); - cmap3.Add("s3:myprefix", new HashSet() { "world" }); - - ConditionKeyMap cmap4 = new ConditionKeyMap(); - cmap4.Add("s3:prefix", new HashSet() { "hello" }); - var testCases = new List, string>>() - { - // Both args are empty - new KeyValuePair, string>(Tuple.Create(new ConditionKeyMap(),new ConditionKeyMap()), @"{}" ), - // First arg empty - new KeyValuePair, string>(Tuple.Create(new ConditionKeyMap(),cmap1), @"{""s3:prefix"":[""hello""]}" ), - //Second arg empty - new KeyValuePair, string>(Tuple.Create(cmap1,new ConditionKeyMap()), @"{""s3:prefix"":[""hello""]}" ), - //Both args have same value - new KeyValuePair, string>(Tuple.Create(cmap1,cmap4), @"{""s3:prefix"":[""hello""]}"), - //Value of second arg will be merged - new KeyValuePair, string>(Tuple.Create(cmap1, cmap2), @"{""s3:prefix"":[""hello"",""world""]}" ), - //second arg will be added - new KeyValuePair, string>(Tuple.Create(cmap1, cmap3), @"{""s3:prefix"":[""hello"",""world""],""s3:myprefix"":[""world""]}" ), - - }; - - - int index = 0; - foreach (KeyValuePair, string> pair in testCases) - { - try - { - index += 1; - var testcase = pair.Key; - ConditionKeyMap first = testcase.Item1; - ConditionKeyMap second = testcase.Item2; - string expectedConditionKMapJSON = pair.Value; - foreach (KeyValuePair> kvpair in second) - { - first.Put(kvpair.Key, kvpair.Value); - } - string cmpstring = JsonConvert.SerializeObject(first, Formatting.None, - new JsonSerializerSettings - { - NullValueHandling = NullValueHandling.Ignore - }); - - Assert.AreEqual(cmpstring, expectedConditionKMapJSON); - } - catch (ArgumentException) - { - Assert.Fail(); - } - - - } - } - [TestMethod] - public void TestConditionMapAdd() - { - ConditionMap cmap = new ConditionMap(); - - ConditionKeyMap ckmap1 = new ConditionKeyMap("s3:prefix", "hello"); - ConditionKeyMap ckmap2 = new ConditionKeyMap("s3:prefix", new HashSet { "hello", "world" }); - - var testCases = new List, string>>() - { - // Add new key and value - new KeyValuePair, string> (Tuple.Create("StringEquals",ckmap1), @"{""StringEquals"":{""s3:prefix"":[""hello""]}}"), - //Add existing key and value - new KeyValuePair, string> (Tuple.Create("StringEquals",ckmap1), @"{""StringEquals"":{""s3:prefix"":[""hello""]}}"), - //Add existing key and new value - new KeyValuePair, string> (Tuple.Create("StringEquals",ckmap2), @"{""StringEquals"":{""s3:prefix"":[""hello"",""world""]}}"), - - }; - int index = 0; - foreach (KeyValuePair,string> pair in testCases) - { - - Tuple tuple = pair.Key; - string expectedJSON = pair.Value; - - index += 1; - cmap.Put(tuple.Item1, tuple.Item2); - string cmapJSON = JsonConvert.SerializeObject(cmap, Formatting.None, - new JsonSerializerSettings - { - NullValueHandling = NullValueHandling.Ignore - }); - Assert.AreEqual(expectedJSON, cmapJSON); - } - } - - [TestMethod] - // Tests if condition key map merges existing values - public void TestConditionMapPutAll() - { - ConditionMap cmap1 = new ConditionMap(); - cmap1.Add("StringEquals",new ConditionKeyMap("s3:prefix", new HashSet() { "hello" })); - - ConditionMap cmap2 = new ConditionMap(); - cmap2.Add("StringEquals", new ConditionKeyMap("s3:prefix", new HashSet() { "world" })); - - ConditionMap cmap3 = new ConditionMap(); - cmap3.Add("StringEquals", new ConditionKeyMap("s3:myprefix", new HashSet() { "world" })); - - ConditionMap cmap4 = new ConditionMap(); - cmap4.Add("StringEquals", new ConditionKeyMap("s3:prefix", new HashSet() { "hello" })); - var testCases = new List, string>>() - { - // Both args are empty - new KeyValuePair, string>(Tuple.Create(new ConditionMap(),new ConditionMap()), @"{}" ), - // First arg empty - new KeyValuePair, string>(Tuple.Create(new ConditionMap(),cmap1), @"{""StringEquals"":{""s3:prefix"":[""hello""]}}" ), - //Second arg empty - new KeyValuePair, string>(Tuple.Create(cmap1,new ConditionMap()), @"{""StringEquals"":{""s3:prefix"":[""hello""]}}" ), - //Both args have same value - new KeyValuePair, string>(Tuple.Create(cmap1,cmap4), @"{""StringEquals"":{""s3:prefix"":[""hello""]}}"), - //Value of second arg will be merged - new KeyValuePair, string>(Tuple.Create(cmap1, cmap2), @"{""StringEquals"":{""s3:prefix"":[""hello"",""world""]}}" ), - //second arg will be added - new KeyValuePair, string>(Tuple.Create(cmap1, cmap3), @"{""StringEquals"":{""s3:prefix"":[""hello"",""world""],""s3:myprefix"":[""world""]}}" ), - - }; - - int index = 0; - foreach (KeyValuePair, string> pair in testCases) - { - try - { - index += 1; - var testcase = pair.Key; - ConditionMap first = testcase.Item1; - ConditionMap second = testcase.Item2; - string expectedConditionKMapJSON = pair.Value; - first.PutAll(second); - string cmpstring = JsonConvert.SerializeObject(first, Formatting.None, - new JsonSerializerSettings - { - NullValueHandling = NullValueHandling.Ignore - }); - - Assert.AreEqual(cmpstring, expectedConditionKMapJSON); - } - catch (ArgumentException) - { - Assert.Fail(); - } - - - } - } - - - [TestMethod] - public void TestIfStringIsetGetsDeSerialized_Test1() - { - string policyString = @"{""Version"":""2012 - 10 - 17"",""Statement"":[{""Sid"":"""",""Effect"":""Allow"",""Principal"":{""AWS"":"" * ""},""Action"":""s3: GetBucketLocation"",""Resource"":""arn: aws: s3:::miniodotnetvpn5pic718xfutt""},{""Sid"":"""",""Effect"":""Allow"",""Principal"":{""AWS"":"" * ""},""Action"":""s3: ListBucket"",""Resource"":""arn: aws: s3:::miniodotnetvpn5pic718xfutt"",""Condition"":{""StringEquals"":{""s3: prefix"":""dotnetcms1ssazhd""}}},{""Sid"":"""",""Effect"":""Allow"",""Principal"":{""AWS"":"" * ""},""Action"":""s3: GetObject"",""Resource"":""arn: aws: s3:::miniodotnetvpn5pic718xfutt / dotnetcms1ssazhd * ""}]}"; - - - // ConditionKeyMap ckmap = JsonConvert.DeserializeObject(ckmapString); - var contentBytes = System.Text.Encoding.UTF8.GetBytes(policyString); - string bucketName = "miniodotnetvpn5pic718xfutt"; - var stream = new MemoryStream(contentBytes); - BucketPolicy policy = BucketPolicy.ParseJson(stream, bucketName); - } - - } -} diff --git a/Minio.Tests/PolicyTests.cs b/Minio.Tests/PolicyTests.cs deleted file mode 100644 index 5e13dc2e9..000000000 --- a/Minio.Tests/PolicyTests.cs +++ /dev/null @@ -1,746 +0,0 @@ -/* - * Minio .NET Library for Amazon S3 Compatible Cloud Storage, (C) 2017 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 Microsoft.VisualStudio.TestTools.UnitTesting; -using System.Collections.Generic; -using Minio.DataModel.Policy; -using Minio.DataModel; -using Newtonsoft.Json; - -namespace Minio.Tests -{ - [TestClass] - public class PolicyTests - { - [TestMethod] - public void TestIfStatementIsValid() - { - var testCases = new List, bool>>() - { - - // Empty statement and bucket name - new KeyValuePair, bool>(new List{null, null, null, null,null, null },false), - - // Empty statement - new KeyValuePair, bool>(new List{"mybucket", null, null, null,null, null },false), - - // Empty bucketname - new KeyValuePair, bool>(new List{null, PolicyConstants.READ_ONLY_BUCKET_ACTIONS, "Allow",new Principal("*"),new Resources("arn:aws:s3:::mybucket"), null },false), - - // Statement with unknown actions - new KeyValuePair, bool>(new List{"mybucket", new List() { "s3:ListBucketTypes" }, "Allow", new Principal("*"),new Resources("arn:aws:s3:::mybucket"), null },false), - // Statement with unknown effect - new KeyValuePair, bool>(new List{"mybucket", PolicyConstants.READ_ONLY_BUCKET_ACTIONS, "Deny", new Principal("*"),new Resources("arn:aws:s3:::mybucket"), null },false), - - // Statement with nil Principal - new KeyValuePair, bool>(new List{"mybucket", PolicyConstants.READ_ONLY_BUCKET_ACTIONS, "Allow", null,new Resources("arn:aws:s3:::mybucket"), null },false), - - // Statement with invalid Principal - new KeyValuePair, bool>(new List{"mybucket", PolicyConstants.READ_ONLY_BUCKET_ACTIONS, "Allow", new Principal("arn:aws:iam::AccountNumberWithoutHyphens:root"),new Resources("arn:aws:s3:::mybucket"), null },false), - - // Statement with different bucketname in resource - new KeyValuePair, bool>(new List{"mybucket", PolicyConstants.READ_ONLY_BUCKET_ACTIONS, "Allow", new Principal("*"),new Resources("arn:aws:s3:::bucket"), null },false), - // Statement with incorrect bucketname in resource and suffixed string - new KeyValuePair, bool>(new List{"mybucket", PolicyConstants.READ_ONLY_BUCKET_ACTIONS, "Allow", new Principal("*"), new Resources("arn:aws:s3:::mybuckettest/testobject"),new ConditionMap() },false), - // Statement with bucket name and object name - new KeyValuePair, bool>(new List{"mybucket", PolicyConstants.READ_ONLY_BUCKET_ACTIONS, "Allow", new Principal("*"), new Resources("arn:aws:s3:::mybucket/myobject"),new ConditionMap() },true), - // Statement with conditions - new KeyValuePair, bool>(new List{"mybucket", PolicyConstants.READ_ONLY_BUCKET_ACTIONS, "Allow", new Principal("*"), new Resources("arn:aws:s3:::mybucket"),new ConditionMap() },true), - - }; - int index = 0; - foreach (KeyValuePair, bool> testCase in testCases) - { - index += 1; - List data = testCase.Key; - string bucketName = (string)data[0]; - - List actions = (List)data[1]; - string effect = (string)data[2]; - Principal principal = (Principal)data[3]; - Resources resources = (Resources)data[4]; - ConditionMap conditionMap = (ConditionMap)data[5]; - bool isExpected = testCase.Value; - - //Set statement attributes - Statement statement = new Statement(); - - statement.actions = actions; - statement.effect = effect; - statement.principal = principal; - statement.conditions = conditionMap; - statement.resources = resources; - bool isActual = statement.isValid(bucketName); - Assert.AreEqual(isActual, isExpected); - } - - } - - // Test Bucket Policy resource match - [TestMethod] - public void TestBucketPolicyResourceMatch() - { - string awsPrefix = PolicyConstants.AWS_RESOURCE_PREFIX; - - var testCases = new List, bool>>() - { - // Policy with resource ending with bucket /* allows access to all objects within given bucket. - new KeyValuePair,bool>(new List{ TestHelper.GenerateResourcesPrefix("minio-bucket",""), - TestHelper.GenerateStatement(awsPrefix + "minio-bucket/*"), - }, - true), - // Policy with resource ending with bucket/oo* should deny access to object named output.txt in that bucket - new KeyValuePair,bool>(new List{ TestHelper.GenerateResourcesPrefix("minio-bucket","output.txt"), - TestHelper.GenerateStatement(awsPrefix + "minio-bucket/oo*"), - }, - false), - // Policy with resource ending with bucket/oo* should allow access to object named ootput.txt in that bucket - - new KeyValuePair,bool>(new List{ TestHelper.GenerateResourcesPrefix("minio-bucket","ootput.txt"), - TestHelper.GenerateStatement(awsPrefix + "minio-bucket/oo*"), - }, - true), - // Policy with resource ending with bucket/oo* allows access to all subfolders starting with "oo" inside given bucket. - new KeyValuePair,bool>(new List{ TestHelper.GenerateResourcesPrefix("minio-bucket","oops/output.txt"), - TestHelper.GenerateStatement(awsPrefix + "minio-bucket/oo*"), - }, - true), - // Policy with resource subfolder not matching object subfolder. - new KeyValuePair,bool>(new List{ TestHelper.GenerateResourcesPrefix("minio-bucket","test/mybad/output.txt"), - TestHelper.GenerateStatement(awsPrefix + "minio-bucket/test/mybed/*"), - }, - false), - // Test names space flatness - new KeyValuePair,bool>(new List{ TestHelper.GenerateResourcesPrefix("minio-bucket","Asia/India/MountK2/trip/sunrise.jpg"), - TestHelper.GenerateStatement(awsPrefix + "minio-bucket/*/India/*/trip/*"), - }, - true), - new KeyValuePair,bool>(new List{ TestHelper.GenerateResourcesPrefix("minio-bucket","Asia/India/MountK2/trip/sunrise.jpg"), - TestHelper.GenerateStatement(awsPrefix + "minio-bucket/*/India/*/sunrise.jpg"), - }, - true), - }; - int index = 0; - foreach (KeyValuePair, bool> testCase in testCases) - { - index += 1; - List data = testCase.Key; - string resourcePrefix = (string)data[0]; - - Statement stmt = (Statement)data[1]; - - bool isExpected = testCase.Value; - - Resources matched = stmt.resources.Match(resourcePrefix); - bool isActualMatch = matched.SetEquals(stmt.resources); - Assert.AreEqual(isExpected, isActualMatch); - } - - } - [TestMethod] - public void TestGetPolicy() - { - var testCases = new List, PolicyType>>() - { - - // BucketPolicy NONE - empty statements, bucketname and prefix - new KeyValuePair,PolicyType>(new List - { new Statement(),"","" }, PolicyType.NONE), - - // BucketPolicy NONE - non empty statements, empty bucketname and empty prefix - new KeyValuePair,PolicyType>(new List - { TestHelper.GenerateStatement(PolicyConstants.READ_ONLY_BUCKET_ACTIONS, - resourcePrefix:"arn:aws:s3:::mybucket"), - "","" },PolicyType.NONE), - // BucketPolicy NONE - empty statements, nonempty bucketname and empty prefix - new KeyValuePair,PolicyType>(new List - { new Statement(),"mybucket","" }, PolicyType.NONE), - - // BucketPolicy NONE - empty statements, empty bucketname and nonempty prefix - new KeyValuePair,PolicyType>(new List - { new Statement(),"","" }, PolicyType.NONE), - - // Not matching statements - new KeyValuePair,PolicyType>(new List - { TestHelper.GenerateStatement(PolicyConstants.READ_ONLY_BUCKET_ACTIONS, - effect:"Allow", - aws:"*", - withConditions:false, - resourcePrefix:"arn:aws:s3:::mybucket" - ),"testbucket","" },PolicyType.NONE), - - // Not matching statements with prefix - new KeyValuePair,PolicyType>(new List - { TestHelper.GenerateStatement(PolicyConstants.READ_ONLY_BUCKET_ACTIONS, - effect:"Allow", - aws:"*", - withConditions:false, - resourcePrefix:"arn:aws:s3:::mybucket" - ),"mybucket","hello" },PolicyType.NONE), - // Statements with only common bucket actions - new KeyValuePair,PolicyType>(new List - { TestHelper.GenerateStatement(PolicyConstants.COMMON_BUCKET_ACTIONS, - effect:"Allow", - aws:"*", - withConditions:false, - resourcePrefix:"arn:aws:s3:::mybucket" - ),"mybucket","" },PolicyType.NONE), - // Statements with only common bucket actions with prefix - new KeyValuePair,PolicyType>(new List - { TestHelper.GenerateStatement(PolicyConstants.COMMON_BUCKET_ACTIONS, - effect:"Allow", - aws:"*", - withConditions:false, - resourcePrefix:"arn:aws:s3:::mybucket" - ),"mybucket","hello" },PolicyType.NONE), - // Statements with only readonlybucketactions - new KeyValuePair,PolicyType>(new List - { TestHelper.GenerateStatement(PolicyConstants.READ_ONLY_BUCKET_ACTIONS, - effect:"Allow", - aws:"*", - withConditions:false, - resourcePrefix:"arn:aws:s3:::mybucket" - ),"mybucket","" },PolicyType.NONE), - // Statements with only readonlybucketactions with prefix - new KeyValuePair,PolicyType>(new List - { TestHelper.GenerateStatement(PolicyConstants.READ_ONLY_BUCKET_ACTIONS, - effect:"Allow", - aws:"*", - withConditions:false, - resourcePrefix:"arn:aws:s3:::mybucket" - ),"mybucket","hello" },PolicyType.NONE), - // Statements with only readonlybucketactions with conditions - new KeyValuePair,PolicyType>(new List - { TestHelper.GenerateStatement(PolicyConstants.READ_ONLY_BUCKET_ACTIONS, - effect:"Allow", - aws:"*", - withConditions:true, - resourcePrefix:"arn:aws:s3:::mybucket" - ),"mybucket","" },PolicyType.NONE), - // Statements with only readonlybucketactions with prefix and conditions - new KeyValuePair,PolicyType>(new List - { TestHelper.GenerateStatement(PolicyConstants.READ_ONLY_BUCKET_ACTIONS, - effect:"Allow", - aws:"*", - withConditions:true, - resourcePrefix:"arn:aws:s3:::mybucket" - ),"mybucket","hello" },PolicyType.NONE), - // Statements with only writeonlybucketactions - new KeyValuePair,PolicyType>(new List - { TestHelper.GenerateStatement(PolicyConstants.WRITE_ONLY_BUCKET_ACTIONS, - effect:"Allow", - aws:"*", - withConditions:false, - resourcePrefix:"arn:aws:s3:::mybucket" - ),"mybucket","" },PolicyType.NONE), - // Statements with only writeonlybucketactions with prefix - new KeyValuePair,PolicyType>(new List - { TestHelper.GenerateStatement(PolicyConstants.WRITE_ONLY_BUCKET_ACTIONS, - effect:"Allow", - aws:"*", - withConditions:false, - resourcePrefix:"arn:aws:s3:::mybucket" - ),"mybucket","hello" },PolicyType.NONE), - // Statements with only writeonlybucketactions +readonlybucketactions - new KeyValuePair,PolicyType>(new List - { TestHelper.GenerateStatement(TestHelper.GetReadAndWriteBucketActions(), - effect:"Allow", - aws:"*", - withConditions:false, - resourcePrefix:"arn:aws:s3:::mybucket" - ),"mybucket","" },PolicyType.NONE), - // Statements with only writeonlybucketactions +readonlybucketactions and with prefix - new KeyValuePair,PolicyType>(new List - { TestHelper.GenerateStatement(TestHelper.GetReadAndWriteBucketActions(), - effect:"Allow", - aws:"*", - withConditions:false, - resourcePrefix:"arn:aws:s3:::mybucket" - ),"mybucket","hello" },PolicyType.NONE), - // Statements with only writeonlybucketactions +readonlybucketactions and with prefix and conditions - new KeyValuePair,PolicyType>(new List - { TestHelper.GenerateStatement(TestHelper.GetReadAndWriteBucketActions(), - effect:"Allow", - aws:"*", - withConditions:true, - resourcePrefix:"arn:aws:s3:::mybucket" - ),"mybucket","hello" },PolicyType.NONE), - }; - int index = 0; - foreach (KeyValuePair, PolicyType> testCase in testCases) - { - index += 1; - List data = testCase.Key; - Statement statement = (Statement)data[0]; - - string bucketName = (string)data[1]; - - string prefix = (string)data[2]; - PolicyType expectedResult = (PolicyType)testCase.Value; - BucketPolicy policy = new BucketPolicy(bucketName); - policy.SetStatements(statement); - - Assert.IsTrue(expectedResult.Equals(policy.GetPolicy(prefix))); - } - } - - [TestMethod] - public void TestGetBucketPolicy() - { - var testCases = new List, Tuple>>() - { - - // Statement with invalid effect - new KeyValuePair,Tuple>(new List - { TestHelper.GenerateStatement(PolicyConstants.READ_ONLY_BUCKET_ACTIONS, - effect:"Deny",resourcePrefix:"arn:aws:s3:::mybucket"), - "mybucket","" }, Tuple.Create(false,false,false)), - - // Statement with invalid effect with prefix - new KeyValuePair,Tuple>(new List - { TestHelper.GenerateStatement(PolicyConstants.READ_ONLY_BUCKET_ACTIONS, - effect:"Deny",resourcePrefix:"arn:aws:s3:::mybucket"), - "mybucket","hello" }, Tuple.Create(false,false,false) ), - - // Statement with invalid principal.aws - new KeyValuePair,Tuple>(new List - { TestHelper.GenerateStatement(PolicyConstants.READ_ONLY_BUCKET_ACTIONS, - effect:"Allow",aws:"arn:aws:iam::AccountNumberWithoutHyphens:root",resourcePrefix:"arn:aws:s3:::mybucket"), - "mybucket","" }, Tuple.Create(false,false,false)), - // Statement with invalid principal.aws with prefix - new KeyValuePair,Tuple>(new List - { TestHelper.GenerateStatement(PolicyConstants.READ_ONLY_BUCKET_ACTIONS, - effect:"Allow",aws:"arn:aws:iam::AccountNumberWithoutHyphens:root",resourcePrefix:"arn:aws:s3:::mybucket"), - "mybucket","hello" }, Tuple.Create(false,false,false)), - // Statement with common bucket actions - new KeyValuePair,Tuple>(new List - { TestHelper.GenerateStatement(PolicyConstants.COMMON_BUCKET_ACTIONS, - effect:"Allow",resourcePrefix:"arn:aws:s3:::mybucket"), - "mybucket","" }, Tuple.Create(true,false,false)), - // Statement with common bucket actions and prefix - new KeyValuePair,Tuple>(new List - { TestHelper.GenerateStatement(PolicyConstants.COMMON_BUCKET_ACTIONS, - effect:"Allow",resourcePrefix:"arn:aws:s3:::mybucket"), - "mybucket","hello" }, Tuple.Create(true,false,false)), - // Statement with common bucket actions and condition - new KeyValuePair,Tuple>(new List - { TestHelper.GenerateStatement(PolicyConstants.COMMON_BUCKET_ACTIONS, - effect:"Allow",resourcePrefix:"arn:aws:s3:::mybucket", withConditions:true), - "mybucket","hello" }, Tuple.Create(false,false,false)), - - // Statement with writeonly bucket actions - new KeyValuePair,Tuple>(new List - { TestHelper.GenerateStatement(PolicyConstants.WRITE_ONLY_BUCKET_ACTIONS, - effect:"Allow",resourcePrefix:"arn:aws:s3:::mybucket", withConditions:false), - "mybucket","" }, Tuple.Create(false,false,true)), - // Statement with writeonly bucket actions - new KeyValuePair,Tuple>(new List - { TestHelper.GenerateStatement(PolicyConstants.WRITE_ONLY_BUCKET_ACTIONS, - effect:"Allow",resourcePrefix:"arn:aws:s3:::mybucket", withConditions:false), - "mybucket","hello" }, Tuple.Create(false,false,true)), - - // Statement with writeonly bucket actions with condition and no prefix - new KeyValuePair,Tuple>(new List - { TestHelper.GenerateStatement(PolicyConstants.WRITE_ONLY_BUCKET_ACTIONS, - effect:"Allow",resourcePrefix:"arn:aws:s3:::mybucket", withConditions:true), - "mybucket","" }, Tuple.Create(false,false,false)), - // Statement with writeonly bucket actions with condition and prefix - new KeyValuePair,Tuple>(new List - { TestHelper.GenerateStatement(PolicyConstants.WRITE_ONLY_BUCKET_ACTIONS, - effect:"Allow",resourcePrefix:"arn:aws:s3:::mybucket", withConditions:true), - "mybucket","hello" }, Tuple.Create(false,false,false)), - - // Statement with Readonly bucket actions - new KeyValuePair,Tuple>(new List - { TestHelper.GenerateStatement(PolicyConstants.READ_ONLY_BUCKET_ACTIONS, - effect:"Allow",resourcePrefix:"arn:aws:s3:::mybucket", withConditions:false), - "mybucket","" }, Tuple.Create(false,true,false)), - - // Statement with Readonly bucket actions and prefix - new KeyValuePair,Tuple>(new List - { TestHelper.GenerateStatement(PolicyConstants.READ_ONLY_BUCKET_ACTIONS, - effect:"Allow",resourcePrefix:"arn:aws:s3:::mybucket", withConditions:false), - "mybucket","hello" }, Tuple.Create(false,true,false)), - // Statement with Readonly bucket actions with condition - new KeyValuePair,Tuple>(new List - { TestHelper.GenerateStatement(PolicyConstants.READ_ONLY_BUCKET_ACTIONS, - effect:"Allow",resourcePrefix:"arn:aws:s3:::mybucket", withConditions:true, withStringSet:null), - "mybucket","" }, Tuple.Create(false,false,false)), - - // Statement with Readonly bucket actions with empty condition and prefix - new KeyValuePair,Tuple>(new List - { TestHelper.GenerateStatement(PolicyConstants.READ_ONLY_BUCKET_ACTIONS, - effect:"Allow",resourcePrefix:"arn:aws:s3:::mybucket", withConditions:true, withStringSet:null), - "mybucket","hello" }, Tuple.Create(false,false,false)), - - // Statement with Readonly bucket actions with matching condition and no prefix - new KeyValuePair,Tuple>(new List - { TestHelper.GenerateStatement(PolicyConstants.READ_ONLY_BUCKET_ACTIONS, - effect:"Allow",resourcePrefix:"arn:aws:s3:::mybucket", withConditions:true,withStringSet:"hello"), - "mybucket","" }, Tuple.Create(false,false,false)), - - - // Statement with Readonly bucket actions with matching condition and prefix - new KeyValuePair,Tuple>(new List - { TestHelper.GenerateStatement(PolicyConstants.READ_ONLY_BUCKET_ACTIONS, - effect:"Allow",resourcePrefix:"arn:aws:s3:::mybucket", withConditions:true,withStringSet:"hello"), - "mybucket","hello" }, Tuple.Create(false,true,false)), - // Statement with Readonly bucket actions with different condition - new KeyValuePair,Tuple>(new List - { TestHelper.GenerateStatement(PolicyConstants.READ_ONLY_BUCKET_ACTIONS, - effect:"Allow",resourcePrefix:"arn:aws:s3:::mybucket", withConditions:true,withStringSet:"world"), - "mybucket","" }, Tuple.Create(false,false,false)), - // Statement with Readonly bucket actions with different condition - new KeyValuePair,Tuple>(new List - { TestHelper.GenerateStatement(PolicyConstants.READ_ONLY_BUCKET_ACTIONS, - effect:"Allow",resourcePrefix:"arn:aws:s3:::mybucket", withConditions:true,withStringSet:"world"), - "mybucket","hello" }, Tuple.Create(false,false,false)), - // Statement with Readonly bucket actions with StringNotEquals condition - new KeyValuePair,Tuple>(new List - { TestHelper.GenerateStatement(PolicyConstants.READ_ONLY_BUCKET_ACTIONS, - effect:"Allow",resourcePrefix:"arn:aws:s3:::mybucket", withConditions:true,withStringSet:"hello",condition:"StringNotEquals"), - "mybucket","" }, Tuple.Create(false,false,false)), - - // Statement with Readonly bucket actions with StringNotEquals condition - new KeyValuePair,Tuple>(new List - { TestHelper.GenerateStatement(PolicyConstants.READ_ONLY_BUCKET_ACTIONS, - effect:"Allow",resourcePrefix:"arn:aws:s3:::mybucket", withConditions:true,withStringSet:"hello",condition:"StringNotEquals"), - "mybucket","" }, Tuple.Create(false,false,false)), - - // Statement with Readonly bucket actions with StringNotEquals condition - new KeyValuePair,Tuple>(new List - { TestHelper.GenerateStatement(PolicyConstants.READ_ONLY_BUCKET_ACTIONS, - effect:"Allow",resourcePrefix:"arn:aws:s3:::mybucket", withConditions:true,withStringSet:"hello",condition:"StringNotEquals"), - "mybucket","hello" }, Tuple.Create(false,false,false)), - new KeyValuePair,Tuple>(new List - { TestHelper.GenerateStatement(PolicyConstants.READ_ONLY_BUCKET_ACTIONS, - effect:"Allow",resourcePrefix:"arn:aws:s3:::mybucket", withConditions:true,withStringSet:"hello",condition:"StringNotEquals"), - "mybucket","world" }, Tuple.Create(false,true,false)), - - }; - int index = 0; - foreach (KeyValuePair, Tuple> testCase in testCases) - { - index += 1; - List data = testCase.Key; - Statement statement = (Statement)data[0]; - string bucketName = (string)data[1]; - - string prefix = (string)data[2]; - Tuple expectedResult = testCase.Value; - bool[] actualResult = statement.getBucketPolicy(prefix); - - Assert.IsTrue(expectedResult.Item1.Equals(actualResult[0])); - Assert.IsTrue(expectedResult.Item2.Equals(actualResult[1])); - - Assert.IsTrue(expectedResult.Item3.Equals(actualResult[2])); - - } - } - - [TestMethod] - public void TestGetObjectPolicy() - { - var testCases = new List, Tuple>>() - { - - // Statement with invalid effect - new KeyValuePair,Tuple>(new List - { TestHelper.GenerateStatement(PolicyConstants.READ_ONLY_OBJECT_ACTIONS, - effect:"Deny",resourcePrefix:"arn:aws:s3:::mybucket/hello*"), - "mybucket","" }, Tuple.Create(false,false)), - // Statement with invalid Principal AWS - new KeyValuePair,Tuple>(new List - { TestHelper.GenerateStatement(PolicyConstants.READ_ONLY_OBJECT_ACTIONS, - effect:"Allow",aws:"arn:aws:iam::AccountNumberWithoutHyphens:root",resourcePrefix:"arn:aws:s3:::mybucket/hello*"), - "mybucket","" }, Tuple.Create(false,false)), - // Statement with condition - new KeyValuePair,Tuple>(new List - { TestHelper.GenerateStatement(PolicyConstants.READ_ONLY_OBJECT_ACTIONS, - effect:"Allow", - withConditions:true,condition: null, - resourcePrefix:"arn:aws:s3:::mybucket/hello*"), - "mybucket","" }, Tuple.Create(false,false)), - // Statement with readonlyobjectactions - new KeyValuePair,Tuple>(new List - { TestHelper.GenerateStatement(PolicyConstants.READ_ONLY_OBJECT_ACTIONS, - effect:"Allow", - resourcePrefix:"arn:aws:s3:::mybucket/hello*"), - "mybucket","" }, Tuple.Create(true,false)), - // Statement with writeonlyobjectactions - new KeyValuePair,Tuple>(new List - { TestHelper.GenerateStatement(PolicyConstants.WRITE_ONLY_OBJECT_ACTIONS, - effect:"Allow", - resourcePrefix:"arn:aws:s3:::mybucket/hello*"), - "mybucket","" }, Tuple.Create(false,true)), - // Statement with writeonlyobjectactions - new KeyValuePair,Tuple>(new List - { TestHelper.GenerateStatement(PolicyConstants.READ_WRITE_OBJECT_ACTIONS(), - effect:"Allow", - resourcePrefix:"arn:aws:s3:::mybucket/hello*"), - "mybucket","" }, Tuple.Create(true,true)), - }; - int index = 0; - foreach (KeyValuePair, Tuple> testCase in testCases) - { - index += 1; - List data = testCase.Key; - Statement statement = (Statement)data[0]; - string bucketName = (string)data[1]; - - string prefix = (string)data[2]; - Tuple expectedResult = testCase.Value; - bool[] actualResult = statement.getObjectPolicy(); - - Assert.IsTrue(expectedResult.Item1.Equals(actualResult[0])); - Assert.IsTrue(expectedResult.Item2.Equals(actualResult[1])); - } - } - - [TestMethod] - public void TestGetPolicies() - { - - var testCases = new List, Dictionary>>() - { - - // BucketPolicy NONE - empty statements, bucketname and prefix - new KeyValuePair,Dictionary>(new List - { new List{new Statement() },""}, new Dictionary{}), - - // BucketPolicy NONE - non empty statements, empty bucketname and empty prefix - new KeyValuePair,Dictionary>(new List - { new List{TestHelper.GenerateStatement(PolicyConstants.READ_ONLY_BUCKET_ACTIONS, - resourcePrefix:"arn:aws:s3:::mybucket") }, - "","" },new Dictionary{}), - // BucketPolicy NONE - empty statements, nonempty bucketname and empty prefix - new KeyValuePair,Dictionary>(new List - { new List{new Statement() },"mybucket","" }, new Dictionary{}), - - // BucketPolicy NONE - empty statements, empty bucketname and nonempty prefix - new KeyValuePair,Dictionary>(new List - { new List{new Statement() },"","" }, new Dictionary{}), - - // Statements with read bucket actions - new KeyValuePair,Dictionary>(new List - { new List{TestHelper.GenerateStatement(PolicyConstants.COMMON_BUCKET_ACTIONS, - effect:"Allow", - aws:"*", - withConditions:false, - resourcePrefix:"arn:aws:s3:::mybucket" - ) , - TestHelper.GenerateStatement(PolicyConstants.READ_ONLY_BUCKET_ACTIONS, - effect:"Allow", - aws:"*", - withConditions:true, - withStringSet: "download", - resourcePrefix:"arn:aws:s3:::mybucket" - ), - TestHelper.GenerateStatement(PolicyConstants.READ_ONLY_OBJECT_ACTIONS, - effect:"Allow", - aws:"*", - withConditions:false, - resourcePrefix: "arn:aws:s3:::mybucket/download*" - ) - },"mybucket","" },new Dictionary{{"mybucket/download*",PolicyType.READ_ONLY }}), - // Statements with write only bucket actions - new KeyValuePair,Dictionary>(new List - { new List{TestHelper.GenerateStatement(PolicyConstants.COMMON_BUCKET_ACTIONS, - effect:"Allow", - aws:"*", - withConditions:false, - resourcePrefix:"arn:aws:s3:::mybucket" - ) , - TestHelper.GenerateStatement(PolicyConstants.WRITE_ONLY_BUCKET_ACTIONS, - effect:"Allow", - aws:"*", - withConditions:false, - withStringSet: "download", - resourcePrefix:"arn:aws:s3:::mybucket" - ), - TestHelper.GenerateStatement(PolicyConstants.WRITE_ONLY_OBJECT_ACTIONS, - effect:"Allow", - aws:"*", - withConditions:false, - resourcePrefix: "arn:aws:s3:::mybucket/upload*" - ) - },"mybucket","" },new Dictionary{{"mybucket/upload*",PolicyType.WRITE_ONLY }}), - // Statements with read-write bucket actions - new KeyValuePair,Dictionary>(new List - { new List{TestHelper.GenerateStatement(PolicyConstants.COMMON_BUCKET_ACTIONS, - effect:"Allow", - aws:"*", - withConditions:false, - resourcePrefix:"arn:aws:s3:::mybucket" - ) , - TestHelper.GenerateStatement(PolicyConstants.READ_ONLY_BUCKET_ACTIONS, - effect:"Allow", - aws:"*", - withConditions:true, - withStringSet: "both", - resourcePrefix:"arn:aws:s3:::mybucket" - ), - TestHelper.GenerateStatement(PolicyConstants.WRITE_ONLY_BUCKET_ACTIONS, - effect:"Allow", - aws:"*", - resourcePrefix:"arn:aws:s3:::mybucket" - ), - TestHelper.GenerateStatement(PolicyConstants.WRITE_ONLY_OBJECT_ACTIONS, - effect:"Allow", - aws:"*", - withConditions:false, - resourcePrefix: "arn:aws:s3:::mybucket/both*" - ), - TestHelper.GenerateStatement(PolicyConstants.READ_ONLY_OBJECT_ACTIONS, - effect:"Allow", - aws:"*", - withConditions:false, - resourcePrefix: "arn:aws:s3:::mybucket/both*" - ) - },"mybucket","" },new Dictionary{{"mybucket/both*",PolicyType.READ_WRITE }}) - }; - int index = 0; - foreach (KeyValuePair, Dictionary> testCase in testCases) - { - index += 1; - List data = testCase.Key; - List statements = (List)data[0]; - - string bucketName = (string)data[1]; - Dictionary expectedResult = testCase.Value; - BucketPolicy policy = new BucketPolicy(bucketName); - foreach (Statement statement in statements) - policy.statements.Add(statement); - Dictionary actualResult = policy.GetPolicies(); - Assert.IsTrue(expectedResult.PoliciesEqual(policy.GetPolicies())); - } - } - - - - [TestMethod] - public void TestSetPolicy() - { - var testCases = new List, string>>() - { - - // BucketPolicy NONE - empty statements, bucketname and prefix - new KeyValuePair,string>(new List - { @"{""Statement"":[]}", - PolicyType.NONE,"","" }, @"{""Version"":""2012-10-17"",""Statement"":[]}"), - - // BucketPolicy NONE - non empty statements, empty bucketname and prefix - new KeyValuePair,string>(new List - { @"{""Statement"":[{""Action"":[""s3:ListBucket""],""Effect"":""Allow"",""Principal"":{""AWS"":["" * ""]},""Resource"":[""arn: aws: s3:::mybucket""],""Sid"":""""}]}", - PolicyType.NONE,"","" },@"{""Version"":""2012-10-17"",""Statement"":[{""Action"":[""s3:ListBucket""],""Effect"":""Allow"",""Principal"":{""AWS"":["" * ""]},""Resource"":[""arn: aws: s3:::mybucket""],""Sid"":""""}]}" ), - // BucketPolicy NONE - empty statements, nonempty bucketname and prefix - new KeyValuePair,string>(new List - { @"{""Statement"":[]}", - PolicyType.NONE,"mybucket","" }, @"{""Version"":""2012-10-17"",""Statement"":[]}"), - - // Bucket policy NONE , empty statements , bucketname, nonempty prefix - new KeyValuePair,string>(new List - { @"{""Statement"":[]}", - PolicyType.NONE,"","prefix" }, @"{""Version"":""2012-10-17"",""Statement"":[]}"), - // BucketPolicy READONLY - empty statements, bucket name and prefix. - new KeyValuePair,string>(new List - { @"{""Statement"":[]}", - PolicyType.READ_ONLY,"","" }, @"{""Version"":""2012-10-17"",""Statement"":[]}"), - // Bucket policy READONLY , nonempty statements , bucketname and prefix - no change to existing bucketpolicy - new KeyValuePair,string>(new List - { @"{""Statement"":[{""Action"":[""s3:ListBucket""],""Effect"":""Allow"",""Principal"":{""AWS"":["" * ""]},""Resource"":[""arn: aws: s3:::mybucket""],""Sid"":""""}]}", - PolicyType.READ_ONLY,"","" }, @"{""Version"":""2012-10-17"",""Statement"":[{""Action"":[""s3:ListBucket""],""Effect"":""Allow"",""Principal"":{""AWS"":["" * ""]},""Resource"":[""arn: aws: s3:::mybucket""],""Sid"":""""}]}"), - - // BucketPolicy READONLY - empty statements, empty bucket name and prefix. - new KeyValuePair,string>(new List - { @"{""Statement"":[]}", - PolicyType.READ_ONLY,"mybucket","" }, @"{""Version"":""2012-10-17"",""Statement"":[{""Action"":[""s3:GetBucketLocation""],""Effect"":""Allow"",""Principal"":{""AWS"":[""*""]},""Resource"":[""arn:aws:s3:::mybucket""],""Sid"":""""},{""Action"":[""s3:ListBucket""],""Effect"":""Allow"",""Principal"":{""AWS"":[""*""]},""Resource"":[""arn:aws:s3:::mybucket""],""Sid"":""""},{""Action"":[""s3:GetObject""],""Effect"":""Allow"",""Principal"":{""AWS"":[""*""]},""Resource"":[""arn:aws:s3:::mybucket/*""],""Sid"":""""}]}"), - // BucketPolicy Writeonly - empty statements, bucket name and prefix. - new KeyValuePair,string>(new List - { @"{""Statement"":[]}", - PolicyType.WRITE_ONLY,"","" }, @"{""Version"":""2012-10-17"",""Statement"":[]}"), - // BucketPolicy Writeonly - empty statements, empty bucket name and non-empty prefix. - new KeyValuePair,string>(new List - { @"{""Statement"":[]}", - PolicyType.WRITE_ONLY,"","hello" }, @"{""Version"":""2012-10-17"",""Statement"":[]}"), - - // Bucket policy WRITEONLY , nonempty statements , empty bucketname and prefix - no change to existing bucketpolicy - new KeyValuePair,string>(new List - { @"{""Statement"":[{""Action"":[""s3:ListBucket""],""Effect"":""Allow"",""Principal"":{""AWS"":["" * ""]},""Resource"":[""arn: aws: s3:::mybucket""],""Sid"":""""}]}", - PolicyType.WRITE_ONLY,"","" }, @"{""Version"":""2012-10-17"",""Statement"":[{""Action"":[""s3:ListBucket""],""Effect"":""Allow"",""Principal"":{""AWS"":["" * ""]},""Resource"":[""arn: aws: s3:::mybucket""],""Sid"":""""}]}"), - // BucketPolicy WRITEONLY - empty statements, non-empty bucket name and prefix. - new KeyValuePair,string>(new List - { @"{""Statement"":[]}", - PolicyType.WRITE_ONLY,"mybucket","" }, @"{""Version"":""2012-10-17"",""Statement"":[{""Action"":[""s3:GetBucketLocation""],""Effect"":""Allow"",""Principal"":{""AWS"":[""*""]},""Resource"":[""arn:aws:s3:::mybucket""],""Sid"":""""},{""Action"":[""s3:ListBucketMultipartUploads""],""Effect"":""Allow"",""Principal"":{""AWS"":[""*""]},""Resource"":[""arn:aws:s3:::mybucket""],""Sid"":""""},{""Action"":[""s3:AbortMultipartUpload"",""s3:DeleteObject"",""s3:ListMultipartUploadParts"",""s3:PutObject""],""Effect"":""Allow"",""Principal"":{""AWS"":[""*""]},""Resource"":[""arn:aws:s3:::mybucket/*""],""Sid"":""""}]}"), - // BucketPolicy WRITEONLY - empty statements, non-empty bucket name and prefix. - new KeyValuePair,string>(new List - { @"{""Statement"":[]}", - PolicyType.WRITE_ONLY,"mybucket","" }, @"{""Version"":""2012-10-17"",""Statement"":[{""Action"":[""s3:GetBucketLocation""],""Effect"":""Allow"",""Principal"":{""AWS"":[""*""]},""Resource"":[""arn:aws:s3:::mybucket""],""Sid"":""""},{""Action"":[""s3:ListBucketMultipartUploads""],""Effect"":""Allow"",""Principal"":{""AWS"":[""*""]},""Resource"":[""arn:aws:s3:::mybucket""],""Sid"":""""},{""Action"":[""s3:AbortMultipartUpload"",""s3:DeleteObject"",""s3:ListMultipartUploadParts"",""s3:PutObject""],""Effect"":""Allow"",""Principal"":{""AWS"":[""*""]},""Resource"":[""arn:aws:s3:::mybucket/*""],""Sid"":""""}]}"), - // BucketPolicy WRITEONLY - empty statements, non-empty bucket name and prefix. - new KeyValuePair,string>(new List - { @"{""Statement"":[]}", - PolicyType.WRITE_ONLY,"mybucket","hello" }, @"{""Version"":""2012-10-17"",""Statement"":[{""Action"":[""s3:GetBucketLocation""],""Effect"":""Allow"",""Principal"":{""AWS"":[""*""]},""Resource"":[""arn:aws:s3:::mybucket""],""Sid"":""""},{""Action"":[""s3:ListBucketMultipartUploads""],""Effect"":""Allow"",""Principal"":{""AWS"":[""*""]},""Resource"":[""arn:aws:s3:::mybucket""],""Sid"":""""},{""Action"":[""s3:AbortMultipartUpload"",""s3:DeleteObject"",""s3:ListMultipartUploadParts"",""s3:PutObject""],""Effect"":""Allow"",""Principal"":{""AWS"":[""*""]},""Resource"":[""arn:aws:s3:::mybucket/hello*""],""Sid"":""""}]}"), - - // BucketPolicy READWRITE - empty statements, empty bucket name and prefix. - new KeyValuePair,string>(new List - { @"{""Statement"":[]}", - PolicyType.READ_WRITE,"mybucket","" }, @"{""Version"":""2012-10-17"",""Statement"":[{""Action"":[""s3:GetBucketLocation""],""Effect"":""Allow"",""Principal"":{""AWS"":[""*""]},""Resource"":[""arn:aws:s3:::mybucket""],""Sid"":""""},{""Action"":[""s3:ListBucket""],""Effect"":""Allow"",""Principal"":{""AWS"":[""*""]},""Resource"":[""arn:aws:s3:::mybucket""],""Sid"":""""},{""Action"":[""s3:ListBucketMultipartUploads""],""Effect"":""Allow"",""Principal"":{""AWS"":[""*""]},""Resource"":[""arn:aws:s3:::mybucket""],""Sid"":""""},{""Action"":[""s3:GetObject"",""s3:AbortMultipartUpload"",""s3:DeleteObject"",""s3:ListMultipartUploadParts"",""s3:PutObject""],""Effect"":""Allow"",""Principal"":{""AWS"":[""*""]},""Resource"":[""arn:aws:s3:::mybucket/*""],""Sid"":""""}]}"), - // BucketPolicy RERADWRITE - empty statements, bucket name and prefix. - new KeyValuePair,string>(new List - { @"{""Statement"":[]}", - PolicyType.READ_WRITE,"","" }, @"{""Version"":""2012-10-17"",""Statement"":[]}"), - // BucketPolicy READWRITE - empty statements, empty bucket name and non-empty prefix. - new KeyValuePair,string>(new List - { @"{""Statement"":[]}", - PolicyType.READ_WRITE,"","" }, @"{""Version"":""2012-10-17"",""Statement"":[]}"), - - // Bucket policy READWRITE , nonempty statements , empty bucketname and prefix - no change to existing bucketpolicy - new KeyValuePair,string>(new List - { @"{""Statement"":[{""Action"":[""s3:ListBucket""],""Effect"":""Allow"",""Principal"":{""AWS"":["" * ""]},""Resource"":[""arn: aws: s3:::mybucket""],""Sid"":""""}]}", - PolicyType.READ_WRITE,"","" }, @"{""Version"":""2012-10-17"",""Statement"":[{""Action"":[""s3:ListBucket""],""Effect"":""Allow"",""Principal"":{""AWS"":["" * ""]},""Resource"":[""arn: aws: s3:::mybucket""],""Sid"":""""}]}"), - // BucketPolicy WRITEONLY - empty statements, non-empty bucket name and prefix. - new KeyValuePair,string>(new List - { @"{""Statement"":[]}", - PolicyType.READ_WRITE,"mybucket","" }, @"{""Version"":""2012-10-17"",""Statement"":[{""Action"":[""s3:GetBucketLocation""],""Effect"":""Allow"",""Principal"":{""AWS"":[""*""]},""Resource"":[""arn:aws:s3:::mybucket""],""Sid"":""""},{""Action"":[""s3:ListBucket""],""Effect"":""Allow"",""Principal"":{""AWS"":[""*""]},""Resource"":[""arn:aws:s3:::mybucket""],""Sid"":""""},{""Action"":[""s3:ListBucketMultipartUploads""],""Effect"":""Allow"",""Principal"":{""AWS"":[""*""]},""Resource"":[""arn:aws:s3:::mybucket""],""Sid"":""""},{""Action"":[""s3:GetObject"",""s3:AbortMultipartUpload"",""s3:DeleteObject"",""s3:ListMultipartUploadParts"",""s3:PutObject""],""Effect"":""Allow"",""Principal"":{""AWS"":[""*""]},""Resource"":[""arn:aws:s3:::mybucket/*""],""Sid"":""""}]}"), - // BucketPolicy WRITEONLY - empty statements, non-empty bucket name and prefix. - new KeyValuePair,string>(new List - { @"{""Statement"":[]}", - PolicyType.READ_WRITE,"mybucket","" }, @"{""Version"":""2012-10-17"",""Statement"":[{""Action"":[""s3:GetBucketLocation""],""Effect"":""Allow"",""Principal"":{""AWS"":[""*""]},""Resource"":[""arn:aws:s3:::mybucket""],""Sid"":""""},{""Action"":[""s3:ListBucket""],""Effect"":""Allow"",""Principal"":{""AWS"":[""*""]},""Resource"":[""arn:aws:s3:::mybucket""],""Sid"":""""},{""Action"":[""s3:ListBucketMultipartUploads""],""Effect"":""Allow"",""Principal"":{""AWS"":[""*""]},""Resource"":[""arn:aws:s3:::mybucket""],""Sid"":""""},{""Action"":[""s3:GetObject"",""s3:AbortMultipartUpload"",""s3:DeleteObject"",""s3:ListMultipartUploadParts"",""s3:PutObject""],""Effect"":""Allow"",""Principal"":{""AWS"":[""*""]},""Resource"":[""arn:aws:s3:::mybucket/*""],""Sid"":""""}]}"), - // BucketPolicy WRITEONLY - empty statements, non-empty bucket name and prefix. - new KeyValuePair,string>(new List - { @"{""Statement"":[]}", - PolicyType.READ_WRITE,"mybucket","hello" }, @"{""Version"":""2012-10-17"",""Statement"":[{""Action"":[""s3:GetBucketLocation""],""Effect"":""Allow"",""Principal"":{""AWS"":[""*""]},""Resource"":[""arn:aws:s3:::mybucket""],""Sid"":""""},{""Action"":[""s3:ListBucket""],""Condition"":{""StringEquals"":{""s3:prefix"":[""hello""]}},""Effect"":""Allow"",""Principal"":{""AWS"":[""*""]},""Resource"":[""arn:aws:s3:::mybucket""],""Sid"":""""},{""Action"":[""s3:ListBucketMultipartUploads""],""Effect"":""Allow"",""Principal"":{""AWS"":[""*""]},""Resource"":[""arn:aws:s3:::mybucket""],""Sid"":""""},{""Action"":[""s3:GetObject"",""s3:AbortMultipartUpload"",""s3:DeleteObject"",""s3:ListMultipartUploadParts"",""s3:PutObject""],""Effect"":""Allow"",""Principal"":{""AWS"":[""*""]},""Resource"":[""arn:aws:s3:::mybucket/hello*""],""Sid"":""""}]}"), - - }; - int index = 0; - foreach (KeyValuePair, string> testCase in testCases) - { - index += 1; - List data = testCase.Key; - PolicyType policyType = (PolicyType)data[1]; - string bucketName = (string)data[2]; - string prefix = (string)data[3]; - BucketPolicy currentpolicy = TestHelper.GenerateBucketPolicy((string)data[0], bucketName); - currentpolicy.SetPolicy(policyType, prefix); - string expectedResult = testCase.Value; - string policyJSON = currentpolicy.GetJson(); - Assert.AreEqual(expectedResult, policyJSON); - } - } - - - } -} diff --git a/Minio.Tests/TestHelper.cs b/Minio.Tests/TestHelper.cs index 1a97a1dce..7c5c1c1f4 100644 --- a/Minio.Tests/TestHelper.cs +++ b/Minio.Tests/TestHelper.cs @@ -15,7 +15,6 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using Minio.DataModel; -using Minio.DataModel.Policy; using System; using System.Collections.Generic; using System.IO; @@ -40,57 +39,5 @@ public static String GetRandomName(int length = 5) } return result.ToString(); } - - // Generate an empty statement - internal static Statement GenerateStatement(string resource) - { - Statement stmt = new Statement(); - stmt.resources = new Resources(resource); - return stmt; - } - - // Generate a resource prefix - internal static string GenerateResourcesPrefix(string bucketName, string objectName) - { - return PolicyConstants.AWS_RESOURCE_PREFIX + bucketName + "/" + objectName; - } - - // Generate a new statement - internal static Statement GenerateStatement(List actions,string resourcePrefix, string effect = "Allow", string aws = "*",bool withConditions=false,string withStringSet="hello",string condition="StringEquals") - { - Statement stmt = new Statement(); - stmt.resources = new Resources(resourcePrefix); - stmt.actions = actions; - stmt.effect = effect; - stmt.principal = new Principal(aws); - if (withConditions) - { - stmt.conditions = new ConditionMap(); - ConditionKeyMap ckmap = new ConditionKeyMap(); - if (withStringSet != null) - ckmap.Add("s3:prefix", new HashSet() {withStringSet }); - if (condition != null && ckmap != null) - stmt.conditions.Add(condition, ckmap); - } - - return stmt; - } - // Get List with Read and Write bucket actions - internal static List GetReadAndWriteBucketActions() - { - List res = new List(); - res.AddRange(PolicyConstants.READ_ONLY_BUCKET_ACTIONS); - res.AddRange(PolicyConstants.WRITE_ONLY_BUCKET_ACTIONS); - return res; - } - // Hydrate a bucket policy from JSON string - internal static BucketPolicy GenerateBucketPolicy(string policyString,string bucketName) - { - var contentBytes = System.Text.Encoding.UTF8.GetBytes(policyString); - var stream = new MemoryStream(contentBytes); - return BucketPolicy.ParseJson(stream, bucketName); - - } - } } diff --git a/Minio.core.nuspec b/Minio.core.nuspec index 1446d022a..fddd10b57 100644 --- a/Minio.core.nuspec +++ b/Minio.core.nuspec @@ -2,7 +2,7 @@ Minio.NetCore - 1.0.8 + 1.1.0 Minio, Inc. Minio, Inc http://www.apache.org/licenses/LICENSE-2.0.html diff --git a/Minio.nuspec b/Minio.nuspec index 9becb1399..5d9fcdfb9 100644 --- a/Minio.nuspec +++ b/Minio.nuspec @@ -2,7 +2,7 @@ Minio - 1.0.8 + 1.1.0 Minio, Inc. Minio, Inc http://www.apache.org/licenses/LICENSE-2.0.html diff --git a/Minio/ApiEndpoints/BucketOperations.cs b/Minio/ApiEndpoints/BucketOperations.cs index 1f06e3fbd..b6082e67b 100644 --- a/Minio/ApiEndpoints/BucketOperations.cs +++ b/Minio/ApiEndpoints/BucketOperations.cs @@ -245,10 +245,9 @@ public partial class MinioClient : IBucketOperations /// /// Bucket name. /// Optional cancellation token to cancel the operation - /// Task that returns the Bucket policy - private async Task GetPolicyAsync(string bucketName, CancellationToken cancellationToken = default(CancellationToken)) + /// Task that returns the Bucket policy as a json string + public async Task GetPolicyAsync(string bucketName, CancellationToken cancellationToken = default(CancellationToken)) { - BucketPolicy policy = null; IRestResponse response = null; var path = bucketName + "?policy"; @@ -256,60 +255,26 @@ public partial class MinioClient : IBucketOperations var request = await this.CreateRequest(Method.GET, bucketName, contentType: "application/json", resourcePath: "?policy"); - try - { - response = await this.ExecuteTaskAsync(this.NoErrorHandlers, request, cancellationToken); - var contentBytes = System.Text.Encoding.UTF8.GetBytes(response.Content); - - using (var stream = new MemoryStream(contentBytes)) - { - policy = BucketPolicy.ParseJson(stream, bucketName); - } + string policyString = null; + response = await this.ExecuteTaskAsync(this.NoErrorHandlers, request, cancellationToken); + var contentBytes = System.Text.Encoding.UTF8.GetBytes(response.Content); - } - catch (ErrorResponseException e) - { - // Ignore if there is - if (!e.Response.Code.Equals("NoSuchBucketPolicy")) - { - throw e; - } - } - finally + using (var stream = new MemoryStream(contentBytes)) { - if (policy == null) - { - policy = new BucketPolicy(bucketName); - } + policyString = new StreamReader(stream).ReadToEnd(); } - return policy; + return policyString; } - /// - /// Get bucket policy at given objectPrefix - /// - /// Bucket name. - /// Name of the object prefix - /// Optional cancellation token to cancel the operation - /// Task that returns the PolicyType - public async Task GetPolicyAsync(string bucketName, string objectPrefix = "", CancellationToken cancellationToken = default(CancellationToken)) - { - BucketPolicy policy = await GetPolicyAsync(bucketName, cancellationToken); - return policy.GetPolicy(objectPrefix); - } - - /// - /// Internal method that sets the bucket access policy + /// Sets the current bucket policy /// - /// Bucket Name. - /// Valid Json policy object + /// Bucket Name + /// Policy json as string /// Optional cancellation token to cancel the operation - /// Task that sets policy - private async Task setPolicyAsync(string bucketName, BucketPolicy policy, CancellationToken cancellationToken = default(CancellationToken)) + /// Task to set a policy + public async Task SetPolicyAsync(String bucketName, String policyJson, CancellationToken cancellationToken = default(CancellationToken)) { - - string policyJson = policy.GetJson(); var request = await this.CreateRequest(Method.PUT, bucketName, resourcePath: "?policy", contentType: "application/json", @@ -318,30 +283,6 @@ public partial class MinioClient : IBucketOperations IRestResponse response = await this.ExecuteTaskAsync(this.NoErrorHandlers, request, cancellationToken); } - /// - /// Sets the current bucket policy - /// - /// Bucket Name - /// Name of the object prefix. - /// Desired Policy type change - /// Optional cancellation token to cancel the operation - /// Task to set a policy - public async Task SetPolicyAsync(String bucketName, String objectPrefix, PolicyType policyType, CancellationToken cancellationToken = default(CancellationToken)) - { - utils.validateObjectPrefix(objectPrefix); - BucketPolicy policy = await GetPolicyAsync(bucketName, cancellationToken); - if (policyType == PolicyType.NONE && policy.Statements() == null) - { - // As the request is for removing policy and the bucket - // has empty policy statements, just return success. - return; - } - - policy.SetPolicy(policyType, objectPrefix); - - await setPolicyAsync(bucketName, policy, cancellationToken); - } - /// /// Gets notification configuration for this bucket /// diff --git a/Minio/ApiEndpoints/IBucketOperations.cs b/Minio/ApiEndpoints/IBucketOperations.cs index 13a91d97e..8ac23e4bb 100644 --- a/Minio/ApiEndpoints/IBucketOperations.cs +++ b/Minio/ApiEndpoints/IBucketOperations.cs @@ -64,23 +64,21 @@ public interface IBucketOperations IObservable ListObjectsAsync(string bucketName, string prefix = null, bool recursive = true, CancellationToken cancellationToken = default(CancellationToken)); /// - /// Get bucket policy at given objectPrefix + /// Get bucket policy /// /// Bucket name. - /// Name of the object prefix /// Optional cancellation token to cancel the operation - /// Returns Task - Task GetPolicyAsync(String bucketName, String objectPrefix, CancellationToken cancellationToken = default(CancellationToken)); + /// Returns Task with bucket policy json as string + Task GetPolicyAsync(String bucketName, CancellationToken cancellationToken = default(CancellationToken)); /// /// Sets the current bucket policy /// /// Bucket Name - /// Name of the object prefix. - /// Desired Policy type change + /// policy json /// Optional cancellation token to cancel the operation /// Returns Task that sets the current bucket policy - Task SetPolicyAsync(String bucketName, String objectPrefix, PolicyType policyType, CancellationToken cancellationToken = default(CancellationToken)); + Task SetPolicyAsync(String bucketName, String policyJson, CancellationToken cancellationToken = default(CancellationToken)); /// /// Gets the notification configuration set for this bucket diff --git a/Minio/DataModel/Policy/ActionJsonConverter.cs b/Minio/DataModel/Policy/ActionJsonConverter.cs deleted file mode 100644 index 2fce98001..000000000 --- a/Minio/DataModel/Policy/ActionJsonConverter.cs +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Minio .NET Library for Amazon S3 Compatible Cloud Storage, (C) 2017 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 Newtonsoft.Json; - -namespace Minio.DataModel.Policy -{ - class ActionJsonConverter : JsonConverter - { - public override bool CanConvert(Type objectType) - { - throw new NotImplementedException(); - } - - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) - { - object retVal = new Object(); - if (reader.TokenType == JsonToken.StartObject) - { - Principal instance = (Principal)serializer.Deserialize(reader, typeof(Principal)); - retVal = instance; - } - else if (reader.TokenType == JsonToken.String) - { - if (reader.Value.Equals("*")) - { - Principal instance = new Principal("AWS"); - instance.CanonicalUser(reader.Value.ToString()); - retVal = instance; - } - } - else if (reader.TokenType == JsonToken.StartArray) - { - retVal = serializer.Deserialize(reader, objectType); - } - return retVal; - - } - - public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) - { - throw new NotImplementedException(); - } - } -} - diff --git a/Minio/DataModel/Policy/BucketPolicy.cs b/Minio/DataModel/Policy/BucketPolicy.cs deleted file mode 100644 index a76e5ec9f..000000000 --- a/Minio/DataModel/Policy/BucketPolicy.cs +++ /dev/null @@ -1,572 +0,0 @@ -/* - * Minio .NET Library for Amazon S3 Compatible Cloud Storage, (C) 2017 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.Collections.Generic; -using System.Linq; -using Newtonsoft.Json; -using System.IO; -using Newtonsoft.Json.Linq; -using Minio.DataModel.Policy; -using Newtonsoft.Json.Serialization; - -namespace Minio.DataModel -{ - public class BucketPolicy - { - [JsonIgnore] - private string bucketName; - [JsonProperty("Version")] - private static string version; - - - [JsonProperty("Statement")] - internal List statements { get; set; } - - public BucketPolicy(string bucketName = null) - { - - this.bucketName = bucketName; - version = "2012-10-17"; - this.statements = new List(); - } - - - /** - * Reads JSON from given {@link Reader} and returns new {@link BucketPolicy} of given bucket name. - */ - public static BucketPolicy ParseJson(MemoryStream reader, String bucketName) - { - string toparse = new StreamReader(reader).ReadToEnd(); - JObject jsonData = JObject.Parse(toparse); - - BucketPolicy bucketPolicy = JsonConvert.DeserializeObject(toparse, - new JsonSerializerSettings - { - NullValueHandling = NullValueHandling.Ignore, - }); - bucketPolicy.bucketName = bucketName; - - return bucketPolicy; - } - // Helper method for unit testing - internal void SetStatements(Statement stmt) - { - if (this.statements == null) - this.statements = new List(); - this.statements.Add(stmt); - } - - - internal List Statements() - { - return this.statements; - } - /** - * Generates JSON of this BucketPolicy object. - */ - //JsonIgnore - public string GetJson() - { - return JsonConvert.SerializeObject(this, Formatting.None, - new JsonSerializerSettings - { - NullValueHandling = NullValueHandling.Ignore, - }); - } - - - /** - * Returns new bucket statements for given policy type. - */ - private List newBucketStatement(PolicyType policy, String prefix) - { - List statements = new List(); - - if (policy.Equals(PolicyType.NONE) || bucketName == null || bucketName.Length == 0) - { - return statements; - } - - Resources resources = new Resources(PolicyConstants.AWS_RESOURCE_PREFIX + bucketName); - - Statement statement = new Statement(); - statement.actions = PolicyConstants.COMMON_BUCKET_ACTIONS; - statement.effect = "Allow"; - statement.principal = new Principal("*"); - statement.resources = resources; - statement.sid = ""; - - statements.Add(statement); - - if (policy.Equals(PolicyType.READ_ONLY) || policy.Equals(PolicyType.READ_WRITE)) - { - statement = new Statement(); - statement.actions = PolicyConstants.READ_ONLY_BUCKET_ACTIONS; - statement.effect = "Allow"; - statement.principal = new Principal("*"); - statement.resources = resources; - statement.sid = ""; - - if (prefix != null && prefix.Length != 0) - { - ConditionKeyMap map = new ConditionKeyMap(); - map.Put("s3:prefix", prefix); - statement.conditions = new ConditionMap("StringEquals", map); - } - - statements.Add(statement); - } - - if (policy.Equals(PolicyType.WRITE_ONLY) || policy.Equals(PolicyType.READ_WRITE)) - { - statement = new Statement(); - statement.actions = PolicyConstants.WRITE_ONLY_BUCKET_ACTIONS; - statement.effect = "Allow"; - statement.principal = new Principal("*"); - statement.resources = resources; - statement.sid = ""; - - statements.Add(statement); - } - - return statements; - } - - - /** - * Returns new object statements for given policy type. - */ - private List newObjectStatement(PolicyType policy, String prefix) - { - List statements = new List(); - - if (policy.Equals(PolicyType.NONE) || bucketName == null || bucketName.Length == 0) - { - return statements; - } - - Resources resources = new Resources(PolicyConstants.AWS_RESOURCE_PREFIX + bucketName + "/" + prefix + "*"); - - Statement statement = new Statement(); - statement.effect = "Allow"; - statement.principal = new Principal("*"); - statement.resources = resources; - statement.sid = ""; - if (policy.Equals(PolicyType.READ_ONLY)) - { - statement.actions = PolicyConstants.READ_ONLY_OBJECT_ACTIONS; - } - else if (policy.Equals(PolicyType.WRITE_ONLY)) - { - statement.actions = PolicyConstants.WRITE_ONLY_OBJECT_ACTIONS; - } - else if (policy.Equals(PolicyType.READ_WRITE)) - { - statement.actions = PolicyConstants.READ_WRITE_OBJECT_ACTIONS(); - } - - statements.Add(statement); - return statements; - } - - - /** - * Returns new statements for given policy type. - */ - private List newStatements(PolicyType policy, String prefix) - { - List statements = this.newBucketStatement(policy, prefix); - List objectStatements = this.newObjectStatement(policy, prefix); - - statements.AddRange(objectStatements); - - return statements; - } - - - /** - * Returns whether statements are used by other than given prefix statements. - */ - //@JsonIgnore - private bool[] getInUsePolicy(string prefix) - { - string resourcePrefix = PolicyConstants.AWS_RESOURCE_PREFIX + bucketName + "/"; - string objectResource = PolicyConstants.AWS_RESOURCE_PREFIX + bucketName + "/" + prefix + "*"; - - bool readOnlyInUse = false; - bool writeOnlyInUse = false; - - foreach (Statement statement in statements) - { - if (!statement.resources.Contains(objectResource) - && statement.resources.startsWith(resourcePrefix).Count() != 0) - { - if (utils.isSupersetOf(statement.actions, PolicyConstants.READ_ONLY_OBJECT_ACTIONS)) - { - readOnlyInUse = true; - } - if (utils.isSupersetOf(statement.actions, PolicyConstants.WRITE_ONLY_OBJECT_ACTIONS)) - { - writeOnlyInUse = true; - } - } - - if (readOnlyInUse && writeOnlyInUse) - { - break; - } - } - - bool[] rv = { readOnlyInUse, writeOnlyInUse }; - return rv; - } - - - /** - * Returns all statements of given prefix. - */ - private void removeStatements(String prefix) - { - String bucketResource = PolicyConstants.AWS_RESOURCE_PREFIX + bucketName; - String objectResource = PolicyConstants.AWS_RESOURCE_PREFIX + bucketName + "/" + prefix + "*"; - bool[] inUse = getInUsePolicy(prefix); - bool readOnlyInUse = inUse[0]; - bool writeOnlyInUse = inUse[1]; - - List outList = new List(); - ISet s3PrefixValues = new HashSet(); - List readOnlyBucketStatements = new List(); - - foreach (Statement statement in statements) - { - if (!statement.isValid(bucketName)) - { - outList.Add(statement); - continue; - } - - if (statement.resources.Contains(bucketResource)) - { - if (statement.conditions != null) - { - statement.removeBucketActions(prefix, bucketResource, false, false); - } - else - { - statement.removeBucketActions(prefix, bucketResource, readOnlyInUse, writeOnlyInUse); - } - } - else if (statement.resources.Contains(objectResource)) - { - statement.removeObjectActions(objectResource); - } - - if (statement.actions.Count != 0) - { - if (statement.resources.Contains(bucketResource) - && (utils.isSupersetOf(statement.actions, PolicyConstants.READ_ONLY_BUCKET_ACTIONS)) - && statement.effect.Equals("Allow") - && statement.principal.aws().Contains("*")) - { - - if (statement.conditions != null) - { - ConditionKeyMap stringEqualsValue; - statement.conditions.TryGetValue("StringEquals", out stringEqualsValue); - if (stringEqualsValue != null) - { - ISet values; - stringEqualsValue.TryGetValue("s3:prefix", out values); - if (values != null) - { - foreach (string v in values) - { - s3PrefixValues.Add(bucketResource + "/" + v + "*"); - } - } - } - } - else if (s3PrefixValues.Count() != 0) - { - readOnlyBucketStatements.Add(statement); - continue; - } - } - - outList.Add(statement); - } - } - - bool skipBucketStatement = true; - String resourcePrefix = PolicyConstants.AWS_RESOURCE_PREFIX + bucketName + "/"; - foreach (Statement statement in outList) - { - ISet intersection = new HashSet(s3PrefixValues); - intersection.IntersectWith(statement.resources); - - if (statement.resources.startsWith(resourcePrefix).Count() != 0 - && intersection.Count() == 0) - { - skipBucketStatement = false; - break; - } - } - - foreach (Statement statement in readOnlyBucketStatements) - { - IList aws = statement.principal.aws(); - if (skipBucketStatement - && statement.resources.Contains(bucketResource) - && statement.effect.Equals("Allow") - && aws != null && aws.Contains("*") - && statement.conditions == null) - { - continue; - } - - outList.Add(statement); - } - - if (outList.Count() == 1) - { - Statement statement = outList[0]; - IList aws = statement.principal.aws(); - if (statement.resources.Contains(bucketResource) - && (utils.isSupersetOf(statement.actions, PolicyConstants.COMMON_BUCKET_ACTIONS)) - && statement.effect.Equals("Allow") - && aws != null && aws.Contains("*") - && statement.conditions == null) - { - outList = new List(); - } - } - - statements = outList; - } - - - /** - * Appends given statement into statement list to have unique statements. - * - If statement already exists in statement list, it ignores. - * - If statement exists with different conditions, they are merged. - * - Else the statement is appended to statement list. - */ - private void appendStatement(Statement statement) - { - foreach (Statement s in statements) - { - IList aws = s.principal.aws(); - ConditionMap conditions = s.conditions; - - if ((utils.isSupersetOf(s.actions, statement.actions) - && s.effect.Equals(statement.effect) - && aws != null && (utils.isSupersetOf(aws, statement.principal.aws())) - && conditions != null && conditions.Equals(statement.conditions))) - { - s.resources.UnionWith(statement.resources); - return; - } - - if (s.resources.IsSupersetOf(statement.resources) - && s.effect.Equals(statement.effect) - && aws != null && (utils.isSupersetOf(aws, statement.principal.aws())) - && conditions != null && conditions.Equals(statement.conditions)) - { - s.actions.Union(statement.actions); - return; - } - - if (s.resources.IsSupersetOf(statement.resources) - && (utils.isSupersetOf(s.actions, statement.actions) - && s.effect.Equals(statement.effect) - && aws != null && utils.isSupersetOf(aws, statement.principal.aws()))) - { - if (conditions != null && conditions.Equals(statement.conditions)) - { - return; - } - - if (conditions != null && statement.conditions != null) - { - conditions.PutAll(statement.conditions); - return; - } - } - } - if (statement.actions != null && statement.resources != null && statement.actions.Count() != 0 && statement.resources.Count() != 0) - { - statements.Add(statement); - } - } - - - /** - * Appends new statements for given policy type. - */ - private void appendStatements(PolicyType policy, String prefix) - { - List appendStatements = newStatements(policy, prefix); - foreach (Statement statement in appendStatements) - { - appendStatement(statement); - } - } - - - /** - * Returns policy type of this bucket policy. - */ - // @JsonIgnore - public PolicyType GetPolicy(string prefix) - { - string bucketResource = PolicyConstants.AWS_RESOURCE_PREFIX + bucketName; - string objectResource = PolicyConstants.AWS_RESOURCE_PREFIX + bucketName + "/" + prefix + "*"; - - bool bucketCommonFound = false; - bool bucketReadOnly = false; - bool bucketWriteOnly = false; - string matchedResource = ""; - bool objReadOnly = false; - bool objWriteOnly = false; - - foreach (Statement s in statements ?? new List()) - { - ISet matchedObjResources = new HashSet(); - - if (s.resources == null) - continue; - - if (s.resources.Contains(objectResource)) - { - matchedObjResources.Add(objectResource); - } - else - { - matchedObjResources = s.resources.Match(objectResource); - } - - if (matchedObjResources.Count() != 0) - { - bool[] rv = s.getObjectPolicy(); - bool readOnly = rv[0]; - bool writeOnly = rv[1]; - - foreach (string resource in matchedObjResources) - { - if (matchedResource.Length < resource.Length) - { - objReadOnly = readOnly; - objWriteOnly = writeOnly; - matchedResource = resource; - } - else if (matchedResource.Length == resource.Length) - { - objReadOnly = objReadOnly || readOnly; - objWriteOnly = objWriteOnly || writeOnly; - matchedResource = resource; - } - } - } - else if (s.resources.Contains(bucketResource)) - { - bool[] rv = s.getBucketPolicy(prefix); - bool commonFound = rv[0]; - bool readOnly = rv[1]; - bool writeOnly = rv[2]; - bucketCommonFound = bucketCommonFound || commonFound; - bucketReadOnly = bucketReadOnly || readOnly; - bucketWriteOnly = bucketWriteOnly || writeOnly; - } - } - - if (bucketCommonFound) - { - if (bucketReadOnly && bucketWriteOnly && objReadOnly && objWriteOnly) - { - return PolicyType.READ_WRITE; - } - else if (bucketReadOnly && objReadOnly) - { - return PolicyType.READ_ONLY; - } - else if (bucketWriteOnly && objWriteOnly) - { - return PolicyType.WRITE_ONLY; - } - } - - return PolicyType.NONE; - } - - - /** - * Returns policy type of all prefixes. - */ - //@JsonIgnore - public Dictionary GetPolicies() - { - Dictionary policyRules = new Dictionary(); - ISet objResources = new HashSet(); - - String bucketResource = PolicyConstants.AWS_RESOURCE_PREFIX + bucketName; - - // Search all resources related to objects policy - foreach (Statement s in statements) - { - if (s.resources != null) - objResources.UnionWith(s.resources.startsWith(bucketResource + "/")); - } - - // Pretend that policy resource as an actual object and fetch its policy - foreach (string r in objResources) - { - // Put trailing * if exists in asterisk - string asterisk = ""; - string resource = r; - if (r.EndsWith("*")) - { - resource = r.Substring(0, r.Length - 1); - asterisk = "*"; - } - - // String objectPath = resource.Substring(bucketResource.Length + 1, resource.Length); - String objectPath = resource.Substring(bucketResource.Length + 1, resource.Length - bucketResource.Length - 1); - - PolicyType policy = this.GetPolicy(objectPath); - policyRules.Add(bucketName + "/" + objectPath + asterisk, policy); - } - - return policyRules; - } - - - /** - * Sets policy type for given prefix. - */ - // @JsonIgnore - public void SetPolicy(PolicyType policy, String prefix) - { - if (statements == null) - { - statements = new List(); - } - - removeStatements(prefix); - appendStatements(policy, prefix); - } - } -} diff --git a/Minio/DataModel/Policy/ConditionKeyMap.cs b/Minio/DataModel/Policy/ConditionKeyMap.cs deleted file mode 100644 index 85a44d515..000000000 --- a/Minio/DataModel/Policy/ConditionKeyMap.cs +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Minio .NET Library for Amazon S3 Compatible Cloud Storage, (C) 2017 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 Minio.DataModel.Policy; -using Newtonsoft.Json; -using System.Collections.Generic; - -namespace Minio.DataModel -{ - [JsonConverter(typeof(ConditionKeyMapConverter))] - public class ConditionKeyMap : Dictionary> - { - public ConditionKeyMap() : base() { } - public ConditionKeyMap(ConditionKeyMap map = null) : base(map) { } - - public ConditionKeyMap(string key, string value) - { - ISet values = new HashSet(); - values.Add(value); - this.Add(key, values); - } - - public ConditionKeyMap(string key, ISet value) - { - this.Add(key, value); - } - - public ISet Put(string key, string value) - { - ISet existingValue; - this.TryGetValue(key, out existingValue); - if (existingValue == null) - { - existingValue = new HashSet(); - } - existingValue.Add(value); - this.Add(key, existingValue); - return existingValue; - } - public ISet Put(string key, ISet value) - { - ISet existingValue; - this.TryGetValue(key, out existingValue); - if (existingValue == null) - { - existingValue = new HashSet(); - } - existingValue.UnionWith(value); - this[key] = existingValue; - return existingValue; - } - - public void remove(string key, ISet value) - { - ISet existingValue; - this.TryGetValue(key, out existingValue); - if (existingValue == null) - { - return; - } - existingValue.ExceptWith(value); - if (existingValue.Count == 0) - { - this.Remove(key); - } - else - { - this[key] = existingValue; - } - } - - } -} diff --git a/Minio/DataModel/Policy/ConditionKeyMapConverter.cs b/Minio/DataModel/Policy/ConditionKeyMapConverter.cs deleted file mode 100644 index 9223ee109..000000000 --- a/Minio/DataModel/Policy/ConditionKeyMapConverter.cs +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Minio .NET Library for Amazon S3 Compatible Cloud Storage, (C) 2017 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.Collections.Generic; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using System.Linq; - -namespace Minio.DataModel.Policy -{ - public class ConditionKeyMapConverter : JsonConverter - { - public override bool CanConvert(Type objectType) - { - return (objectType == typeof(IDictionary<,>)); - } - - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) - { - object retVal = new Object(); - bool isParsed = false; - ISet parseSet = new HashSet(); - string key = null; - ConditionKeyMap instance = null; - if (reader.TokenType == JsonToken.StartObject) - { - instance = new ConditionKeyMap(); - } - do - { - { - if (reader.TokenType == JsonToken.PropertyName) - { - if (key == null) - key = reader.Value.ToString(); - } - else if (reader.TokenType == JsonToken.String) - { - parseSet.Add(reader.Value.ToString()); - instance.Put(key, parseSet); - isParsed = true; - } - else if (reader.TokenType == JsonToken.StartArray) - { - JArray array = JArray.Load(reader); - var rs = array.ToObject>(); - parseSet = new HashSet(); - foreach (var el in rs) - { - parseSet.Add(el); - } - instance.Put(key, parseSet); - isParsed = true; - } - } - } - while (reader.Read() && !isParsed); - return instance; - } - - public override bool CanWrite { get { return false; } } - - - public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) - { - throw new NotImplementedException(); - } - } -} diff --git a/Minio/DataModel/Policy/ConditionMap.cs b/Minio/DataModel/Policy/ConditionMap.cs deleted file mode 100644 index b9de2e679..000000000 --- a/Minio/DataModel/Policy/ConditionMap.cs +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Minio .NET Library for Amazon S3 Compatible Cloud Storage, (C) 2017 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.Collections.Generic; - -namespace Minio.DataModel -{ - public class ConditionMap : Dictionary - { - public ConditionMap() : base() { } - public ConditionMap(ConditionMap map = null) : base(map) { } - public ConditionMap(string key = null, ConditionKeyMap value = null) : base() - { - if (key != null && value != null) - { - this.Add(key, value); - } - } - // Merge Condition Key map values. - public ConditionKeyMap Put(string key, ConditionKeyMap value) - { - ConditionKeyMap existingValue; - base.TryGetValue(key, out existingValue); - if (existingValue == null) - { - existingValue = new ConditionKeyMap(value); - } - else - { - foreach (var item in value) - { - existingValue.Put(item.Key, item.Value); - } - } - this[key] = existingValue; - return existingValue; - } - public void PutAll(ConditionMap cmap) - { - foreach (var item in cmap) - { - this.Put(item.Key, item.Value); - - } - } - - } -} diff --git a/Minio/DataModel/Policy/Constants.cs b/Minio/DataModel/Policy/Constants.cs deleted file mode 100644 index fa3ee1d92..000000000 --- a/Minio/DataModel/Policy/Constants.cs +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Minio .NET Library for Amazon S3 Compatible Cloud Storage, (C) 2017 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.Collections.Generic; -using System.Linq; - -namespace MinioCore2.Policy -{ - class Constants - { - // Resource prefix for all aws resources. - public static readonly String AWS_RESOURCE_PREFIX = "arn:aws:s3:::"; - - // Common bucket actions for both read and write policies. - public static readonly List COMMON_BUCKET_ACTIONS = new List() { "s3:GetBucketLocation" }; - - // Read only bucket actions. - public static readonly List READ_ONLY_BUCKET_ACTIONS = new List() { "s3:ListBucket"}; - - // Write only bucket actions. - public static readonly List WRITE_ONLY_BUCKET_ACTIONS = - new List() { "s3:ListBucketMultipartUploads" }; - - // Read only object actions. - public static readonly List READ_ONLY_OBJECT_ACTIONS = new List() { "s3:GetObject" }; - - // Write only object actions. - public static readonly List WRITE_ONLY_OBJECT_ACTIONS = - new List() { "s3:AbortMultipartUpload", - "s3:DeleteObject", - "s3:ListMultipartUploadParts", - "s3:PutObject" }; - - // Read and write object actions. - public static IList READ_WRITE_OBJECT_ACTIONS() - { - IList res = new List(); - res.Union(READ_ONLY_OBJECT_ACTIONS); - res.Union(WRITE_ONLY_OBJECT_ACTIONS); - return res; - } - // All valid bucket and object actions. - - public static List VALID_ACTIONS() - { - List res = new List(); - res.Union(COMMON_BUCKET_ACTIONS); - res.Union(READ_ONLY_BUCKET_ACTIONS); - res.Union(WRITE_ONLY_BUCKET_ACTIONS); - res.Union(READ_WRITE_OBJECT_ACTIONS()); - return res; - } - - } -} diff --git a/Minio/DataModel/Policy/PolicyConstants.cs b/Minio/DataModel/Policy/PolicyConstants.cs deleted file mode 100644 index daf452315..000000000 --- a/Minio/DataModel/Policy/PolicyConstants.cs +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Minio .NET Library for Amazon S3 Compatible Cloud Storage, (C) 2017 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.Collections.Generic; -using System.Linq; - -namespace Minio.DataModel.Policy -{ - public class PolicyConstants - { - // Resource prefix for all aws resources. - public static readonly String AWS_RESOURCE_PREFIX = "arn:aws:s3:::"; - - // Common bucket actions for both read and write policies. - public static readonly List COMMON_BUCKET_ACTIONS = new List() { "s3:GetBucketLocation" }; - - // Read only bucket actions. - public static readonly List READ_ONLY_BUCKET_ACTIONS = new List() { "s3:ListBucket"}; - - // Write only bucket actions. - public static readonly List WRITE_ONLY_BUCKET_ACTIONS = - new List() { "s3:ListBucketMultipartUploads" }; - - // Read only object actions. - public static readonly List READ_ONLY_OBJECT_ACTIONS = new List() { "s3:GetObject" }; - - // Write only object actions. - public static readonly List WRITE_ONLY_OBJECT_ACTIONS = - new List() { "s3:AbortMultipartUpload", - "s3:DeleteObject", - "s3:ListMultipartUploadParts", - "s3:PutObject" }; - - // Read and write object actions. - public static List READ_WRITE_OBJECT_ACTIONS() - { - List res = new List(); - res.AddRange(READ_ONLY_OBJECT_ACTIONS); - res.AddRange(WRITE_ONLY_OBJECT_ACTIONS); - return res; - } - // All valid bucket and object actions. - - public static List VALID_ACTIONS() - { - List res = new List(); - res.AddRange(COMMON_BUCKET_ACTIONS); - res.AddRange(READ_ONLY_BUCKET_ACTIONS); - res.AddRange(WRITE_ONLY_BUCKET_ACTIONS); - res.AddRange(READ_WRITE_OBJECT_ACTIONS()); - return res; - } - - } -} diff --git a/Minio/DataModel/Policy/PolicyType.cs b/Minio/DataModel/Policy/PolicyType.cs deleted file mode 100644 index f6ef4a0fd..000000000 --- a/Minio/DataModel/Policy/PolicyType.cs +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Minio .NET Library for Amazon S3 Compatible Cloud Storage, (C) 2017 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; - -namespace Minio.DataModel -{ - - public class PolicyType : object - { - private PolicyType(string value) { Value = value; } - public string Value { get; set; } - - public static PolicyType NONE { get { return new PolicyType("none"); } } - public static PolicyType READ_ONLY { get { return new PolicyType("readonly"); } } - public static PolicyType READ_WRITE { get { return new PolicyType("readwrite"); } } - public static PolicyType WRITE_ONLY { get { return new PolicyType("writeonly"); } } - - public override bool Equals(Object other) - { - return Value.Equals(((PolicyType)other).Value); - } - - public override string ToString() - { - return string.Format("{0}", this.Value); - } - - public override int GetHashCode() - { - return Value.GetHashCode(); - } - - } - -} diff --git a/Minio/DataModel/Policy/Principal.cs b/Minio/DataModel/Policy/Principal.cs deleted file mode 100644 index 270fa1824..000000000 --- a/Minio/DataModel/Policy/Principal.cs +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Minio .NET Library for Amazon S3 Compatible Cloud Storage, (C) 2017 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.Collections.Generic; -using System.Runtime.Serialization; -using Newtonsoft.Json.Serialization; -using Newtonsoft.Json; - -namespace Minio.DataModel.Policy -{ - [DataContract] - public class Principal - { - [JsonProperty("AWS")] - [JsonConverter(typeof(SingleOrArrayConverter))] - - internal IList awsList { get; set; } - [JsonProperty("CanonicalUser")] - internal IList canonicalUser { get; set; } - public Principal() - { - - } - public Principal(string aws=null) - { - this.awsList = new List(); - if (aws != null) - { - this.awsList.Add(aws); - } - } - public void CanonicalUser(string val) - { - this.canonicalUser = new List(); - if (val != null) - { - this.canonicalUser.Add(val); - } - } - public IList aws() - { - return this.awsList; - } - } -} diff --git a/Minio/DataModel/Policy/PrincipalJsonConverter.cs b/Minio/DataModel/Policy/PrincipalJsonConverter.cs deleted file mode 100644 index 40f5907f4..000000000 --- a/Minio/DataModel/Policy/PrincipalJsonConverter.cs +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Minio .NET Library for Amazon S3 Compatible Cloud Storage, (C) 2017 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 Newtonsoft.Json; - -namespace Minio.DataModel.Policy -{ - public class PrincipalJsonConverter : JsonConverter - { - public override bool CanConvert(Type objectType) - { - throw new NotImplementedException(); - } - - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) - { - object retVal = new Object(); - - if (reader.TokenType == JsonToken.StartObject) - { - Principal instance = (Principal)serializer.Deserialize(reader, typeof(Principal)); - retVal = instance ; - - } - else if (reader.TokenType == JsonToken.String) - { - if (reader.Value.Equals("*")) - { - Principal instance = new Principal("AWS"); - instance.awsList.Add(reader.Value.ToString()); - instance.CanonicalUser(reader.Value.ToString()); - retVal = instance; - } - } - else if (reader.TokenType == JsonToken.StartArray) - { - retVal = serializer.Deserialize(reader, objectType); - } - return retVal; - - } - - public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) - { - if (value != null) - { - serializer.Serialize(writer, value); - } - } -} -} diff --git a/Minio/DataModel/Policy/ResourceJsonConverter.cs b/Minio/DataModel/Policy/ResourceJsonConverter.cs deleted file mode 100644 index 11bd53271..000000000 --- a/Minio/DataModel/Policy/ResourceJsonConverter.cs +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Minio .NET Library for Amazon S3 Compatible Cloud Storage, (C) 2017 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.Collections.Generic; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; - -namespace Minio.DataModel.Policy -{ - public class ResourceJsonConverter : JsonConverter - { - public override bool CanConvert(Type objectType) - { - throw new NotImplementedException(); - } - - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) - { - object retVal = new Object(); - if (reader.TokenType == JsonToken.StartObject) - { - Resources instance = (Resources)serializer.Deserialize(reader, typeof(Resources)); - retVal = instance ; - - } - else if (reader.TokenType == JsonToken.String) - { - Resources instance = new Resources(); - instance.Add(reader.Value.ToString()); - retVal = instance; - - } - else if (reader.TokenType == JsonToken.StartArray) - { - // retVal = serializer.Deserialize(reader, objectType); - JArray array = JArray.Load(reader); - var rs = array.ToObject>(); - Resources instance = new Resources(); - foreach (var el in rs) - { - instance.Add(el); - } - retVal = instance; - } - return retVal; - - } - - public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) - { - if (value != null) - { - serializer.Serialize(writer, value); - } - } - } -} diff --git a/Minio/DataModel/Policy/Resources.cs b/Minio/DataModel/Policy/Resources.cs deleted file mode 100644 index 43e54eb5c..000000000 --- a/Minio/DataModel/Policy/Resources.cs +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Minio .NET Library for Amazon S3 Compatible Cloud Storage, (C) 2017 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.Collections.Generic; -using System.Text.RegularExpressions; - -namespace Minio.DataModel.Policy -{ - internal class Resources : HashSet - { - public Resources(string resource=null) : base() - { - if (resource != null) - { - Add(resource); - } - } - public ISet startsWith(string resourcePrefix) - { - HashSet res = new HashSet(); - foreach(string resource in this) - { - if (resource.StartsWith(resourcePrefix)) - { - res.Add(resource); - } - } - return res; - } - private bool matched(string pattern, string resource) - { - if (pattern.Length == 0) - { - return resource.Equals(pattern); - } - if (pattern.Equals("*")) - { - return true; - } - string[] parts = Regex.Split(pattern, "\\*"); - if (parts.Length == 1) - { - return resource.Equals(parts[0]); - } - bool tglob = pattern.EndsWith("*"); - int end = parts.Length - 1; - - if (!resource.StartsWith(parts[0])) - { - return false; - } - for (int i = 1; i < end; i++) - { - if (!resource.Contains(parts[i])) - { - return false; - } - int idx = resource.IndexOf(parts[i]) + parts[i].Length; - resource = resource.Substring(idx); - } - return tglob || resource.EndsWith(parts[end]); - - } - internal Resources Match(string resource) - { - Resources res = new Resources(); - foreach (string pattern in this) - { - if (matched(pattern,resource)) - { - res.Add(pattern); - } - } - return res; - } - } -} diff --git a/Minio/DataModel/Policy/SingleOrArrayConverter.cs b/Minio/DataModel/Policy/SingleOrArrayConverter.cs deleted file mode 100644 index 2cb8638cb..000000000 --- a/Minio/DataModel/Policy/SingleOrArrayConverter.cs +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Minio .NET Library for Amazon S3 Compatible Cloud Storage, (C) 2017 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.Collections.Generic; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; - -namespace Minio.DataModel.Policy -{ - - public class SingleOrArrayConverter : JsonConverter - { - public override bool CanConvert(Type objectType) - { - return (objectType == typeof(List)); - } - - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) - { - JToken token = JToken.Load(reader); - if (token.Type == JTokenType.Array) - { - return token.ToObject>(); - } - return new List { token.ToObject() }; - } - - public override bool CanWrite - { - get { return false; } - } - - public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) - { - throw new NotImplementedException(); - } - } -} - diff --git a/Minio/DataModel/Policy/Statement.cs b/Minio/DataModel/Policy/Statement.cs deleted file mode 100644 index 9110f6a9b..000000000 --- a/Minio/DataModel/Policy/Statement.cs +++ /dev/null @@ -1,299 +0,0 @@ -/* - * Minio .NET Library for Amazon S3 Compatible Cloud Storage, (C) 2017 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.Collections.Generic; -using System.Linq; -using Newtonsoft.Json; - -namespace Minio.DataModel.Policy -{ - - internal class Statement - - { - [JsonProperty("Action")] - [JsonConverter(typeof(SingleOrArrayConverter))] - public IList actions { get; set; } - - [JsonProperty("Condition")] - public ConditionMap conditions { get; set; } - - [JsonProperty("Effect")] - public string effect { get; set; } - - [JsonProperty("Principal")] - [JsonConverter(typeof(PrincipalJsonConverter))] - public Principal principal { get; set; } - - [JsonProperty("Resource")] - [JsonConverter(typeof(ResourceJsonConverter))] - public Resources resources { get; set; } - - [JsonProperty("Sid")] - public string sid { get; set; } - /** - * Returns whether given statement is valid to process for given bucket name. - */ - public bool isValid(string bucketName) - { - ISet intersection; - if (this.actions != null) - intersection = new HashSet(this.actions); - else - intersection = new HashSet(); - - intersection.IntersectWith(PolicyConstants.VALID_ACTIONS()); - - if (intersection.Count == 0) - { - return false; - } - if (!this.effect.Equals("Allow")) - { - return false; - } - - IList aws = this.principal != null ? this.principal.aws() : null; - - if (aws == null || !aws.Contains("*")) - { - return false; - } - - string bucketResource = PolicyConstants.AWS_RESOURCE_PREFIX + bucketName; - - if (this.resources == null) - { - return false; - } - - if (this.resources.Contains(bucketResource)) - { - return true; - } - - if (this.resources.startsWith(bucketResource + "/").Count == 0) - { - return false; - } - - return true; - } - - /** - * Removes object actions for given object resource. - */ - public void removeObjectActions(string objectResource) - { - if (this.conditions != null) - { - return; - } - - if (this.resources.Count > 1) - { - this.resources.Remove(objectResource); - } - else - { - this.actions.Except(PolicyConstants.READ_WRITE_OBJECT_ACTIONS()); - } - } - private void removeReadOnlyBucketActions(string prefix) - { - if (!utils.isSupersetOf(this.actions, PolicyConstants.READ_ONLY_BUCKET_ACTIONS)) - { - return; - } - - this.actions.Except(PolicyConstants.READ_ONLY_BUCKET_ACTIONS); - - if (this.conditions == null) - { - return; - } - - if (prefix == null || prefix.Count() == 0) - { - return; - } - - ConditionKeyMap stringEqualsValue; - this.conditions.TryGetValue("StringEquals", out stringEqualsValue); - if (stringEqualsValue == null) - { - return; - } - - ISet values; - stringEqualsValue.TryGetValue("s3:prefix", out values); - if (values != null) - { - values.Remove(prefix); - } - - if (values == null || values.Count == 0) - { - stringEqualsValue.Remove("s3:prefix"); - } - - if (stringEqualsValue.Count == 0) - { - this.conditions.Remove("StringEquals"); - } - - if (this.conditions.Count == 0) - { - this.conditions = null; - } - } - - private void removeWriteOnlyBucketActions() - { - if (this.conditions == null) - { - this.actions.Except(PolicyConstants.WRITE_ONLY_BUCKET_ACTIONS); - } - } - - /** - * Removes bucket actions for given prefix and bucketResource. - */ - public void removeBucketActions(string prefix, string bucketResource, - bool readOnlyInUse, bool writeOnlyInUse) - { - if (this.resources.Count > 1) - { - this.resources.Remove(bucketResource); - return; - } - - if (!readOnlyInUse) - { - removeReadOnlyBucketActions(prefix); - } - - if (!writeOnlyInUse) - { - removeWriteOnlyBucketActions(); - } - - return; - } - - /** - * Returns bucket policy types for given prefix. - */ - // [JsonIgnore] - public bool[] getBucketPolicy(string prefix) - { - bool commonFound = false; - bool readOnly = false; - bool writeOnly = false; - - IList aws = this.principal.aws(); - if (!(this.effect.Equals("Allow") && aws != null && aws.Contains("*"))) - { - return new bool[] { commonFound, readOnly, writeOnly }; - } - - if (utils.isSupersetOf(this.actions, PolicyConstants.COMMON_BUCKET_ACTIONS) && this.conditions == null) - { - commonFound = true; - } - - if (utils.isSupersetOf(this.actions, PolicyConstants.WRITE_ONLY_BUCKET_ACTIONS) && this.conditions == null) - { - writeOnly = true; - } - - if (utils.isSupersetOf(this.actions, PolicyConstants.READ_ONLY_BUCKET_ACTIONS)) - { - if (prefix != null && prefix.Count() != 0 && this.conditions != null) - { - ConditionKeyMap stringEqualsValue; - this.conditions.TryGetValue("StringEquals", out stringEqualsValue); - if (stringEqualsValue != null) - { - ISet s3PrefixValues; - stringEqualsValue.TryGetValue("s3:prefix", out s3PrefixValues); - if (s3PrefixValues != null && s3PrefixValues.Contains(prefix)) - { - readOnly = true; - } - } - else - { - ConditionKeyMap stringNotEqualsValue; - this.conditions.TryGetValue("StringNotEquals", out stringNotEqualsValue); - if (stringNotEqualsValue != null) - { - ISet s3PrefixValues; - stringNotEqualsValue.TryGetValue("s3:prefix", out s3PrefixValues); - if (s3PrefixValues != null && !s3PrefixValues.Contains(prefix)) - { - readOnly = true; - } - } - } - } - else if ((prefix == null || prefix.Count() == 0) && this.conditions == null) - { - readOnly = true; - } - else if (prefix != null && prefix.Count() != 0 && this.conditions == null) - { - readOnly = true; - } - } - - return new bool[] { commonFound, readOnly, writeOnly }; - } - - /** - * Returns object policy types. - */ - // [JsonIgnore] - public bool[] getObjectPolicy() - { - bool readOnly = false; - bool writeOnly = false; - - IList aws = null; - if (this.principal != null) - { - aws = this.principal.aws(); - } - - if (this.effect.Equals("Allow") - && aws != null && aws.Contains("*") - && this.conditions == null) - { - if (utils.isSupersetOf(this.actions, PolicyConstants.READ_ONLY_OBJECT_ACTIONS)) - { - readOnly = true; - } - if (utils.isSupersetOf(this.actions, PolicyConstants.WRITE_ONLY_OBJECT_ACTIONS)) - { - writeOnly = true; - } - } - - return new bool[] { readOnly, writeOnly }; - } - - } -}