use of com.emc.storageos.security.authorization.BasePermissionsHelper.UserMapping in project coprhd-controller by CoprHD.
the class UserFromRequestHelper method parseOldFormat.
/**
* This method parses the userContext information using the "old" format
* ( "user,user@domain.com;group,group2")
* TODO: once AD integration is complete and attribute release is only
* available through that channel, this old format should be removed. For
* now, keeping for backwards compatibility and so that authz testing can
* continue without AD servers.
*
* @param userContext
* @return a UserFromRequest pojo
*/
private StorageOSUser parseOldFormat(String userContext) {
StorageOSUser user = null;
if (!StringUtils.isBlank(userContext)) {
String[] userInfo = userContext.split(";");
String[] userAttributes = userInfo[0].split(",");
String name = userAttributes[0];
String[] parts = name.split("@");
String domain = "";
if (parts.length > 1) {
domain = parts[1];
}
URI tenant = null;
boolean local = false;
if (userAttributes.length > 1 && null != userAttributes[1] && !StringUtils.isBlank(userAttributes[1])) {
String[] attrKV = userAttributes[1].split("=");
if (attrKV[0].equals(USERDETAILS_LOCALUSER)) {
if (attrKV.length > 1 && Boolean.valueOf(attrKV[1])) {
local = true;
}
} else {
UserMapping mapping = new UserMapping();
mapping.setDomain(domain);
if (attrKV.length > 1) {
if (attrKV[0].equalsIgnoreCase("group")) {
mapping.setGroups(Collections.singletonList(attrKV[1]));
} else {
UserMappingAttribute tenantAttribute = new UserMappingAttribute();
tenantAttribute.setKey(attrKV[0]);
tenantAttribute.setValues(Collections.singletonList(attrKV[1]));
}
try {
tenant = _permissionsHelper.lookupTenant(mapping);
} catch (DatabaseException e) {
_logger.error("Failed to query for tenant with attribute: {}. Exception {} ", mapping.toString(), e);
}
}
}
} else if (!domain.isEmpty()) {
UserMapping mapping = new UserMapping();
mapping.setDomain(domain);
try {
tenant = _permissionsHelper.lookupTenant(mapping);
} catch (DatabaseException e) {
_logger.error("Failed to query for tenant with attribute: {}. Exception {} ", mapping.toString(), e);
}
}
if (null == tenant) {
tenant = _permissionsHelper.getRootTenant().getId();
}
user = new StorageOSUser(name, tenant.toString());
user.setIsLocal(local);
if (userInfo.length > 1) {
String[] groups = org.springframework.util.StringUtils.commaDelimitedListToStringArray(userInfo[1]);
if (groups.length > 0) {
for (String group : groups) {
user.addGroup(group);
}
}
}
return user;
}
return null;
}
use of com.emc.storageos.security.authorization.BasePermissionsHelper.UserMapping in project coprhd-controller by CoprHD.
the class StorageOSLdapPersonAttributeDao method mapUserToTenant.
/**
* Match the user to one and only one tenant if found user there attributes/groups
*
* @param domains
* @param storageOSUser
* @param attributeKeyValuesMap
* @param tenantToMappingMap
*/
private Map<URI, UserMapping> mapUserToTenant(StringSet domains, StorageOSUserDAO storageOSUser, Map<String, List<String>> attributeKeyValuesMap, Map<URI, List<UserMapping>> tenantToMappingMap, ValidationFailureReason[] failureReason) {
Map<URI, UserMapping> tenants = new HashMap<URI, UserMapping>();
if (CollectionUtils.isEmpty(domains)) {
return tenants;
}
List<UserMappingAttribute> userMappingAttributes = new ArrayList<UserMappingAttribute>();
for (Entry<String, List<String>> attributeKeyValues : attributeKeyValuesMap.entrySet()) {
UserMappingAttribute userMappingAttribute = new UserMappingAttribute();
userMappingAttribute.setKey(attributeKeyValues.getKey());
userMappingAttribute.setValues(attributeKeyValues.getValue());
userMappingAttributes.add(userMappingAttribute);
}
List<String> userMappingGroups = new ArrayList<String>();
if (null != storageOSUser.getGroups()) {
for (String group : storageOSUser.getGroups()) {
userMappingGroups.add((group.split("@")[0]).toUpperCase());
_log.debug("Adding user's group {} to usermapping group ", (group.split("@")[0]).toUpperCase());
}
}
for (Entry<URI, List<UserMapping>> tenantToMappingMapEntry : tenantToMappingMap.entrySet()) {
if (tenantToMappingMapEntry == null || tenantToMappingMapEntry.getValue() == null) {
continue;
}
for (String domain : domains) {
for (UserMapping userMapping : tenantToMappingMapEntry.getValue()) {
if (userMapping.isMatch(domain, userMappingAttributes, userMappingGroups)) {
tenants.put(tenantToMappingMapEntry.getKey(), userMapping);
}
}
}
}
// unless the root tenant is restricted by a mapping
if (tenants.isEmpty()) {
BasePermissionsHelper permissionsHelper = new BasePermissionsHelper(_dbClient, false);
TenantOrg rootTenant = permissionsHelper.getRootTenant();
// if yes, means Provider Tenant's user-mapping under modification.
if (tenantToMappingMap.containsKey(rootTenant.getId())) {
List<UserMapping> rootUserMapping = tenantToMappingMap.get(rootTenant.getId());
// if yes, set user map to provider tenant.
if (CollectionUtils.isEmpty(rootUserMapping)) {
_log.debug("User {} did not match a tenant. Assigning to root tenant since root does not have any attribute mappings", storageOSUser.getUserName());
tenants.put(rootTenant.getId(), null);
}
// provider tenant is not in UserMapping parameter, means no change to its user-mapping in this request,
// need to check if its original user-mapping is empty or not.
} else if (rootTenant.getUserMappings() == null || rootTenant.getUserMappings().isEmpty()) {
_log.debug("User {} did not match a tenant. Assigning to root tenant since root does not have any attribute mappings", storageOSUser.getUserName());
tenants.put(rootTenant.getId(), null);
}
}
return tenants;
}
use of com.emc.storageos.security.authorization.BasePermissionsHelper.UserMapping in project coprhd-controller by CoprHD.
the class CustomAuthenticationManagerTest method testGetUserGroups.
@Test
public void testGetUserGroups() throws Exception {
cleanupProviders();
AuthnProvider authConfig = createValidAuthProviderInDB();
final String DOMAIN_USERS_GROUP = "Domain Users@sanity.local";
final String OUTER_GROUP = "OuterGroup@sanity.local";
final String INNER_GROUP = "InsideGroup@sanity.local";
// look for a user with an unsupported domain
String principalSearchFailedFormat = "Search for %s failed for this tenant, or could not be found for this tenant.";
String user = "invaliduser@invalidDomain.com";
UserDetails userDetails = null;
try {
userDetails = _authManager.getUserDetails(user);
Assert.assertNull(userDetails);
} catch (SecurityException e) {
Assert.fail("Got a SecurityException when BadRequestException was expected. Details: " + e.getLocalizedMessage());
} catch (BadRequestException e) {
assertServiceError(HttpStatus.SC_BAD_REQUEST, ServiceCode.API_BAD_REQUEST, String.format(principalSearchFailedFormat, user), e);
} catch (Exception e) {
Assert.fail("Got a " + e.getClass().toString() + "when BadRequestException was expected. Details: " + e.getLocalizedMessage());
}
// look for a user that doesn't exist
user = "iShouldntExistAnywhereInTheWholeWideWorld@sanity.local";
try {
_authManager.getUserDetails(user);
Assert.assertNull(userDetails);
} catch (SecurityException e) {
Assert.fail("Got a SecurityException when BadRequestException was expected. Details: " + e.getLocalizedMessage());
} catch (BadRequestException e) {
assertServiceError(HttpStatus.SC_BAD_REQUEST, ServiceCode.API_BAD_REQUEST, String.format(principalSearchFailedFormat, user), e);
} catch (Exception e) {
Assert.fail("Got a " + e.getClass().toString() + "when BadRequestException was expected. Details: " + e.getLocalizedMessage());
}
// look for a user that does exist
user = "userGroupsTestUser@sanity.local";
try {
userDetails = _authManager.getUserDetails(user);
Assert.assertNotNull(userDetails);
Assert.assertEquals(3, userDetails.getUserGroupList().size());
Assert.assertTrue("user is supposed to be part of the root tenant " + _rootTenantId + "but is actually in tenant" + userDetails.getTenant(), _rootTenantId.toString().equals(userDetails.getTenant()));
boolean isDomainUser = false;
boolean isInsideGroup = false;
boolean isOuterGroup = false;
for (String groupName : userDetails.getUserGroupList()) {
if (groupName.equalsIgnoreCase(DOMAIN_USERS_GROUP)) {
isDomainUser = true;
} else if (groupName.equalsIgnoreCase(INNER_GROUP)) {
isInsideGroup = true;
} else if (groupName.equalsIgnoreCase(OUTER_GROUP)) {
isOuterGroup = true;
}
}
Assert.assertTrue("isDomainUser = " + isDomainUser + ", isInsideGroup = " + isInsideGroup + ", isOuterGroup = " + isOuterGroup, isDomainUser && isInsideGroup && isOuterGroup);
} catch (SecurityException e) {
Assert.fail("Got a SecurityException. Details: " + e.getLocalizedMessage());
} catch (BadRequestException e) {
Assert.fail("Got a BadRequestException. Details: " + e.getLocalizedMessage());
} catch (Exception e) {
Assert.fail("Got a " + e.getClass().toString() + ". Details: " + e.getLocalizedMessage());
}
// now test the returned user has the right tenant- it should now be mapped to the
// subtenant
UserMapping tenantMapping = new UserMapping();
tenantMapping.setDomain("sanity.local");
tenantMapping.setGroups(Collections.singletonList(OUTER_GROUP.split("@")[0]));
StringSetMap mappings = new StringSetMap();
mappings.put(tenantMapping.getDomain(), tenantMapping.toString());
URI subtenantId = URIUtil.createId(TenantOrg.class);
TenantOrg subtenant = new TenantOrg();
subtenant.setLabel("subtenant for user groups test");
subtenant.setDescription("auth subtenan1t");
subtenant.setId(subtenantId);
subtenant.setParentTenant(new NamedURI(_rootTenantId, "subtenant"));
subtenant.setUserMappings(mappings);
_dbClient.persistObject(subtenant);
try {
userDetails = _authManager.getUserDetails(user);
Assert.assertNotNull(userDetails);
Assert.assertEquals(3, userDetails.getUserGroupList().size());
boolean isDomainUser = false;
boolean isInsideGroup = false;
boolean isOuterGroup = false;
for (String groupName : userDetails.getUserGroupList()) {
if (groupName.equalsIgnoreCase(DOMAIN_USERS_GROUP)) {
isDomainUser = true;
} else if (groupName.equalsIgnoreCase(INNER_GROUP)) {
isInsideGroup = true;
} else if (groupName.equalsIgnoreCase(OUTER_GROUP)) {
isOuterGroup = true;
}
}
Assert.assertTrue("isDomainUser = " + isDomainUser + ", isInsideGroup = " + isInsideGroup + ", isOuterGroup = " + isOuterGroup, isDomainUser && isInsideGroup && isOuterGroup);
Assert.assertTrue("user is supposed to be part of the subtenant " + subtenantId + " but is actually in tenant " + userDetails.getTenant() + " (root tenant is " + _rootTenantId + " )", subtenantId.toString().equals(userDetails.getTenant()));
} catch (SecurityException e) {
Assert.fail("Got a SecurityException. Details: " + e.getLocalizedMessage());
} catch (BadRequestException e) {
Assert.fail("Got a BadRequestException. Details: " + e.getLocalizedMessage());
} catch (Exception e) {
Assert.fail("Got a " + e.getClass().toString() + ". Details: " + e.getLocalizedMessage());
}
}
use of com.emc.storageos.security.authorization.BasePermissionsHelper.UserMapping in project coprhd-controller by CoprHD.
the class CustomAuthenticationManagerTest method testAuthentication.
@Test
public void testAuthentication() throws Exception {
createADLDAPProviders();
UsernamePasswordCredentials sanityUserCreds = new UsernamePasswordCredentials("sanity_user@sanity.local", "P@ssw0rd");
Assert.assertNotNull(_authManager.authenticate(sanityUserCreds));
UsernamePasswordCredentials ldapUserCreds = new UsernamePasswordCredentials("user@root.com", "password");
Assert.assertNotNull(_authManager.authenticate(ldapUserCreds));
UsernamePasswordCredentials badDomainUserCreds = new UsernamePasswordCredentials("sanity_user@baddomain", "P@ssw0rd");
Assert.assertNull(_authManager.authenticate(badDomainUserCreds));
UsernamePasswordCredentials noDomainUserCreds = new UsernamePasswordCredentials("sanity_user", "P@ssw0rd");
Assert.assertNull(_authManager.authenticate(noDomainUserCreds));
UsernamePasswordCredentials badUserUserCreds = new UsernamePasswordCredentials("sanity_user@root.com", "P@ssw0rd");
Assert.assertNull(_authManager.authenticate(badUserUserCreds));
UsernamePasswordCredentials badPasswordUserCreds = new UsernamePasswordCredentials("sanity_user@sanity.local", "badpassword");
Assert.assertNull(_authManager.authenticate(badPasswordUserCreds));
UsernamePasswordCredentials emptyUsernameUserCreds = new UsernamePasswordCredentials("", "P@ssw0rd");
Assert.assertNull(_authManager.authenticate(emptyUsernameUserCreds));
UsernamePasswordCredentials emptyPasswordUserCreds = new UsernamePasswordCredentials("sanity_user@sanity.local", "");
Assert.assertNull(_authManager.authenticate(emptyPasswordUserCreds));
UsernamePasswordCredentials nullPasswordUserCreds = new UsernamePasswordCredentials("sanity_user@sanity.local", null);
Assert.assertNull(_authManager.authenticate(nullPasswordUserCreds));
UserMapping tenantMapping = new UserMapping();
UserMappingAttribute tenantAttr = new UserMappingAttribute();
tenantAttr.setKey("o");
tenantAttr.setValues(Collections.singletonList("sales"));
tenantMapping.setAttributes(Collections.singletonList(tenantAttr));
tenantMapping.setDomain("root.com");
UserMapping tenantMapping2 = new UserMapping();
tenantMapping2.setGroups(Collections.singletonList("Test Group"));
tenantMapping2.setDomain("sanity.local");
StringSetMap mappings = new StringSetMap();
mappings.put(tenantMapping.getDomain(), tenantMapping.toString());
mappings.put(tenantMapping2.getDomain(), tenantMapping2.toString());
_subtenantId = URIUtil.createId(TenantOrg.class);
TenantOrg subtenant = new TenantOrg();
subtenant.setLabel("subtenant");
subtenant.setDescription("auth subtenant");
subtenant.setId(_subtenantId);
subtenant.setParentTenant(new NamedURI(_rootTenantId, "subtenant"));
subtenant.setUserMappings(mappings);
_dbClient.persistObject(subtenant);
StorageOSUserDAO user = _authManager.authenticate(sanityUserCreds);
Assert.assertEquals(_rootTenantId.toString(), user.getTenantId());
// this user has the o=sales attribute so should be in the subtenant
user = _authManager.authenticate(ldapUserCreds);
Assert.assertEquals(_subtenantId.toString(), user.getTenantId());
// this user is in the group Test Group so should be in the subtenant
UsernamePasswordCredentials groupUserCreds = new UsernamePasswordCredentials("testuser@sanity.local", "P@ssw0rd");
user = _authManager.authenticate(groupUserCreds);
Assert.assertEquals(_subtenantId.toString(), user.getTenantId());
// Create the a good authConfig with whitelist values
AuthnProvider adAuthConfig = new AuthnProvider();
adAuthConfig.setId(URIUtil.createId(AuthnProvider.class));
adAuthConfig.setMode("ad");
StringSet adDomains = new StringSet();
adDomains.add("whitelist1");
adDomains.add("whitelist2");
adAuthConfig.setDomains(adDomains);
adAuthConfig.setManagerDN("CN=Administrator,CN=Users,DC=sanity,DC=local");
adAuthConfig.setManagerPassword(_adManagerPassword);
StringSet adUrls = new StringSet();
adUrls.add(LDAP_SERVER_2);
adAuthConfig.setServerUrls(adUrls);
adAuthConfig.setSearchBase("CN=Users,DC=sanity,DC=local");
adAuthConfig.setSearchFilter("sAMAccountName=%U");
adAuthConfig.setGroupAttribute("CN");
StringSet whitelistValues = new StringSet();
whitelistValues.add("*Users*");
whitelistValues.add("ProjectAdmins");
adAuthConfig.setGroupWhitelistValues(whitelistValues);
adAuthConfig.setLastModified(System.currentTimeMillis());
_dbClient.createObject(adAuthConfig);
reloadConfig(true);
// Login the user the user that is in the group "Test Group" but it is not in the whitelist in
// the auth config so the user should end up in the root tenant
UsernamePasswordCredentials whitelist1GroupUserCreds = new UsernamePasswordCredentials("testuser@whitelist1", "P@ssw0rd");
user = _authManager.authenticate(whitelist1GroupUserCreds);
Assert.assertEquals(_rootTenantId.toString(), user.getTenantId());
// log the same user in to the other domain to make sure it is mapped to the same domain
UsernamePasswordCredentials whitelist2GroupUserCreds = new UsernamePasswordCredentials("testuser@whitelist2", "P@ssw0rd");
user = _authManager.authenticate(whitelist2GroupUserCreds);
Assert.assertEquals(_rootTenantId.toString(), user.getTenantId());
ValidationFailureReason[] failureReason = new ValidationFailureReason[1];
_authManager.validateUser("sanity_user@sanity.local", _rootTenantId.toString(), null);
thrown.expect(APIException.class);
_authManager.validateUser("sanity_user@sanity.local", _subtenantId.toString(), null);
_authManager.validateUser("sanity_user@sanity.local", _subtenantId.toString(), _rootTenantId.toString());
_authManager.validateUser("user2@root.com", _rootTenantId.toString(), null);
thrown.expect(APIException.class);
_authManager.validateUser("user2@root.com", _subtenantId.toString(), null);
_authManager.validateUser("user2@root.com", _subtenantId.toString(), _rootTenantId.toString());
_authManager.validateUser("user@root.com", _subtenantId.toString(), null);
thrown.expect(APIException.class);
_authManager.validateUser("user@root.com", _rootTenantId.toString(), null);
_authManager.validateUser("testuser@sanity.local", _subtenantId.toString(), null);
thrown.expect(APIException.class);
_authManager.validateUser("testuser@sanity.local", _rootTenantId.toString(), null);
thrown.expect(APIException.class);
_authManager.validateUser("testuser", _rootTenantId.toString(), null);
thrown.expect(APIException.class);
_authManager.validateUser("testuser", _subtenantId.toString(), null);
Assert.assertTrue(_authManager.isGroupValid("Test Group@sanity.local", failureReason));
Assert.assertFalse(_authManager.isGroupValid("Test Group@whitelist1", failureReason));
Assert.assertEquals(failureReason[0], ValidationFailureReason.USER_OR_GROUP_NOT_FOUND_FOR_TENANT);
Assert.assertFalse(_authManager.isGroupValid("Test Group@whitelist2", failureReason));
Assert.assertTrue(_authManager.isGroupValid("Domain Users@whitelist2", failureReason));
Assert.assertTrue(_authManager.isGroupValid("ProjectAdmins@whitelist1", failureReason));
Assert.assertFalse(_authManager.isGroupValid("Test Group", failureReason));
// Create the a good authConfig with the sid group attribute
AuthnProvider sidAuthConfig = new AuthnProvider();
sidAuthConfig.setId(URIUtil.createId(AuthnProvider.class));
sidAuthConfig.setMode("ad");
StringSet sidDomains = new StringSet();
sidDomains.add("sidtest");
sidAuthConfig.setDomains(sidDomains);
sidAuthConfig.setManagerDN("CN=Administrator,CN=Users,DC=sanity,DC=local");
sidAuthConfig.setManagerPassword(_adManagerPassword);
StringSet sidUrls = new StringSet();
sidUrls.add(LDAP_SERVER_2);
sidAuthConfig.setServerUrls(sidUrls);
sidAuthConfig.setSearchBase("CN=Users,DC=sanity,DC=local");
sidAuthConfig.setSearchFilter("sAMAccountName=%U");
sidAuthConfig.setGroupAttribute("objectSid");
StringSet sidWhitelistValues = new StringSet();
// Domain users ends in -513
sidWhitelistValues.add("*-513");
// Test group SID
sidWhitelistValues.add("S-1-5-21-2759885641-1951973838-595118951-1135");
sidAuthConfig.setGroupWhitelistValues(sidWhitelistValues);
sidAuthConfig.setLastModified(System.currentTimeMillis());
_dbClient.createObject(sidAuthConfig);
reloadConfig(true);
// Create a subtenant using the sid of Domain users from '@sidtest'
// for mapping
UserMapping sidGroupMapping = new UserMapping();
sidGroupMapping.setDomain("sidtest");
sidGroupMapping.setGroups(Collections.singletonList("S-1-5-21-2759885641-1951973838-595118951-513"));
StringSetMap sidTestMappings = new StringSetMap();
sidTestMappings.put(sidGroupMapping.getDomain(), sidGroupMapping.toString());
URI subtenant2Id = URIUtil.createId(TenantOrg.class);
TenantOrg subtenant2 = new TenantOrg();
subtenant2.setLabel("subtenant2");
subtenant2.setDescription("auth subtenant2");
subtenant2.setId(subtenant2Id);
subtenant2.setParentTenant(new NamedURI(_rootTenantId, "subtenant2"));
subtenant2.setUserMappings(sidTestMappings);
_dbClient.persistObject(subtenant2);
// login the sanity_user (sanity_user@sanity.local) and verify that the user is in the
// root tenant still despite being in 'Domain Users' group because it is a different domain
user = _authManager.authenticate(sanityUserCreds);
Assert.assertEquals(_rootTenantId.toString(), user.getTenantId());
// Now try sanity_user@sidtest and the user should be in subtenant2
UsernamePasswordCredentials sidTestUserCreds = new UsernamePasswordCredentials("sanity_user@sidtest", "P@ssw0rd");
user = _authManager.authenticate(sidTestUserCreds);
Assert.assertEquals(subtenant2Id.toString(), user.getTenantId());
_authManager.validateUser("sanity_user@sidtest", subtenant2Id.toString(), null);
_authManager.validateUser("testuser@sidtest", subtenant2Id.toString(), null);
_authManager.validateUser("baduser@sidtest", subtenant2Id.toString(), null);
// Test group
Assert.assertTrue(_authManager.isGroupValid("S-1-5-21-2759885641-1951973838-595118951-1135@sidtest", failureReason));
// Domain Users
Assert.assertTrue(_authManager.isGroupValid("S-1-5-21-2759885641-1951973838-595118951-513@sidtest", failureReason));
// non-existent group
Assert.assertFalse(_authManager.isGroupValid("S-2-2-21-2759885641-1951973838-595118951-513@sidtest", failureReason));
// non-whitelist group (ProjectAdmins)
Assert.assertFalse(_authManager.isGroupValid("S-1-5-21-2759885641-1951973838-595118951-1111@sidtest", failureReason));
// Create an config with a bad URL
AuthnProvider ldapAuthConfig = new AuthnProvider();
ldapAuthConfig.setId(URIUtil.createId(AuthnProvider.class));
ldapAuthConfig.setMode("ldap");
StringSet ldapDomains = new StringSet();
ldapDomains.add("badurl.com");
ldapAuthConfig.setDomains(ldapDomains);
ldapAuthConfig.setManagerDN("cn=Manager,dc=root,dc=com");
ldapAuthConfig.setManagerPassword("secret");
StringSet ldapURLs = new StringSet();
ldapURLs.add("ldap://xxx");
ldapAuthConfig.setServerUrls(ldapURLs);
ldapAuthConfig.setSearchBase("ou=People,dc=root,dc=com");
ldapAuthConfig.setSearchFilter("(uid=%U)");
_dbClient.createObject(ldapAuthConfig);
UsernamePasswordCredentials badURLUserCreds = new UsernamePasswordCredentials("user@badurl.com", "password");
// Check that authentication and validation operations fail
// but do not throw connection exceptions
user = _authManager.authenticate(badURLUserCreds);
Assert.assertNull(user);
thrown.expect(APIException.class);
_authManager.validateUser("user@badurl.com", subtenant2Id.toString(), null);
Assert.assertFalse(_authManager.isGroupValid("group@badurl.com", failureReason));
cleanupProviders();
}
use of com.emc.storageos.security.authorization.BasePermissionsHelper.UserMapping in project coprhd-controller by CoprHD.
the class TenantsService method setTenant.
/**
* Update info for tenant or subtenant
*
* @param param Tenant update parameter
* @param id the URN of a ViPR Tenant/Subtenant
* @prereq If modifying user mappings, an authentication provider needs to support the domain used in the mappings
* @brief Update tenant or subtenant
* @return the updated Tenant/Subtenant instance
*/
@PUT
@Path("/{id}")
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@CheckPermission(roles = { Role.TENANT_ADMIN, Role.SECURITY_ADMIN })
public TenantOrgRestRep setTenant(@PathParam("id") URI id, TenantUpdateParam param) {
TenantOrg tenant = getTenantById(id, true);
ObjectNamespace namesp = null;
boolean namespModified = false;
ObjectNamespace oldNamesp = null;
boolean oldNamespModified = false;
if (param.getLabel() != null && !param.getLabel().isEmpty()) {
if (!tenant.getLabel().equalsIgnoreCase(param.getLabel())) {
checkForDuplicateName(param.getLabel(), TenantOrg.class, tenant.getParentTenant().getURI(), "parentTenant", _dbClient);
}
tenant.setLabel(param.getLabel());
NamedURI parent = tenant.getParentTenant();
if (parent != null) {
parent.setName(param.getLabel());
tenant.setParentTenant(parent);
}
}
if (param.getDescription() != null) {
tenant.setDescription(param.getDescription());
}
if (!StringUtils.isEmpty(param.getNamespace())) {
if (!param.getNamespace().equals(tenant.getNamespace())) {
checkForDuplicateNamespace(param.getNamespace());
}
if (!StringUtils.isEmpty(tenant.getNamespace()) && !"null".equals(tenant.getNamespace())) {
if (!tenant.getNamespace().equalsIgnoreCase(param.getNamespace())) {
List<Class<? extends DataObject>> excludeTypes = Lists.newArrayList();
excludeTypes.add(ObjectNamespace.class);
// Though we are not deleting need to check no dependencies on this tenant
ArgValidator.checkReference(TenantOrg.class, id, checkForDelete(tenant, excludeTypes));
}
}
String oldNamespace = tenant.getNamespace();
tenant.setNamespace(param.getNamespace());
// Update tenant info in respective namespace CF
List<URI> allNamespaceURI = _dbClient.queryByType(ObjectNamespace.class, true);
Iterator<ObjectNamespace> nsItr = _dbClient.queryIterativeObjects(ObjectNamespace.class, allNamespaceURI);
while (nsItr.hasNext()) {
namesp = nsItr.next();
if (namesp.getNativeId().equalsIgnoreCase(param.getNamespace())) {
namesp.setTenant(tenant.getId());
namesp.setMapped(true);
// There is a chance of exceptions ahead; hence updated db at the end
namespModified = true;
break;
}
}
// removing link between tenant and the old namespace
List<URI> namespaceURIs = _dbClient.queryByType(ObjectNamespace.class, true);
Iterator<ObjectNamespace> nsItrToUnMap = _dbClient.queryIterativeObjects(ObjectNamespace.class, namespaceURIs);
while (nsItrToUnMap.hasNext()) {
oldNamesp = nsItrToUnMap.next();
if (oldNamesp.getNativeId().equalsIgnoreCase(oldNamespace)) {
oldNamesp.setMapped(false);
oldNamespModified = true;
break;
}
}
}
if (param.getDetachNamespace()) {
List<Class<? extends DataObject>> excludeTypes = Lists.newArrayList();
excludeTypes.add(ObjectNamespace.class);
// Though we are not deleting need to check no dependencies on this tenant
ArgValidator.checkReference(TenantOrg.class, id, checkForDelete(tenant, excludeTypes));
String oldNamespace = tenant.getNamespace();
tenant.setNamespace(NullColumnValueGetter.getNullStr());
// Update tenant info in respective namespace CF
List<URI> allNamespaceURI = _dbClient.queryByType(ObjectNamespace.class, true);
Iterator<ObjectNamespace> nsItr = _dbClient.queryIterativeObjects(ObjectNamespace.class, allNamespaceURI);
while (nsItr.hasNext()) {
namesp = nsItr.next();
if (namesp.getNativeId().equalsIgnoreCase(oldNamespace)) {
namesp.setMapped(false);
// There is a chance of exceptions ahead; hence updated db at the end
namespModified = true;
break;
}
}
}
if (!isUserMappingEmpty(param)) {
// only SecurityAdmin can modify user-mapping
if (!_permissionsHelper.userHasGivenRole((StorageOSUser) sc.getUserPrincipal(), null, Role.SECURITY_ADMIN)) {
throw ForbiddenException.forbidden.onlySecurityAdminsCanModifyUserMapping();
}
if (null != param.getUserMappingChanges().getRemove() && !param.getUserMappingChanges().getRemove().isEmpty() && null != tenant.getUserMappings()) {
checkUserMappingAttribute(param.getUserMappingChanges().getRemove());
List<UserMapping> remove = UserMapping.fromParamList(param.getUserMappingChanges().getRemove());
StringSetMap mappingsToRemove = new StringSetMap();
// Find the database entries to remove
for (UserMapping mappingToRemove : remove) {
StringSet domainMappings = tenant.getUserMappings().get(mappingToRemove.getDomain().trim());
trimGroupAndDomainNames(mappingToRemove);
if (null != domainMappings) {
for (String existingMapping : domainMappings) {
if (mappingToRemove.equals(UserMapping.fromString(existingMapping))) {
mappingsToRemove.put(mappingToRemove.getDomain(), existingMapping);
}
}
}
}
// Remove the items from the tenant database object
for (Entry<String, AbstractChangeTrackingSet<String>> mappingToRemoveSet : mappingsToRemove.entrySet()) {
for (String mappingToRemove : mappingToRemoveSet.getValue()) {
tenant.removeUserMapping(mappingToRemoveSet.getKey(), mappingToRemove);
}
}
}
if (null != param.getUserMappingChanges().getAdd() && !param.getUserMappingChanges().getAdd().isEmpty()) {
checkUserMappingAttribute(param.getUserMappingChanges().getAdd());
addUserMappings(tenant, param.getUserMappingChanges().getAdd(), getUserFromContext());
}
if (!TenantOrg.isRootTenant(tenant)) {
boolean bMappingsEmpty = true;
for (AbstractChangeTrackingSet<String> mapping : tenant.getUserMappings().values()) {
if (!mapping.isEmpty()) {
bMappingsEmpty = false;
break;
}
}
if (bMappingsEmpty) {
throw APIException.badRequests.requiredParameterMissingOrEmpty("user_mappings");
}
}
// request contains user-mapping change, perform the check.
mapOutProviderTenantCheck(tenant);
}
if (namespModified) {
_dbClient.updateObject(namesp);
}
if (oldNamespModified) {
_dbClient.updateObject(oldNamesp);
}
_dbClient.updateAndReindexObject(tenant);
recordOperation(OperationTypeEnum.UPDATE_TENANT, tenant.getId(), tenant);
return map(getTenantById(id, false));
}
Aggregations