/// <summary> /// </summary> /// <returns></returns> public async Task PerformRoleMasterTasks() { KV2SecretEngine secEngine = (KV2SecretEngine)_vaultAgent.ConnectToSecretBackend(EnumSecretBackendTypes.KeyValueV2, "Sheakley KV2 Secrets", _beKV2Name); // Create the Path1 "secret" KV2Secret a = new KV2Secret("path1"); var result = await secEngine.TryReadSecret(a); if (!result.IsSuccess) { await secEngine.SaveSecret(a, KV2EnumSecretSaveOptions.OnlyIfKeyDoesNotExist); } // Create the AppData Folder KV2Secret b = new KV2Secret(Constants.appData); result = await secEngine.TryReadSecret(b); if (!result.IsSuccess) { await secEngine.SaveSecret(b, KV2EnumSecretSaveOptions.OnlyIfKeyDoesNotExist); } return; }
// 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); }
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>(); }
/// <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); } }
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,) }
/// <summary> /// Saves the given Secret to the Vault /// </summary> /// <param name="secret">The secret to save</param> /// <returns></returns> private async Task <bool> SaveSecret(KV2SecretEngine engine, KV2Secret secret) { try { return(await engine.SaveSecret(secret, KV2EnumSecretSaveOptions.AlwaysAllow)); } catch (VaultForbiddenException e) { return(false); } }
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); }
/// <summary> /// Reads the Secret from the Engine /// </summary> /// <param name="engine"></param> /// <param name="secretPath"></param> /// <returns></returns> private async Task <(bool isSuccess, KV2Secret theSecret)> ReadSecret(KV2SecretEngine engine, string secretPath) { try { KV2Secret secret = await engine.ReadSecret <KV2Secret>(secretPath); return(true, secret); } catch (VaultForbiddenException e) { return(false, null); } }
public async Task Run() { await CreateBackendMounts(); _appRoleAuthEngine = (AppRoleAuthEngine)_vault.ConnectAuthenticationBackend(EnumBackendTypes.A_AppRole, _beAuthName, _beAuthName); _idEngine = (IdentitySecretEngine)_vault.ConnectToSecretBackend(EnumSecretBackendTypes.Identity); _kv2SecretEngine = (KV2SecretEngine)_vault.ConnectToSecretBackend(EnumSecretBackendTypes.KeyValueV2, "KV2 Secrets", _beKV2Name); await AppRoleBE_UpdateRoleID(); Console.WriteLine("Finished With Optimization Run. Press any key to continue."); Console.ReadKey(); }
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> /// Start The Scenario /// </summary> /// <returns></returns> public async Task Run() { // Create the mounts and policies and store in Vault await CreateBackendMounts(); await CreatePolicies(); // Mount the Secret Engine _secretEngine = (KV2SecretEngine)_masterVaultAgent.ConnectToSecretBackend(EnumSecretBackendTypes.KeyValueV2, _beKV2Name, _beKV2Name); // Mount the Authentication Engine, so roles can login _appRoleAuthEngine = (AppRoleAuthEngine)_masterVaultAgent.ConnectAuthenticationBackend(EnumBackendTypes.A_AppRole, _AppBEName, _AppBEName); // Create the roles - assigning policies to the roles roleMother = await CreateRole("roleMother", _policyHouse_Full.Name); roleFather = await CreateRole("roleFather", _policyHouse_Full.Name); roleTeenager = await CreateRole("roleTeenager", _policyTeenagerBedroom_Full.Name, _policyKitchenRefrigerator_Write.Name, _policyHouseOnly_Read.Name, _policyKitchen_Write.Name); roleToddler = await CreateRole("roleToddler", _policyToddlerBedroom_Full.Name); // Create Login SIDS for each role _sidMother = await _appRoleAuthEngine.CreateSecretID(roleMother.Name); _sidFather = await _appRoleAuthEngine.CreateSecretID(roleFather.Name); _sidTeenager = await _appRoleAuthEngine.CreateSecretID(roleTeenager.Name); _sidToddler = await _appRoleAuthEngine.CreateSecretID(roleToddler.Name); // Set the Mother role to have full access. KV2Secret a = new KV2Secret(HOUSE.HOUSE_PATH); await SaveSecret(_secretEngine, a); // It's important to note: Up to now we have been using the Master token to create objects, secret stores, policies and the initial House Secret. From here forward each // user will login and perform the actions under their user ID. await Perform_MotherTasks(); await Perform_TeenTasks(); }
/// <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); }
public async Task Setup() { string rootToken = "tokenA"; string ip = "127.0.0.1"; int port = 47002; Uri vaultURI = new Uri("http://" + ip + ":" + port); // Connect to Vault, add an authentication backend of AppRole. _vaultAgent = new VaultAgentAPI("Vault", vaultURI); TokenLoginConnector loginConnector = new TokenLoginConnector(_vaultAgent, "Token Authenticator", rootToken); await CreateBackendMounts(); _appRoleAuthEngine = (AppRoleAuthEngine)_vaultAgent.ConnectAuthenticationBackend(EnumBackendTypes.A_AppRole, _beAuthName, _beAuthName); _secretEngine = (KV2SecretEngine)_vaultAgent.ConnectToSecretBackend(EnumSecretBackendTypes.KeyValueV2, "Benchmarking KV2 Secrets", _beKV2Name); await SetupRoles(); }
/// <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); } }
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)); }
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); }
/// <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); }