SafesService { public ResponseEntity<String> addGroupToSafe(String token, SafeGroup safeGroup, UserDetails userDetails) { OIDCGroup oidcGroup = new OIDCGroup(); log.debug(JSONUtil.getJSON(ImmutableMap.<String, String>builder(). put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()). put(LogMessage.ACTION, "Add Group to SDB"). put(LogMessage.MESSAGE, String.format ("Trying to add Group to SDB folder")). put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL).toString()). build())); if(!ControllerUtil.areSafeGroupInputsValid(safeGroup)) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("{\"errors\":[\"Invalid input values\"]}"); } String jsonstr = JSONUtil.getJSON(safeGroup); if (TVaultConstants.USERPASS.equals(vaultAuthMethod)) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("{\"errors\":[\"This operation is not supported for Userpass authentication. \"]}"); } ObjectMapper objMapper = new ObjectMapper(); Map<String,String> requestMap = null; try { requestMap = objMapper.readValue(jsonstr, new TypeReference<Map<String,String>>() {}); } catch (IOException e) { log.error(e); } String groupName = requestMap.get("groupname"); String path = requestMap.get("path"); String access = requestMap.get("access"); groupName = (groupName !=null) ? groupName.toLowerCase() : groupName; path = (path != null) ? path.toLowerCase() : path; access = (access != null) ? access.toLowerCase(): access; boolean canAddGroup = ControllerUtil.canAddPermission(path, token); if(canAddGroup){ String folders[] = path.split("[/]+"); String policyPrefix =""; switch (access){ case TVaultConstants.READ_POLICY: policyPrefix = "r_"; break ; case TVaultConstants.WRITE_POLICY: policyPrefix = "w_" ;break; case TVaultConstants.DENY_POLICY: policyPrefix = "d_" ;break; } if(TVaultConstants.EMPTY.equals(policyPrefix)){ return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body("{\"errors\":[\"Incorrect access requested. Valid values are read,write,deny \"]}"); } String policy = policyPrefix+folders[0]+"_"+folders[1]; String r_policy = "r_"; String w_policy = "w_"; String d_policy = "d_"; if (folders.length > 0) { for (int index = 0; index < folders.length; index++) { if (index == folders.length -1 ) { r_policy += folders[index]; w_policy += folders[index]; d_policy += folders[index]; } else { r_policy += folders[index] +"_"; w_policy += folders[index] +"_"; d_policy += folders[index] +"_"; } } } List<String> policies = new ArrayList<>(); List<String> currentpolicies = new ArrayList<>(); Response getGrpResp = new Response(); if(TVaultConstants.LDAP.equals(vaultAuthMethod)){ getGrpResp = reqProcessor.process("/auth/ldap/groups","{\"groupname\":\""+groupName+"\"}",token); }else if (TVaultConstants.OIDC.equals(vaultAuthMethod)) { oidcGroup= oidcUtil.getIdentityGroupDetails(groupName, token); if (oidcGroup != null) { getGrpResp.setHttpstatus(HttpStatus.OK); getGrpResp.setResponse(oidcGroup.getPolicies().toString()); } else { getGrpResp.setHttpstatus(HttpStatus.BAD_REQUEST); } } String responseJson=""; if(HttpStatus.OK.equals(getGrpResp.getHttpstatus())){ responseJson = getGrpResp.getResponse(); try { if (TVaultConstants.LDAP.equals(vaultAuthMethod)) { currentpolicies = ControllerUtil.getPoliciesAsListFromJson(objMapper, responseJson); } else if (TVaultConstants.OIDC.equals(vaultAuthMethod)) { currentpolicies.addAll(oidcGroup.getPolicies()); } } catch (IOException e) { log.error(e); } policies.addAll(currentpolicies); policies.remove(r_policy); policies.remove(w_policy); policies.remove(d_policy); policies.add(policy); }else{ policies.add(policy); } String policiesString = StringUtils.join(policies, ","); String currentpoliciesString = StringUtils.join(currentpolicies, ","); Response ldapConfigresponse = new Response(); if (TVaultConstants.LDAP.equals(vaultAuthMethod)) { ldapConfigresponse = ControllerUtil.configureLDAPGroup(groupName, policiesString, token); } else if (TVaultConstants.OIDC.equals(vaultAuthMethod)) { ldapConfigresponse = oidcUtil.updateGroupPolicies(token, groupName, policies, currentpolicies, oidcGroup!=null?oidcGroup.getId(): null); oidcUtil.renewUserToken(userDetails.getClientToken()); } if (ldapConfigresponse.getHttpstatus().equals(HttpStatus.NO_CONTENT) || ldapConfigresponse.getHttpstatus().equals(HttpStatus.OK)) { Map<String,String> params = new HashMap<String,String>(); params.put("type", "groups"); params.put("name",groupName); params.put("path",path); params.put("access",access); Response metadataResponse = ControllerUtil.updateMetadata(params,token); if(metadataResponse !=null && HttpStatus.NO_CONTENT.equals(metadataResponse.getHttpstatus())){ log.debug(JSONUtil.getJSON(ImmutableMap.<String, String>builder(). put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()). put(LogMessage.ACTION, "Add Group to SDB"). put(LogMessage.MESSAGE, "Group configuration Success."). put(LogMessage.STATUS, metadataResponse.getHttpstatus().toString()). put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL).toString()). build())); return ResponseEntity.status(HttpStatus.OK).body("{\"messages\":[\"Group is successfully associated with Safe\"]}"); }else{ String safeType = ControllerUtil.getSafeType(path); String safeName = ControllerUtil.getSafeName(path); List<String> safeNames = ControllerUtil.getAllExistingSafeNames(safeType, token); String newPath = path; if (safeNames != null ) { for (String existingSafeName: safeNames) { if (existingSafeName.equalsIgnoreCase(safeName)) { newPath = safeType + "/" + existingSafeName; break; } } } params.put("path",newPath); metadataResponse = ControllerUtil.updateMetadata(params,token); if (metadataResponse !=null && HttpStatus.NO_CONTENT.equals(metadataResponse.getHttpstatus())) { log.debug(JSONUtil.getJSON(ImmutableMap.<String, String>builder(). put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()). put(LogMessage.ACTION, "Add Group to SDB"). put(LogMessage.MESSAGE, "Group configuration Success."). put(LogMessage.STATUS, metadataResponse.getHttpstatus().toString()). put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL).toString()). build())); return ResponseEntity.status(HttpStatus.OK).body("{\"messages\":[\"Group is successfully associated with Safe\"]}"); } else { log.error(JSONUtil.getJSON(ImmutableMap.<String, String>builder(). put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()). put(LogMessage.ACTION, "Add Group to SDB"). put(LogMessage.MESSAGE, "Group configuration failed."). put(LogMessage.RESPONSE, (null!=metadataResponse)?metadataResponse.getResponse():TVaultConstants.EMPTY). put(LogMessage.STATUS, (null!=metadataResponse)?metadataResponse.getHttpstatus().toString():TVaultConstants.EMPTY). put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL).toString()). build())); if (TVaultConstants.LDAP.equals(vaultAuthMethod)) { ldapConfigresponse = ControllerUtil.configureLDAPGroup(groupName, currentpoliciesString, token); } else if (TVaultConstants.OIDC.equals(vaultAuthMethod)) { ldapConfigresponse = oidcUtil.updateGroupPolicies(token, groupName, currentpolicies, currentpolicies, oidcGroup.getId()); oidcUtil.renewUserToken(userDetails.getClientToken()); } if(ldapConfigresponse.getHttpstatus().equals(HttpStatus.NO_CONTENT)){ log.error(JSONUtil.getJSON(ImmutableMap.<String, String>builder(). put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()). put(LogMessage.ACTION, "Add Group to SDB"). put(LogMessage.MESSAGE, "Reverting user policy update failed"). put(LogMessage.RESPONSE, (null!=metadataResponse)?metadataResponse.getResponse():TVaultConstants.EMPTY). put(LogMessage.STATUS, (null!=metadataResponse)?metadataResponse.getHttpstatus().toString():TVaultConstants.EMPTY). put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL).toString()). build())); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("{\"erros\":[\"Group configuration failed.Please try again\"]}"); }else{ log.error(JSONUtil.getJSON(ImmutableMap.<String, String>builder(). put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()). put(LogMessage.ACTION, "Add Group to SDB"). put(LogMessage.MESSAGE, "Reverting user policy update failed"). put(LogMessage.RESPONSE, (null!=metadataResponse)?metadataResponse.getResponse():TVaultConstants.EMPTY). put(LogMessage.STATUS, (null!=metadataResponse)?metadataResponse.getHttpstatus().toString():TVaultConstants.EMPTY). put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL).toString()). build())); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("{\"errors\":[\"Group configuration failed.Contact Admin \"]}"); } } } }else{ ldapConfigresponse.getResponse(); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("{\"errors\":[\"Group configuration failed.Try Again\"]}"); } }else{ return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("{\"errors\":[\"Invalid 'path' specified\"]}"); } }  ResponseEntity<String> getFolders( String token, String path); ResponseEntity<String> getInfo(String token, String path); ResponseEntity<String> createfolder(String token, String path); ResponseEntity<String> createSafe(String token, Safe safe); ResponseEntity<String> getSafe(String token, String path); ResponseEntity<String> deleteSafe(String token, Safe safe, UserDetails userDetails); ResponseEntity<String> updateSafe(String token, Safe safe); ResponseEntity<String> addUserToSafe(String token, SafeUser safeUser, UserDetails userDetails); ResponseEntity<String> addGroupToSafe(String token, SafeGroup safeGroup, UserDetails userDetails); ResponseEntity<String> removeUserFromSafe(String token, SafeUser safeUser, UserDetails userDetails); ResponseEntity<String> removeGroupFromSafe(String token, SafeGroup safeGroup, UserDetails userDetails); ResponseEntity<String> addAwsRoleToSafe(String token, AWSRole awsRole); ResponseEntity<String> removeAWSRoleFromSafe(String token, AWSRole awsRole, boolean detachOnly, UserDetails userDetails); ResponseEntity<String> deletefolder(String token, String path, UserDetails userDetails); ResponseEntity<String> getFoldersRecursively(String token, String path); ResponseEntity<String> createNestedfolder(String token, String path, UserDetails userDetails); ResponseEntity<String> associateApproletoSDB(String token, SafeAppRoleAccess safeAppRoleAccess); ResponseEntity<String> removeApproleFromSafe(String token, String jsonstr);  }
@Test public void test_addGroupToSafe_successfully() { String token = "5PDrOhsy4ig8L3EpsJZSLAMg"; String path = "shared/mysafe01"; SafeGroup safeGroup = new SafeGroup("shared/mysafe01","mygroup01","read"); String jsonstr = "{ \"path\": \"shared/mysafe01\", \"groupname\": \"mygroup01\", \"access\": \"read\"}"; UserDetails userDetails = new UserDetails(); userDetails.setUsername("testuser1"); Response userResponse = getMockResponse(HttpStatus.OK, true, "{\"data\":{\"bound_cidrs\":[],\"max_ttl\":0,\"policies\":[\"default\",\"w_shared_mysafe01\",\"w_shared_mysafe02\"],\"ttl\":0,\"groups\":\"admin\"}}"); Response groupResponse = getMockResponse(HttpStatus.OK, true, "{\"data\":{\"bound_cidrs\":[],\"max_ttl\":0,\"policies\":[\"default\",\"w_shared_mysafe01\",\"w_shared_mysafe02\"],\"ttl\":0,\"groups\":\"admin\"}}"); Response idapConfigureResponse = getMockResponse(HttpStatus.NO_CONTENT, true, "{\"policies\":null}"); Response responseNoContent = getMockResponse(HttpStatus.NO_CONTENT, true, ""); ResponseEntity<String> responseEntityExpected = ResponseEntity.status(HttpStatus.OK).body("{\"messages\":[\"Group is successfully associated with Safe\"]}"); when(ControllerUtil.areSafeGroupInputsValid(safeGroup)).thenReturn(true); when(JSONUtil.getJSON(safeGroup)).thenReturn(jsonstr); when(ControllerUtil.canAddPermission(path, token)).thenReturn(true); when(reqProcessor.process("/auth/ldap/groups","{\"groupname\":\"mygroup01\"}",token)).thenReturn(groupResponse); try { List<String> resList = new ArrayList<>(); resList.add("default"); resList.add("w_shared_mysafe01"); resList.add("w_shared_mysafe02"); when(ControllerUtil.getPoliciesAsListFromJson(any(), any())).thenReturn(resList); } catch (IOException e) { e.printStackTrace(); } when(ControllerUtil.configureLDAPGroup(any(),any(),eq(token))).thenReturn(idapConfigureResponse); when(ControllerUtil.updateMetadata(any(),eq(token))).thenReturn(responseNoContent); ReflectionTestUtils.setField(safesService, "vaultAuthMethod", "oidc"); List<String> policies = new ArrayList<>(); policies.add("default"); policies.add("w_shared_mysafe02"); policies.add("r_shared_mysafe01"); List<String> currentpolicies = new ArrayList<>(); currentpolicies.add("default"); currentpolicies.add("w_shared_mysafe01"); currentpolicies.add("w_shared_mysafe02"); OIDCGroup oidcGroup = new OIDCGroup("123-123-123", currentpolicies); when(OIDCUtil.getIdentityGroupDetails("mygroup01", token)).thenReturn(oidcGroup); Response response = new Response(); response.setHttpstatus(HttpStatus.NO_CONTENT); when(OIDCUtil.updateGroupPolicies(token, "mygroup01", policies, currentpolicies, oidcGroup.getId())).thenReturn(response); ResponseEntity<String> responseEntity = safesService.addGroupToSafe(token, safeGroup, userDetails); assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); assertEquals(responseEntityExpected, responseEntity); }
@Test public void test_addGroupToSafe_successfully_all_safes() { String token = "5PDrOhsy4ig8L3EpsJZSLAMg"; String path = "shared/mysafe01"; SafeGroup safeGroup = new SafeGroup("shared/mysafe01","mygroup01","read"); String jsonstr = "{ \"path\": \"shared/mysafe01\", \"groupname\": \"mygroup01\", \"access\": \"read\"}"; UserDetails userDetails = new UserDetails(); userDetails.setUsername("testuser1"); Response userResponse = getMockResponse(HttpStatus.OK, true, "{\"data\":{\"bound_cidrs\":[],\"max_ttl\":0,\"policies\":[\"default\",\"w_shared_mysafe01\",\"w_shared_mysafe02\"],\"ttl\":0,\"groups\":\"admin\"}}"); Response groupResponse = getMockResponse(HttpStatus.OK, true, "{\"data\":{\"bound_cidrs\":[],\"max_ttl\":0,\"policies\":[\"default\",\"w_shared_mysafe01\",\"w_shared_mysafe02\"],\"ttl\":0,\"groups\":\"admin\"}}"); Response idapConfigureResponse = getMockResponse(HttpStatus.NO_CONTENT, true, "{\"policies\":null}"); Response responseNoContent = getMockResponse(HttpStatus.NO_CONTENT, true, ""); Response response_404 = getMockResponse(HttpStatus.NOT_FOUND, true, ""); ResponseEntity<String> responseEntityExpected = ResponseEntity.status(HttpStatus.OK).body("{\"messages\":[\"Group is successfully associated with Safe\"]}"); when(ControllerUtil.areSafeGroupInputsValid(safeGroup)).thenReturn(true); when(JSONUtil.getJSON(safeGroup)).thenReturn(jsonstr); when(ControllerUtil.canAddPermission(path, token)).thenReturn(true); when(reqProcessor.process("/auth/ldap/groups","{\"groupname\":\"mygroup01\"}",token)).thenReturn(groupResponse); try { when(ControllerUtil.getPoliciesAsStringFromJson(any(), any())).thenReturn("default,w_shared_mysafe01,w_shared_mysafe02"); } catch (IOException e) { e.printStackTrace(); } when(ControllerUtil.configureLDAPGroup(any(),any(),eq(token))).thenReturn(idapConfigureResponse); when(ControllerUtil.updateMetadata(any(),eq(token))).thenAnswer(new Answer() { private int count = 0; public Object answer(InvocationOnMock invocation) { if (count++ == 1) return responseNoContent; return response_404; } }); when(ControllerUtil.getSafeType(path)).thenReturn("shared"); when(ControllerUtil.getSafeName(path)).thenReturn("mysafe01"); when(ControllerUtil.getAllExistingSafeNames("shared", token)).thenReturn(Arrays.asList("mysafe02")); ReflectionTestUtils.setField(safesService, "vaultAuthMethod", "oidc"); List<String> policies = new ArrayList<>(); policies.add("default"); policies.add("w_shared_mysafe02"); policies.add("r_shared_mysafe01"); List<String> currentpolicies = new ArrayList<>(); currentpolicies.add("default"); currentpolicies.add("w_shared_mysafe01"); currentpolicies.add("w_shared_mysafe02"); OIDCGroup oidcGroup = new OIDCGroup("123-123-123", currentpolicies); when(OIDCUtil.getIdentityGroupDetails("mygroup01", token)).thenReturn(oidcGroup); Response response = new Response(); response.setHttpstatus(HttpStatus.NO_CONTENT); when(OIDCUtil.updateGroupPolicies(token, "mygroup01", policies, currentpolicies, oidcGroup.getId())).thenReturn(response); ResponseEntity<String> responseEntity = safesService.addGroupToSafe(token, safeGroup, userDetails); assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); assertEquals(responseEntityExpected, responseEntity); }
@Test public void test_addGroupToSafe_failure() { String token = "5PDrOhsy4ig8L3EpsJZSLAMg"; String path = "shared/mysafe01"; SafeGroup safeGroup = new SafeGroup("shared/mysafe01","mygroup01","read"); String jsonstr = "{ \"path\": \"shared/mysafe01\", \"groupname\": \"mygroup01\", \"access\": \"read\"}"; UserDetails userDetails = new UserDetails(); userDetails.setUsername("testuser1"); Response userResponse = getMockResponse(HttpStatus.OK, true, "{\"data\":{\"bound_cidrs\":[],\"max_ttl\":0,\"policies\":[\"default\",\"w_shared_mysafe01\",\"w_shared_mysafe02\"],\"ttl\":0,\"groups\":\"admin\"}}"); Response groupResponse = getMockResponse(HttpStatus.OK, true, "{\"data\":{\"bound_cidrs\":[],\"max_ttl\":0,\"policies\":[\"default\",\"w_shared_mysafe01\",\"w_shared_mysafe02\"],\"ttl\":0,\"groups\":\"admin\"}}"); Response idapConfigureResponse = getMockResponse(HttpStatus.NO_CONTENT, true, "{\"policies\":null}"); Response responseNoContent = getMockResponse(HttpStatus.NO_CONTENT, true, ""); Response response_404 = getMockResponse(HttpStatus.NOT_FOUND, true, ""); ResponseEntity<String> responseEntityExpected = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("{\"errors\":[\"Group configuration failed.Try Again\"]}"); when(ControllerUtil.areSafeGroupInputsValid(safeGroup)).thenReturn(true); when(JSONUtil.getJSON(safeGroup)).thenReturn(jsonstr); when(ControllerUtil.canAddPermission(path, token)).thenReturn(true); when(reqProcessor.process("/auth/ldap/groups","{\"groupname\":\"mygroup01\"}",token)).thenReturn(groupResponse); try { List<String> resList = new ArrayList<>(); resList.add("default"); resList.add("w_shared_mysafe01"); resList.add("w_shared_mysafe02"); when(ControllerUtil.getPoliciesAsListFromJson(any(), any())).thenReturn(resList); } catch (IOException e) { e.printStackTrace(); } when(ControllerUtil.configureLDAPGroup(any(),any(),eq(token))).thenReturn(idapConfigureResponse); when(ControllerUtil.updateMetadata(any(),eq(token))).thenReturn(response_404); when(ControllerUtil.getSafeType(path)).thenReturn("shared"); when(ControllerUtil.getSafeName(path)).thenReturn("mysafe01"); when(ControllerUtil.getAllExistingSafeNames("shared", token)).thenReturn(Arrays.asList("mysafe02")); ReflectionTestUtils.setField(safesService, "vaultAuthMethod", "oidc"); List<String> policies = new ArrayList<>(); policies.add("default"); policies.add("w_shared_mysafe02"); policies.add("r_shared_mysafe01"); List<String> currentpolicies = new ArrayList<>(); currentpolicies.add("default"); currentpolicies.add("w_shared_mysafe01"); currentpolicies.add("w_shared_mysafe02"); OIDCGroup oidcGroup = new OIDCGroup("123-123-123", currentpolicies); when(OIDCUtil.getIdentityGroupDetails("mygroup01", token)).thenReturn(oidcGroup); Response response = new Response(); response.setHttpstatus(HttpStatus.BAD_REQUEST); when(OIDCUtil.updateGroupPolicies(token, "mygroup01", policies, currentpolicies, oidcGroup.getId())).thenReturn(response); ResponseEntity<String> responseEntity = safesService.addGroupToSafe(token, safeGroup, userDetails); assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); assertEquals(responseEntityExpected, responseEntity); }