Esempio n. 1
0
        public async Task LoginWithValidCredentials_Success()
        {
            string  roleName_A = _uniqueKeys.GetKey("RLogin");
            AppRole roleA      = new AppRole(roleName_A);

            Assert.True(await _appRoleAuthEngine.SaveRole(roleA), "A1: Saving the role failed.");

            // Read the role ID back.
            string roleID = await _appRoleAuthEngine.ReadRoleID(roleA.Name);

            // Now create the a secret
            AppRoleSecret secret_A = await _appRoleAuthEngine.GenerateSecretID(roleA.Name);


            // Now attempt to login - We need to create a new vault object or else we will screw with the other tests, since a successful login changes the token.
            VaultAgentAPI     v    = new VaultAgentAPI("logintest", VaultServerRef.vaultURI);
            AppRoleAuthEngine eng1 = (AppRoleAuthEngine)v.ConnectAuthenticationBackend(EnumBackendTypes.A_AppRole, "Test", _appRoleAuthEngine.MountPoint);

            Token token = await eng1.Login(roleID, secret_A.ID);

/*		    bool rc;
 *                  rc = await _appRoleAuthEngine.Login(roleID, secret_A.ID);
 *
 *                  Assert.True(rc);
 */
            Assert.IsNotNull(token, "A1:  A token was not returned.  The login failed.");
            Assert.IsNotEmpty(token.ID, "A2:  A token was returned, but it did not have an ID value.");
        }
Esempio n. 2
0
        /// <summary>
        /// Performs tasks that the Role1 user would do.  Creating the actual application folders.
        /// </summary>
        /// <param name="role"></param>
        /// <returns></returns>
        public async Task PerformRole1Tasks()
        {
            try {
                // Here we will create the AppA and B folders in both the path1 and the appData paths.
                KV2Secret path1AppA   = new KV2Secret(Constants.appName_A, "path1");
                KV2Secret path1AppB   = new KV2Secret(Constants.appName_B, "path1");
                KV2Secret appDataAppA = new KV2Secret(Constants.appName_A, Constants.appData);
                KV2Secret appDataAppB = new KV2Secret(Constants.appName_B, Constants.appData);
                KV2Secret appData     = new KV2Secret(Constants.appData);

                // We need to simulate a session as this Role1 User:
                VaultAgentAPI     vault        = new VaultAgentAPI("Role1", _vaultAgent.Uri);
                AppRoleAuthEngine authEngine   = (AppRoleAuthEngine)vault.ConnectAuthenticationBackend(EnumBackendTypes.A_AppRole, _AppBEName, _AppBEName);
                KV2SecretEngine   secretEngine =
                    (KV2SecretEngine)vault.ConnectToSecretBackend(EnumSecretBackendTypes.KeyValueV2, "Sheakley KV2 Secrets", _beKV2Name);

                // Now login.
                Token token = await authEngine.Login(role1.RoleID, _SIDRole1.ID);



                // Create the secrets if they do not exist.  We can attempt to Read the Secret on the path1 paths as we have full control

                var result = await secretEngine.TryReadSecret(appData);

                if (!result.IsSuccess)
                {
                    await secretEngine.SaveSecret(appData, KV2EnumSecretSaveOptions.OnlyIfKeyDoesNotExist);
                }
                result = await secretEngine.TryReadSecret(path1AppA);

                if (!result.IsSuccess)
                {
                    await secretEngine.SaveSecret(path1AppA, KV2EnumSecretSaveOptions.OnlyIfKeyDoesNotExist);
                }
                result = await secretEngine.TryReadSecret(path1AppB);

                if (!result.IsSuccess)
                {
                    await secretEngine.SaveSecret(path1AppB, KV2EnumSecretSaveOptions.OnlyIfKeyDoesNotExist);
                }

                // We have to list the "folders" or secrets on the AppData path as we only have create and List permissions.
                List <string> appFolders = await secretEngine.ListSecretsAtPath(appData);

                if (!appFolders.Contains(Constants.appName_A))
                {
                    await secretEngine.SaveSecret(appDataAppA, KV2EnumSecretSaveOptions.OnlyIfKeyDoesNotExist);
                }
                if (!appFolders.Contains(Constants.appName_B))
                {
                    await secretEngine.SaveSecret(appDataAppB, KV2EnumSecretSaveOptions.OnlyIfKeyDoesNotExist);
                }
            }
            catch (VaultForbiddenException e) { Console.WriteLine("The role does not have permission to perform the requested operation. - Original Error - {0}", e.Message); }
            catch (Exception e) { Console.WriteLine("Error detected in routine - PerformRole1Tasks - Error is - {0}", e.Message); }
        }
Esempio n. 3
0
        public async Task PerformRoleATasks()
        {
            // We need to simulate a session as this Role1 User:
            VaultAgentAPI     vault        = new VaultAgentAPI("Role2", _vaultAgent.Uri);
            AppRoleAuthEngine authEngine   = (AppRoleAuthEngine)vault.ConnectAuthenticationBackend(EnumBackendTypes.A_AppRole, _AppBEName, _AppBEName);
            KV2SecretEngine   secretEngine =
                (KV2SecretEngine)vault.ConnectToSecretBackend(EnumSecretBackendTypes.KeyValueV2, "KV2 Secrets", _beKV2Name);


            // Now login.
            Token token = await authEngine.Login(roleAppA.RoleID, _SIDRoleAppA.ID);

            // Read existing secrets.
            string    rootPath    = Constants.appData + "/" + Constants.appName_A + "/";
            KV2Secret secretA1    = new KV2Secret("Database", rootPath);
            bool      readSuccess = false;

            (readSuccess, secretA1) = await secretEngine.TryReadSecret <KV2Secret>(secretA1, 0);

            // If it did not exist then create it.
            if (!readSuccess)
            {
                secretA1 = new KV2Secret("Database", rootPath);
                // Create Some Secrets.
                secretA1.Attributes.Add("username", "abcUser");
                secretA1.Attributes.Add("password", "passEncrypted");
                secretA1.Attributes.Add("Connection", "db=1.2.3.4:4706/iInstance");

                await secretEngine.SaveSecret(secretA1, KV2EnumSecretSaveOptions.OnlyIfKeyDoesNotExist, 0);
            }

            // Try to read the parent secret - should fail
            KV2Secret secretParent = new KV2Secret(Constants.appData);

            (readSuccess, secretParent) = await secretEngine.TryReadSecret <KV2Secret>(secretParent, 0);


            // Lets try and read an AppB secret.  Should fail.
            try {
                // Lets try and read an AppA secret.  Should fail.
                string    rootBPath = Constants.appData + "/" + Constants.appName_B + "/";
                KV2Secret secretB1  = new KV2Secret("Database", rootBPath);
                (readSuccess, secretB1) = await secretEngine.TryReadSecret <KV2Secret>(secretB1, 0);
            }
            catch (VaultForbiddenException) {
                Console.WriteLine("[SUCCESS-EXPECTED RESULT:  User A does not have access to read from User B's secret store.");
            }


            // Lets update the secret.
            string passwd = secretA1.Attributes["password"];

            passwd = passwd + DateTime.Now.Hour;
            secretA1.Attributes["password"] = passwd;
            //secretEngine.SaveSecret(secretA1,)
        }
Esempio n. 4
0
        public async Task PerformRoleBTasks()
        {
            // We need to simulate a session as this Role1 User:
            VaultAgentAPI     vault        = new VaultAgentAPI("Role2", _vaultAgent.Uri);
            AppRoleAuthEngine authEngine   = (AppRoleAuthEngine)vault.ConnectAuthenticationBackend(EnumBackendTypes.A_AppRole, _AppBEName, _AppBEName);
            KV2SecretEngine   secretEngine =
                (KV2SecretEngine)vault.ConnectToSecretBackend(EnumSecretBackendTypes.KeyValueV2, "KV2 Secrets", _beKV2Name);


            // Now login.
            Token token = await authEngine.Login(roleAppB.RoleID, _SIDRoleAppB.ID);

            // Read existing secrets.
            string    rootPath    = Constants.appData + "/" + Constants.appName_B + "/";
            KV2Secret secretB1    = new KV2Secret("Database", rootPath);
            bool      readSuccess = false;

            (readSuccess, secretB1) = await secretEngine.TryReadSecret(secretB1, 0);


            if (!readSuccess)
            {
                secretB1 = new KV2Secret("Database", rootPath);
                // Create Some Secrets.
                secretB1.Attributes.Add("username", "Buser");
                secretB1.Attributes.Add("password", "Bpassword");
                secretB1.Attributes.Add("Connection", "db=99.100.101.102:0/iBInstance");

                await secretEngine.SaveSecret(secretB1, KV2EnumSecretSaveOptions.OnlyIfKeyDoesNotExist, 0);
            }

            try {
                // Lets try and read an AppA secret.  Should fail.
                string    rootAPath = Constants.appData + "/" + Constants.appName_A + "/";
                KV2Secret secretA1  = new KV2Secret("Database", rootAPath);
                (readSuccess, secretB1) = await secretEngine.TryReadSecret(secretA1, 0);
            }
            catch (VaultForbiddenException) {
                Console.WriteLine("[SUCCESS-EXPECTED RESULT:  User B does not have access to read from User A's secret store.");
            }

            int bb = 0;

            bb++;
        }
        /// <summary>
        /// Performs tasks that the teen wants to to.
        /// </summary>
        /// <returns></returns>
        private async Task Perform_TeenTasks()
        {
            // We cannot use the Vault Agent _masterVaultAgent, since it has the Master Token tied to it.  We will create a new VaultAgent and SecretEngine for use during this Task, which will have our
            // Mother role token AND not the master Token.
            // So, we wire up a new Vault, AppRole and Secret Engines AND use them throughout this routine.
            VaultAgentAPI     vault        = new VaultAgentAPI("TeenConnector", _masterVaultAgent.Uri);
            AppRoleAuthEngine authEngine   = (AppRoleAuthEngine)vault.ConnectAuthenticationBackend(EnumBackendTypes.A_AppRole, _AppBEName, _AppBEName);
            KV2SecretEngine   secretEngine =
                (KV2SecretEngine)vault.ConnectToSecretBackend(EnumSecretBackendTypes.KeyValueV2, _beKV2Name, _beKV2Name);


            // Login.
            Token token = await authEngine.Login(roleTeenager.RoleID, _sidTeenager.ID);



            // Should be able to load the House Secret.  But not updated it.
            KV2Secret a = await secretEngine.ReadSecret <KV2Secret>(HOUSE.HOUSE_PATH);

            a.Attributes["Electric"] = "No";
            // Should Fail
            bool rc = await SaveSecret(secretEngine, a);


            // Should NOT be able to read anything in the Toddler's Bedroom
            (bool rcB, KV2Secret b) = await ReadSecret(secretEngine, HOUSE.TODDLER_BEDROOM);

            // Should be able to read and update the Kitchen secret
            (bool rcK, KV2Secret k) = await ReadSecret(secretEngine, HOUSE.KITCHEN);

            k.Attributes["Carrots"] = "Need";
            rcK = await SaveSecret(secretEngine, k);

            // Should be able to read and update the Fridge
            (bool rcR, KV2Secret r) = await ReadSecret(secretEngine, HOUSE.REFRIGERATOR);

            k.Attributes["Cold"] = "True";
            rcR = await SaveSecret(secretEngine, r);

            // Should have no writes to the Dishwasher
            (bool rcD, KV2Secret d) = await ReadSecret(secretEngine, HOUSE.DISHWASHER);
        }
Esempio n. 6
0
        /// <summary>
        /// Performs tasks that the Role1 user would do.  Creating the actual application folders.
        /// </summary>
        /// <param name="role"></param>
        /// <returns></returns>
        public async Task PerformRole2Tasks()
        {
            try {
                // We just try and read secrets off path1/ folders.

                // We need to simulate a session as this Role1 User:
                VaultAgentAPI     vault        = new VaultAgentAPI("Role2", _vaultAgent.Uri);
                AppRoleAuthEngine authEngine   = (AppRoleAuthEngine)vault.ConnectAuthenticationBackend(EnumBackendTypes.A_AppRole, _AppBEName, _AppBEName);
                KV2SecretEngine   secretEngine =
                    (KV2SecretEngine)vault.ConnectToSecretBackend(EnumSecretBackendTypes.KeyValueV2, "Sheakley KV2 Secrets", _beKV2Name);


                // Now login.
                Token token = await authEngine.Login(role2.RoleID, _SIDRole2.ID);

                // Try and read a secret.
            }
            catch (VaultForbiddenException e) { Console.WriteLine("The role does not have permission to perform the requested operation. - Original Error - {0}", e.Message); }
            catch (Exception e) { Console.WriteLine("Error detected in routine - PerformRole1Tasks - Error is - {0}", e.Message); }
        }
 private async Task Perform_FatherTasks()
 {
     // Now login.
     Token token = await _appRoleAuthEngine.Login(roleFather.RoleID, _sidFather.ID);
 }
        /// <summary>
        /// Perform tasks the mother wants to do
        /// </summary>
        /// <returns></returns>
        private async Task Perform_MotherTasks()
        {
            // We cannot use the Vault Agent _masterVaultAgent, since it has the Master Token tied to it.  We will create a new VaultAgent and SecretEngine for use during this Task, which will have our
            // Mother role token AND not the master Token.
            // So, we wire up a new Vault, AppRole and Secret Engines AND use them throughout this routine.
            VaultAgentAPI     vault        = new VaultAgentAPI("MotherConnector", _masterVaultAgent.Uri);
            AppRoleAuthEngine authEngine   = (AppRoleAuthEngine)vault.ConnectAuthenticationBackend(EnumBackendTypes.A_AppRole, _AppBEName, _AppBEName);
            KV2SecretEngine   secretEngine =
                (KV2SecretEngine)vault.ConnectToSecretBackend(EnumSecretBackendTypes.KeyValueV2, _beKV2Name, _beKV2Name);


            // Login.
            Token token = await authEngine.Login(roleMother.RoleID, _sidMother.ID);

            // Load the house secret, modify it and save it.
            KV2Secret a = await secretEngine.ReadSecret <KV2Secret>(HOUSE.HOUSE_PATH);

            a.Attributes.Add("Electric", "Yes");
            await SaveSecret(secretEngine, a);

            // Create the Kitchen
            KV2Secret b = new KV2Secret(HOUSE.KITCHEN);

            b.Attributes.Add("Dishwasher", "Yes");
            await SaveSecret(secretEngine, b);

            // Refrigerator
            KV2Secret c = new KV2Secret(HOUSE.REFRIGERATOR);

            c.Attributes.Add("Milk", "Chocolate");
            c.Attributes.Add("Cheese", "American");
            await SaveSecret(secretEngine, c);

            // DishWasher
            KV2Secret c1 = new KV2Secret(HOUSE.DISHWASHER);

            c1.Attributes.Add("Drawers", "3");
            await SaveSecret(secretEngine, c1);

            // Garage
            KV2Secret d = new KV2Secret(HOUSE.GARAGE);

            d.Attributes.Add("Car", "Porsche");
            await SaveSecret(secretEngine, d);

            // Master Bedroom
            KV2Secret e = new KV2Secret(HOUSE.MASTER_BEDROOM);

            e.Attributes.Add("Safe", "Yes");
            await SaveSecret(secretEngine, e);

            // Teen Bedroom
            KV2Secret f = new KV2Secret(HOUSE.TEEN_BEDROOM);

            f.Attributes.Add("CarPoster", "Yes");
            await SaveSecret(secretEngine, f);

            // Toddler Bedroom
            KV2Secret g = new KV2Secret(HOUSE.TODDLER_BEDROOM);

            g.Attributes.Add("BabyMonitor", "On");
            await SaveSecret(secretEngine, g);
        }
Esempio n. 9
0
        public async Task TestTemplatedPolicies()
        {
            string appBE = _uniqueKeys.GetKey("appTE");
            string kv2BE = _uniqueKeys.GetKey("kv2TE");


            // 1A - Setup backends needed for testing.
            // We need to setup a KV2 Secrets engine and also an AppRole Backend.
            // Create an Authentication method of App Role.	- This only needs to be done when the Auth method is created.
            AuthMethod am = new AuthMethod(appBE, EnumAuthMethods.AppRole);
            await _vaultSystemBackend.AuthEnable(am);

            // Create a KV2 Secret Mount if it does not exist.
            VaultSystemBackend vaultSystemBackend = new VaultSystemBackend(_vaultAgentAPI.TokenID, _vaultAgentAPI);
            await vaultSystemBackend.SysMountCreate(kv2BE, "ClientTest KeyValue 2 Secrets", EnumSecretBackendTypes.KeyValueV2);



            // 1B. Now we can connect to the backends.
            VaultAgentAPI vault = await VaultServerRef.ConnectVault("PolicyBECapa");

            //new VaultAgentAPI("capability", _vaultAgentAPI.IP, _vaultAgentAPI.Port, _vaultAgentAPI.TokenID);
            AppRoleAuthEngine authEngine   = (AppRoleAuthEngine)vault.ConnectAuthenticationBackend(EnumBackendTypes.A_AppRole, appBE, appBE);
            KV2SecretEngine   secretEngine =
                (KV2SecretEngine)vault.ConnectToSecretBackend(EnumSecretBackendTypes.KeyValueV2, "KV2 Secrets", kv2BE);
            IdentitySecretEngine idEngine = (IdentitySecretEngine)_vaultAgentAPI.ConnectToSecretBackend(EnumSecretBackendTypes.Identity);

            // 1C - Write out some values.
            TestContext.WriteLine("App Role Auth Backend:   {0}", authEngine.Name);
            TestContext.WriteLine("KV2 Secret Backend:      {0}", secretEngine.Name);


            // 2. Setup the policy to provide the permissions to test against.
            VaultPolicyContainer policyContainer = new VaultPolicyContainer("capa");


            // 3. Now create an App Role & Secret ID.  The app role in this case has no policies - it will get them from the Entity.
            string  roleName = _uniqueKeys.GetKey("role");
            AppRole appRole  = new AppRole(roleName);

            appRole = await authEngine.SaveRoleAndReturnRoleObject(appRole);

            AppRoleSecret secretID = await authEngine.CreateSecretID(appRole.Name);



            // 4.  Create an Entity and Entity Alias.
            // 4A.  Get Authentication backend accessor.
            Dictionary <string, AuthMethod> authMethods = await vaultSystemBackend.AuthListAll();

            AuthMethod authMethod = authMethods[authEngine.Name + "/"];

            Assert.IsNotNull(authMethod, "B10:  Expected to find the authentication backend.  But did not.");
            string mountAccessor = authMethod.Accessor;

            // 4B.  Create an entity for the app role.
            string name   = _uniqueKeys.GetKey("EAR");
            Entity entity = new Entity(roleName);

            entity.Policies.Add(policyContainer.Name);

            // 4C.  Now save entity
            entity = await idEngine.SaveEntity(entity);

            Assert.IsNotNull(entity, "B20:  Expected to receive an Entity object");


            // 4D. Write out some values
            TestContext.WriteLine("Entity Name:      {0}", entity.Name);
            TestContext.WriteLine("Entity ID:        {0}", entity.Id);


            // 5. Create an alias that ties the Entity we just created to the AppRole in the authentication backend.
            Guid roleID    = new Guid(appRole.RoleID);
            Guid aliasGuid = await idEngine.SaveAlias(entity.Id, mountAccessor, appRole.RoleID);

            Assert.AreNotEqual(aliasGuid.ToString(), Guid.Empty.ToString());

            // 5B.  Re-read the entity - it should now contain the alias.
            Entity fullEntity = await idEngine.ReadEntity(entity.Id);

            Assert.AreEqual(1, fullEntity.Aliases.Count, "B30:  Expected the full entity to now contain the alias ID.");


            // 6.  Now define the policy and save to Vault.
            policyContainer.PolicyPaths.Clear();
            string appPath1           = "app/{{identity.entity.aliases." + mountAccessor + ".name}}/*";
            VaultPolicyPathItem vppi1 = new VaultPolicyPathItem(kv2BE, "data/" + appPath1);
            VaultPolicyPathItem vppi2 = new VaultPolicyPathItem(kv2BE, "data/app/appA/subItem/*");
            VaultPolicyPathItem vppi3 = new VaultPolicyPathItem(kv2BE, "data/shared/common/*");
            VaultPolicyPathItem vppi4 = new VaultPolicyPathItem(kv2BE, "data/shared/info/*");

            vppi1.FullControl = true;
            vppi2.FullControl = true;
            vppi3.CRUDAllowed = true;
            vppi4.ReadAllowed = true;


            policyContainer.AddPolicyPathObject(vppi1);
            policyContainer.AddPolicyPathObject(vppi2);
            policyContainer.AddPolicyPathObject(vppi3);
            policyContainer.AddPolicyPathObject(vppi4);

            await _vaultSystemBackend.SysPoliciesACLCreate(policyContainer);


            // 7.  Now we can login to get a token..  Validate the entity policy has been set on token.
            Token token = await authEngine.Login(appRole.RoleID, secretID.ID);

            Assert.IsNotNull("B40:  A valid token was not received.");

            CollectionAssert.Contains(token.IdentityPolicies, policyContainer.Name, "B100:  Did not find the policy that should have been applied from the entity.");


            // 8.  Now we can finally test the capabilities of that token.
            List <string> paths    = new List <string>();
            string        pathBase = kv2BE + "/data/app/" + fullEntity.Aliases[0].Name + "/config";
            string        metaBase = kv2BE + "/metadata/app" + fullEntity.Aliases[0].Name + "/config";
            string        path1    = pathBase;
            string        path2    = pathBase + "/subItem";
            string        path3    = kv2BE + "/data/shared/common/testEntry";

            paths.Add(path1);
            paths.Add(path2);
            paths.Add(path3);


            Dictionary <string, List <string> > permissions;

            permissions = await _vaultSystemBackend.GetTokenCapabilityOnPaths(token.ID, paths);


            // 9. Validate the permission results.
            Assert.AreEqual(3, permissions.Count, "B130:  Expected to receive 3 permission objects back.");
            Assert.AreEqual(6, permissions[path1].Count, "B140:  Expected the item: " + path1 + " to contain 6 permissions.");
            Assert.AreEqual(6, permissions[path2].Count, "B150:  Expected the item: " + path2 + " to contain 6 permissions.");
            Assert.AreEqual(4, permissions[path3].Count, "B160:  Expected the item: " + path3 + " to contain 3 permissions.");

            CollectionAssert.Contains(permissions[path3], "create", "B170:  Expected the permission to be create for path: " + path3);
            CollectionAssert.Contains(permissions[path3], "read", "B171:  Expected the permission to be read for path: " + path3);
            CollectionAssert.Contains(permissions[path3], "update", "B172:  Expected the permission to be update for path: " + path3);
            CollectionAssert.Contains(permissions[path3], "delete", "B173:  Expected the permission to be read for path: " + path3);


            // 10. Try to create a secret at path 1
            string    secName1 = _uniqueKeys.GetKey("sec1");
            KV2Secret secret1  = new KV2Secret("config", "app/" + fullEntity.Aliases[0].Name);

            secret1.Attributes.Add("version", "v12.2");
            Assert.True(await secretEngine.SaveSecret(secret1, KV2EnumSecretSaveOptions.AlwaysAllow), "B200:  Save of secret did not work.  Check permissions.");


            // 11. Create and delete a secret at path3.
            KV2Secret secret2 = new KV2Secret("options", "shared/common/testEntry");

            secret2.Attributes.Add("color", "blue");
            secret2.Attributes.Add("size", "Large");
            Assert.True(await secretEngine.SaveSecret(secret2, KV2EnumSecretSaveOptions.AlwaysAllow), "B210:  Save of secret2 failed.");

            // Now delete it.
            Assert.True(await secretEngine.DeleteSecretVersion(secret2));
        }
Esempio n. 10
0
        public async Task TestCapabilitiesFunctionality()
        {
            string appBE = _uniqueKeys.GetKey("appBE");
            string kv2BE = _uniqueKeys.GetKey("kv2BE");


            // 1 - Setup backends needed for testing.
            // We need to setup a KV2 Secrets engine and also an AppRole Backend.
            // Create an Authentication method of App Role.	- This only needs to be done when the Auth method is created.
            AuthMethod am = new AuthMethod(appBE, EnumAuthMethods.AppRole);
            await _vaultSystemBackend.AuthEnable(am);

            // Create a KV2 Secret Mount if it does not exist.
            await _vaultSystemBackend.SysMountCreate(kv2BE, "ClientTest KeyValue 2 Secrets", EnumSecretBackendTypes.KeyValueV2);


            // Now we create secret backend
            VaultAgentAPI vault = await VaultServerRef.ConnectVault("PolicyBeCapa2");

            AppRoleAuthEngine authEngine   = (AppRoleAuthEngine)vault.ConnectAuthenticationBackend(EnumBackendTypes.A_AppRole, appBE, appBE);
            KV2SecretEngine   secretEngine =
                (KV2SecretEngine)vault.ConnectToSecretBackend(EnumSecretBackendTypes.KeyValueV2, "KV2 Secrets", kv2BE);


            // 2. Setup the policy to provide the permissions to test against.
            VaultPolicyContainer policyContainer = new VaultPolicyContainer("capa");

            VaultPolicyPathItem vppi1 = new VaultPolicyPathItem(kv2BE, "data/app/appA/*");
            VaultPolicyPathItem vppi2 = new VaultPolicyPathItem(kv2BE + "data/app/appA/subItem/*");
            VaultPolicyPathItem vppi3 = new VaultPolicyPathItem(kv2BE + "metadata/app/appA/*");
            VaultPolicyPathItem vppi4 = new VaultPolicyPathItem(kv2BE + "data/shared/*");

            vppi1.FullControl = true;
            vppi2.FullControl = true;
            vppi3.ReadAllowed = true;
            vppi4.ReadAllowed = true;

            policyContainer.AddPolicyPathObject(vppi1);
            policyContainer.AddPolicyPathObject(vppi2);
            policyContainer.AddPolicyPathObject(vppi3);
            policyContainer.AddPolicyPathObject(vppi4);

            await _vaultSystemBackend.SysPoliciesACLCreate(policyContainer);


            // 3. Now create an App Role & Secret ID
            string  roleName = _uniqueKeys.GetKey("role");
            AppRole appRole  = new AppRole(roleName);

            appRole.Policies.Add(policyContainer.Name);
            appRole = await authEngine.SaveRoleAndReturnRoleObject(appRole);

            AppRoleSecret secretID = await authEngine.CreateSecretID(appRole.Name);


            // 4.  Now we can create a token against that
            Token token = await authEngine.Login(appRole.RoleID, secretID.ID);


            // 5.  Now we can finally test the capabilities of that token.
            List <string> paths = new List <string>();
            string        path1 = kv2BE + "/data/app/appA/subItem";
            string        path2 = kv2BE + "/data/app/appB/subItem";
            string        path3 = kv2BE + "/noaccess/app/appA";
            string        path4 = kv2BE + "/data/noaccess/app/appA/subItem";

            paths.Add(path1);
            paths.Add(path2);
            paths.Add(path3);
            paths.Add(path4);



            Dictionary <string, List <string> > permissions;

            permissions = await _vaultSystemBackend.GetTokenCapabilityOnPaths(token.ID, paths);

            // 6. Validate the results.
            Assert.AreEqual(4, permissions.Count, "A10:  Expected to receive 4 permission objects back.");
            Assert.AreEqual(6, permissions[path1].Count, "A20:  Expected the item: " + path1 + " to contain 6 permissions.");
            Assert.AreEqual(1, permissions[path2].Count, "A30:  Expected the item: " + path2 + " to contain 1 deny permission.");
            CollectionAssert.Contains(permissions[path2], "deny", "A35:  Expected the permission to be deny for path: " + path2);
            Assert.AreEqual(1, permissions[path3].Count, "A40:  Expected the item: " + path3 + " to contain 1 deny permission.");
            CollectionAssert.Contains(permissions[path3], "deny", "A35:  Expected the permission to be deny for path: " + path3);
            Assert.AreEqual(1, permissions[path4].Count, "A40:  Expected the item: " + path4 + " to contain 1 deny permission.");
            CollectionAssert.Contains(permissions[path4], "deny", "A35:  Expected the permission to be deny for path: " + path4);
        }
Esempio n. 11
0
        public async Task LoginWithInvalidCredentials_GeneratesExpectedError()
        {
            string  roleName_A = _uniqueKeys.GetKey("FailLogin");
            AppRole roleA      = new AppRole(roleName_A);

            Assert.True(await _appRoleAuthEngine.SaveRole(roleA), "A1: Saving the role failed.");

            // Read the role ID back.
            string roleID = await _appRoleAuthEngine.ReadRoleID(roleA.Name);

            // Now create the a secret
            AppRoleSecret secret_A = await _appRoleAuthEngine.GenerateSecretID(roleA.Name);


            // Now attempt to login
            VaultInvalidDataException e = Assert.ThrowsAsync <VaultInvalidDataException> (async() => await _appRoleAuthEngine.Login(roleID, ""),
                                                                                          "A1: Expected Login with bad Secret to throw the [VaultInvalidDataException] but it did not.");

            Assert.AreEqual(EnumVaultExceptionCodes.LoginSecretID_NotFound, e.SpecificErrorCode, "A2: Expected to see the specificErrorCode field set to [LoginSecretID_NotFound] but it was set to " + e.SpecificErrorCode);

            // Now try with invalid Role ID.
            VaultInvalidDataException e2 = Assert.ThrowsAsync <VaultInvalidDataException>(async() => await _appRoleAuthEngine.Login("", secret_A.ID),
                                                                                          "A1: Expected Login with bad RoleID to throw the [VaultInvalidDataException] but it did not.");

            Assert.AreEqual(EnumVaultExceptionCodes.LoginRoleID_NotFound, e2.SpecificErrorCode, "A2: Expected to see the specificErrorCode field set to [LoginRoleID_NotFound] but it was set to " + e2.SpecificErrorCode);
        }