Пример #1
0
        public async Task TokenEngineSetup()
        {
            // Build Connection to Vault.
            vault = await VaultServerRef.ConnectVault("TokenEng");

            _tokenAuthEngine = (TokenAuthEngine)vault.ConnectAuthenticationBackend(EnumBackendTypes.A_Token);
        }
Пример #2
0
        public async Task Transit_Init()
        {
            if (_vaultAgentAPI != null)
            {
                return;
            }


            // Build Connection to Vault.
            _vaultAgentAPI = await VaultServerRef.ConnectVault("TransitSecEng");

            //new VaultAgentAPI("transitVault", VaultServerRef.ipAddress, VaultServerRef.ipPort, VaultServerRef.rootToken, true);


            // Create unique name for the transit Backend we will use to test with.
            string transitMountName = _uniqueKeys.GetKey("TRANsit");


            // Get Connection to Vault System backend
            _systemBackend = new VaultSystemBackend(_vaultAgentAPI.TokenID, _vaultAgentAPI);
            Assert.IsTrue(await _systemBackend.CreateSecretBackendMount(EnumSecretBackendTypes.Transit, transitMountName, transitMountName,
                                                                        "Transit Bckend Testing"), "A10:  Failed to Create the Transit Backend");
            _transitSecretEngine = (TransitSecretEngine)_vaultAgentAPI.ConnectToSecretBackend(EnumSecretBackendTypes.Transit, transitMountName, transitMountName);



//            _transitSecretEngine =
            //			(TransitSecretEngine) await _vaultAgentAPI.CreateSecretBackendMount(EnumSecretBackendTypes.Transit, transitMountName, transitMountName,
            //		                                                                    "Transit Bckend Testing");
            Assert.NotNull(_transitSecretEngine, "Transit Backend was returned null upon creation.");
        }
Пример #3
0
        public async Task Backend_Init()
        {
            if (_vaultSystemBackend != null)
            {
                return;
            }

            // Build Connection to Vault.
            _vaultAgentAPI = await VaultServerRef.ConnectVault("PolicyBE");

            // Create a new system Backend Mount for this series of tests.
            _vaultSystemBackend = new VaultSystemBackend(_vaultAgentAPI.TokenID, _vaultAgentAPI);



            // Create the backend.
            _beName = _uniqueKeys.GetKey("beP");
            VaultSysMountConfig testBE = new VaultSysMountConfig();

            Assert.True(await _vaultSystemBackend.SysMountCreate(_beName, "KeyValue2 Policy Testing Backend", EnumSecretBackendTypes.KeyValueV2),
                        "A10:  Enabling backend " + _beName + " failed.");

            // Create the Root Engine that we will use
            //_vaultRootAgentAPI = new VaultAgentAPI("Root", _vaultAgentAPI.IP, _vaultAgentAPI.Port, _vaultAgentAPI.Token.ID);
            _vaultRootAgentAPI = await VaultServerRef.ConnectVault("PolicyBE_Alt");

            _rootEng = (KV2SecretEngine)_vaultRootAgentAPI.ConnectToSecretBackend(EnumSecretBackendTypes.KeyValueV2, _beName, _beName);

            _vaultAgents = new List <VaultAgentAPI>();
        }
Пример #4
0
        public async Task RevokeSelfTokenSucceeds()
        {
            VaultAgentAPI v1 = await VaultServerRef.ConnectVault("TempVault");

            //new VaultAgentAPI("TempVault", VaultServerRef.ipAddress, VaultServerRef.ipPort, VaultServerRef.rootToken);
            string tokenName = UK.GetKey("tmpTok");

            // Create a new token.
            TokenNewSettings tokenNewSettings = new TokenNewSettings()
            {
                Name = tokenName,
            };

            Token token = await _tokenAuthEngine.CreateToken(tokenNewSettings);

            Assert.NotNull(token, "A1:  Error creating a new token - expected to receive the new token back, instead we received a null value.");

            // Now set vault to use the new token.
            v1.Token = token;
            Assert.AreNotEqual(VaultServerRef.rootToken, token.ID, "A2:  Expected the Vault object to have a different token.  But was still set at initial token.");

            // And then revoke.
            Assert.IsTrue(await v1.RevokeActiveToken());
            Assert.IsNull(v1.Token);

            // Now try and reset the Vault to use the old token. It should fail.
            v1.Token = token;
            Assert.ThrowsAsync <VaultForbiddenException> (async() => await v1.RefreshActiveToken());
        }
Пример #5
0
        // Create the token engines for a successful test and then the control test.
        private async Task <(KV2SecretEngine engKV2OK, KV2SecretEngine engKV2FAIL)> SetupTokenEngines(string policyWithPermission)
        {
            // Get connection to Token Engine so we can create tokens.
            TokenAuthEngine tokenEng = (TokenAuthEngine)_vaultAgentAPI.ConnectAuthenticationBackend(EnumBackendTypes.A_Token);

            // AA - The token that will have the policy.
            TokenNewSettings tokenASettings = new TokenNewSettings();

            tokenASettings.Policies.Add(policyWithPermission);
            Token tokenOK = await tokenEng.CreateToken(tokenASettings);

            // AB - The token that will not have the policy.
            TokenNewSettings tokenBSettings = new TokenNewSettings();

            tokenBSettings.Policies.Add("default");
            Token tokenFAIL = await tokenEng.CreateToken(tokenBSettings);


            // AC - Create 2 Vault Instances that will use each Token.
            VaultAgentAPI vaultOK = await VaultServerRef.ConnectVault("OKVault", tokenOK.ID);

            VaultAgentAPI vaultFail = await VaultServerRef.ConnectVault("FailVault", tokenFAIL.ID);

            //VaultAgentAPI vaultOK = new VaultAgentAPI("OKToken", _vaultAgentAPI.IP, _vaultAgentAPI.Port, tokenOK.ID);
            //VaultAgentAPI vaultFail = new VaultAgentAPI("FAILToken", _vaultAgentAPI.IP, _vaultAgentAPI.Port, tokenFAIL.ID);
            _vaultAgents.Add(vaultOK);
            _vaultAgents.Add(vaultFail);


            // AD - Create the KeyValue Engines for each Token
            KV2SecretEngine engKV2OK   = (KV2SecretEngine)vaultOK.ConnectToSecretBackend(EnumSecretBackendTypes.KeyValueV2, _beName, _beName);
            KV2SecretEngine engKV2FAIL = (KV2SecretEngine)vaultFail.ConnectToSecretBackend(EnumSecretBackendTypes.KeyValueV2, _beName, _beName);

            return(engKV2OK, engKV2FAIL);
        }
Пример #6
0
        public async Task CreateToken()
        {
            // SETUP

            // We need our own vault since we will be manipulating the token value
            VaultAgentAPI ourVault = await VaultServerRef.ConnectVault("TokenTest");

            TokenAuthEngine ourTokenAuthEngine = (TokenAuthEngine)ourVault.ConnectAuthenticationBackend(EnumBackendTypes.A_Token);

            // Need a Token Role so we can autogenerate a token
            TokenRole tokenRole = new TokenRole();

            tokenRole.Name = UK.GetKey();
            await ourTokenAuthEngine.SaveTokenRole(tokenRole);

            string           tokenName        = "Name" + tokenRole.Name;
            TokenNewSettings tokenNewSettings = new TokenNewSettings()
            {
                Name          = tokenName,
                NumberOfUses  = 6,
                NoParentToken = true,
                RoleName      = tokenRole.Name
            };

            Token token = await ourTokenAuthEngine.CreateToken(tokenNewSettings);

            Assert.NotNull(token, "A10:  Expected to receive the new token back, instead we received a null value.");

            // Read the token we just created.
            //Token token = await _tokenAuthEngine.GetTokenWithID(tokenID);
            Assert.IsNotNull(token, "A20: No Token returned.  Was expecting one.");

            ourVault.TokenID = token.ID;
            Assert.AreEqual(ourVault.TokenID, token.ID, "A30: Vault did not store token correctly");
        }
Пример #7
0
        public async Task Setup()
        {
            // Build Connection to Vault.
            _vault = await VaultServerRef.ConnectVault("AppRoleVault");

            //_vault = new VaultAgentAPI ("AppRoleVault", VaultServerRef.ipAddress, VaultServerRef.ipPort, VaultServerRef.rootToken, true);
            _vaultSystemBackend = new VaultSystemBackend(_vault.TokenID, _vault);

            _ldapMountName = _uniqueKeys.GetKey("LDAP");

            // Define the engine.
            _ldapAuthEngine = (LdapAuthEngine)_vault.ConnectAuthenticationBackend(EnumBackendTypes.A_LDAP, "ldap_test", _ldapMountName);

            // Now create the Mount point.
            AuthMethod authMethod = new AuthMethod(_ldapMountName, EnumAuthMethods.LDAP);

            authMethod.Description = "Ldap Test";
            Assert.True(await _vaultSystemBackend.AuthEnable(authMethod), "A10:  Expected the LDAP Backend to have been enabled.");

            // Now build the LDAP Backend.
            _origConfig = _ldapAuthEngine.GetLDAPConfigFromFile(@"C:\a_Dev\Configs\LDAP_Test.json");
            SetLDAPConfig(_ldapMountName, _origConfig);

            // Save the Config.  We do this here so the SetLDAPConfig can be used for multiple engines.
            Assert.True(await _ldapAuthEngine.ConfigureLDAPBackend(_origConfig), "A100:  Expected the LDAP Configuration method to return True");

            // Initialize the LDAP Login Connector.
            _ldapLoginConnector = new LDAPLoginConnector(_vault, _ldapAuthEngine.MountPoint, "Test LDAP Backend");

            // Load the Test Data Object
            LoadTestData();
        }
Пример #8
0
        public async Task VaultAgentTest_OneTimeSetup()
        {
            _uk   = new UniqueKeys();
            name  = _uk.GetKey("vlt");
            vault = await VaultServerRef.ConnectVault(name);

            //new VaultAgentAPI(name, VaultServerRef.ipAddress, VaultServerRef.ipPort, VaultServerRef.rootToken);
        }
Пример #9
0
        public async Task RevokeTokenWithChildren_ChildrenOrphaned()
        {
            // Create a new token.
            string           tokenName        = UK.GetKey("ParentOrp");
            TokenNewSettings tokenNewSettings = new TokenNewSettings()
            {
                Name = tokenName,
            };
            Token parent = await _tokenAuthEngine.CreateToken(tokenNewSettings);

            Assert.NotNull(parent, "A1:  Error creating the parent token - expected to receive the new token back, instead we received a null value.");

            VaultAgentAPI v1 = await VaultServerRef.ConnectVault("TokenAuth2", parent.ID);

            TokenAuthEngine TAE = (TokenAuthEngine)v1.ConnectAuthenticationBackend(EnumBackendTypes.A_Token);


            // Now create 3 child tokens.

            Token token1 = await TAE.CreateToken(tokenNewSettings);

            Assert.NotNull(token1, "A2:  Error creating a new token - expected to receive the new token back, instead we received a null value.");

            // Token 2.
            tokenNewSettings.Name = "Token2";
            Token token2 = await TAE.CreateToken(tokenNewSettings);

            Assert.NotNull(token2, "A3:  Error creating a new token - expected to receive the new token back, instead we received a null value.");

            // Token 3.
            tokenNewSettings.Name = "Token3";
            Token token3 = await TAE.CreateToken(tokenNewSettings);

            Assert.NotNull(token3, "A4:  Error creating a new token - expected to receive the new token back, instead we received a null value.");


            // Now revoke the Parent token.
            Assert.IsTrue(await _tokenAuthEngine.RevokeToken(parent.ID, false), "A5:  Revocation of parent token was not successful.");

            Token parent2 = await _tokenAuthEngine.GetTokenWithID(parent.ID);

            Assert.IsNull(parent2, "A6:  The parent token should have been revoked.  But it still exists.");

            // Validate that each of the child tokens is revoked as well.
            Token a1 = await _tokenAuthEngine.GetTokenWithID(token1.ID);

            Token a2 = await _tokenAuthEngine.GetTokenWithID(token2.ID);

            Token a3 = await _tokenAuthEngine.GetTokenWithID(token3.ID);

            Assert.IsNotNull(a1, "A7:  Expected the child token to still exist.  But it is null");
            Assert.IsNotNull(a2, "A8:  Expected the child token to still exist.  But it is null");
            Assert.IsNotNull(a3, "A9:  Expected the child token to still exist.  But it is null");
            Assert.IsTrue(a1.IsOrphan, "A10: Expected token to be marked as an orphan.");
            Assert.IsTrue(a2.IsOrphan, "A11: Expected token to be marked as an orphan.");
            Assert.IsTrue(a3.IsOrphan, "A12: Expected token to be marked as an orphan.");
        }
Пример #10
0
        public async Task TokenPropertiesSet_WhenPassedValidToken()
        {
            VaultAgentAPI v1 = await VaultServerRef.ConnectVault(name);

            //new VaultAgentAPI(name, VaultServerRef.ipAddress, VaultServerRef.ipPort, VaultServerRef.rootToken);

            // Vault instance was created in one time setup.
            Assert.AreEqual(VaultServerRef.rootToken, v1.Token.ID);
            Assert.IsNotEmpty(v1.Token.APIPath);
            Assert.Greater(v1.Token.CreationTime, 1);
        }
Пример #11
0
        public async Task Setup()
        {
            if (_vaultAgentAPI != null)
            {
                return;
            }

            // Build Connection to Vault.
            _vaultAgentAPI = await VaultServerRef.ConnectVault("VaultSecretEntry");

            //_vaultAgentAPI = new VaultAgentAPI("testa", VaultServerRef.ipAddress, VaultServerRef.ipPort, VaultServerRef.rootToken, true);


            // We will create 3 KV2 mounts in the Vault instance.  One for testing with CAS on, one with CAS off, and then a generic default (CAS off).
            string noCasMountName = _uniqueKey.GetKey("NoCas");
            string casMountName   = _uniqueKey.GetKey("CAS");


            // Config settings for all the mounts.
            VaultSysMountConfig config = new VaultSysMountConfig
            {
                DefaultLeaseTTL   = "30m",
                MaxLeaseTTL       = "90m",
                VisibilitySetting = "hidden"
            };

            // Get Connection to Vault System backend
            _systemBackend = new VaultSystemBackend(_vaultAgentAPI.TokenID, _vaultAgentAPI);
            Assert.IsTrue(await _systemBackend.CreateSecretBackendMount(EnumSecretBackendTypes.KeyValueV2, noCasMountName, noCasMountName,
                                                                        "No CAS Mount Test", config), "Failed to Create the NOCas KV2 secret backend");
            _noCASMount = (KV2SecretEngine)_vaultAgentAPI.ConnectToSecretBackend(EnumSecretBackendTypes.KeyValueV2, noCasMountName, noCasMountName);

            Assert.IsTrue(await _systemBackend.CreateSecretBackendMount(EnumSecretBackendTypes.KeyValueV2, casMountName, casMountName,
                                                                        "CAS Mount Test", config), "Failed to create the CAS Mount KV2 Secret Backend");
            _casMount = (KV2SecretEngine)_vaultAgentAPI.ConnectToSecretBackend(EnumSecretBackendTypes.KeyValueV2, casMountName, casMountName);


            Assert.NotNull(_noCASMount);
            Assert.NotNull(_casMount);

            // This is required as of Vault 1.0  It now seems to take a second or 2 to upgrade the mount from KV1 to KV2.
            Thread.Sleep(2500);

            // Set backend mount config.
            Assert.True(await _noCASMount.SetBackendConfiguration(8, false));
            Assert.True(await _casMount.SetBackendConfiguration(8, false));



            // Setup the DateTimeOffset Fields
            _theDate = DateTimeOffset.FromUnixTimeSeconds(_unixEpochTime);
        }
Пример #12
0
        public async Task Identity_Init()
        {
            if (_vaultAgentAPI != null)
            {
                return;
            }

            // Build Connection to Vault.
            _vaultAgentAPI = await VaultServerRef.ConnectVault("IdTest");

            //new VaultAgentAPI("IdentityTest", VaultServerRef.ipAddress, VaultServerRef.ipPort, VaultServerRef.rootToken, true);
            _idEngine = (IdentitySecretEngine)_vaultAgentAPI.ConnectToSecretBackend(EnumSecretBackendTypes.Identity);
        }
Пример #13
0
        public async Task Backend_Init()
        {
            if (_vaultSystemBackend != null)
            {
                return;
            }

            // Build Connection to Vault.
            _vaultAgentAPI = await VaultServerRef.ConnectVault("TransitVault");

            //new VaultAgentAPI("transitVault", VaultServerRef.ipAddress, VaultServerRef.ipPort, VaultServerRef.rootToken, true);

            // Create a new system Backend Mount for this series of tests.
            _vaultSystemBackend = new VaultSystemBackend(_vaultAgentAPI.TokenID, _vaultAgentAPI);
        }
Пример #14
0
        public async Task NormalLogin()
        {
            // SETUP

            // We need our own vault since we will be manipulating the token value
            VaultAgentAPI ourVault = await VaultServerRef.ConnectVault("TokenTest");

            TokenAuthEngine ourTokenAuthEngine = (TokenAuthEngine)ourVault.ConnectAuthenticationBackend(EnumBackendTypes.A_Token);

            // Need a Token Role so we can autogenerate a token
            TokenRole tokenRole = new TokenRole();

            UniqueKeys UK = new UniqueKeys("", "");       // Unique Key generator

            tokenRole.Name = UK.GetKey();
            await ourTokenAuthEngine.SaveTokenRole(tokenRole);

            string           tokenName        = "Name" + tokenRole.Name;
            TokenNewSettings tokenNewSettings = new TokenNewSettings()
            {
                Name          = tokenName,
                NumberOfUses  = 6,
                NoParentToken = true,
                RoleName      = tokenRole.Name
            };

            Token token = await ourTokenAuthEngine.CreateToken(tokenNewSettings);

            Assert.NotNull(token, "A10:  Expected to receive the new token back, instead we received a null value.");

            // Read the token we just created.
            //Token token = await _tokenAuthEngine.GetTokenWithID(tokenID);
            Assert.IsNotNull(token, "A20: No Token returned.  Was expecting one.");


            VaultAgentAPI vault2 = await VaultServerRef.ConnectVault("TokenLoginTest");

            TokenLoginConnector loginConnector = new TokenLoginConnector(vault2, "test");

            loginConnector.TokenId = token.ID;
            Assert.IsTrue(await loginConnector.Connect(), "A30:  Login Failed");
        }
Пример #15
0
        public async Task AppRoleAuthEngineSetup()
        {
            // Build Connection to Vault.
            _vault = await VaultServerRef.ConnectVault("AppRoleVault");

            //_vault = new VaultAgentAPI("AppRoleVault", VaultServerRef.ipAddress, VaultServerRef.ipPort);  //, VaultServerRef.rootToken,true);
            _vaultSystemBackend = new VaultSystemBackend(_vault.TokenID, _vault);


            string approleMountName = _uniqueKeys.GetKey("AppAuth");


            // Create an AppRole authentication connection.
            _appRoleAuthEngine = (AppRoleAuthEngine)_vault.ConnectAuthenticationBackend(EnumBackendTypes.A_AppRole, "AppRole", approleMountName);


            // Create an Authentication method of App Role.	- This only needs to be done when the Auth method is created.
            AuthMethod am = new AuthMethod(approleMountName, EnumAuthMethods.AppRole);
            bool       rc = await _vaultSystemBackend.AuthEnable(am);
        }
Пример #16
0
        public async Task Secret_Init()
        {
            if (_vaultAgentAPI != null)
            {
                return;
            }

            // Build Connection to Vault.
            _vaultAgentAPI = await VaultServerRef.ConnectVault("SecretBackEnd");

            string mountName = _uniqueKeys.GetKey("SEC");

            // Get Connection to Vault System backend
            _systemBackend = new VaultSystemBackend(_vaultAgentAPI.TokenID, _vaultAgentAPI);
            Assert.IsTrue(await _systemBackend.CreateSecretBackendMount(EnumSecretBackendTypes.Secret, mountName, mountName, "Secret V1 Backend"), "A10:  Failed to create Secret Backend");

            _keyValueSecretEngine = (KeyValueSecretEngine)_vaultAgentAPI.ConnectToSecretBackend(EnumSecretBackendTypes.Secret, mountName, mountName);

//            _keyValueSecretEngine = (KeyValueSecretEngine)await _vaultAgentAPI.CreateSecretBackendMount(EnumSecretBackendTypes.Secret, mountName, mountName, "Secret V1 Backend");

            Assert.NotNull(_keyValueSecretEngine);
            return;
        }
Пример #17
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);
        }
Пример #18
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));
        }