use of org.wso2.carbon.user.api.UserStoreException in project carbon-apimgt by wso2.
the class RegistryCacheInvalidationService method invalidateCache.
/**
* This method invalidates registry cache for given resource in given tenant domain
* @param path
* @param tenantDomain
* @throws APIManagementException
*/
public void invalidateCache(String path, String tenantDomain) throws APIManagementException {
Registry registry;
boolean isTenantFlowStarted = false;
try {
int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
isTenantFlowStarted = true;
registry = ServiceReferenceHolder.getInstance().getRegistryService().getGovernanceSystemRegistry(tenantId);
Cache<RegistryCacheKey, GhostResource> cache = RegistryUtils.getResourceCache(RegistryConstants.REGISTRY_CACHE_BACKED_ID);
RegistryCacheKey cacheKey = null;
// Is registry mounted
if (registry.getRegistryContext().getRemoteInstances().size() > 0) {
for (Mount mount : registry.getRegistryContext().getMounts()) {
for (RemoteConfiguration configuration : registry.getRegistryContext().getRemoteInstances()) {
if (path.startsWith(mount.getPath())) {
DataBaseConfiguration dataBaseConfiguration = registry.getRegistryContext().getDBConfig(configuration.getDbConfig());
String connectionId = (dataBaseConfiguration.getUserName() != null ? dataBaseConfiguration.getUserName().split("@")[0] : dataBaseConfiguration.getUserName()) + "@" + dataBaseConfiguration.getDbUrl();
cacheKey = RegistryUtils.buildRegistryCacheKey(connectionId, tenantId, path);
if (cacheKey != null && cache.containsKey(cacheKey)) {
cache.remove(cacheKey);
}
}
}
}
} else {
DataBaseConfiguration dataBaseConfiguration = registry.getRegistryContext().getDefaultDataBaseConfiguration();
String connectionId = (dataBaseConfiguration.getUserName() != null ? dataBaseConfiguration.getUserName().split("@")[0] : dataBaseConfiguration.getUserName()) + "@" + dataBaseConfiguration.getDbUrl();
cacheKey = RegistryUtils.buildRegistryCacheKey(connectionId, tenantId, path);
if (cacheKey != null && cache.containsKey(cacheKey)) {
cache.remove(cacheKey);
}
}
} catch (RegistryException e) {
APIUtil.handleException("Error in accessing governance registry while invalidating cache for " + path + "in tenant " + tenantDomain, e);
} catch (UserStoreException e) {
APIUtil.handleException("Error in retrieving Tenant Information while invalidating cache for " + path + "in tenant " + tenantDomain, e);
} finally {
if (isTenantFlowStarted) {
PrivilegedCarbonContext.endTenantFlow();
}
}
}
use of org.wso2.carbon.user.api.UserStoreException in project carbon-apimgt by wso2.
the class RestApiUtil method handleMigrationSpecificPermissionViolations.
/**
* Handle if any cross tenant access permission violations detected. Cross tenant resources (apis/apps) can be
* retrieved only by super tenant admin user, only while a migration process(2.6.0 to 3.0.0). APIM server has to be
* started with the system property 'migrationMode=true' if a migration related exports are to be done.
*
* @param targetTenantDomain Tenant domain of which resources are requested
* @param username Logged in user name
* @throws ForbiddenException
*/
public static void handleMigrationSpecificPermissionViolations(String targetTenantDomain, String username) throws ForbiddenException {
boolean isCrossTenantAccess = !targetTenantDomain.equals(MultitenantUtils.getTenantDomain(username));
if (!isCrossTenantAccess) {
return;
}
String superAdminRole = null;
try {
superAdminRole = ServiceReferenceHolder.getInstance().getRealmService().getTenantUserRealm(MultitenantConstants.SUPER_TENANT_ID).getRealmConfiguration().getAdminRoleName();
} catch (UserStoreException e) {
RestApiUtil.handleInternalServerError("Error in getting super admin role name", e, log);
}
// check whether logged in user is a super tenant user
String superTenantDomain = null;
try {
superTenantDomain = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getSuperTenantDomain();
} catch (UserStoreException e) {
RestApiUtil.handleInternalServerError("Error in getting the super tenant domain", e, log);
}
boolean isSuperTenantUser = RestApiCommonUtil.getLoggedInUserTenantDomain().equals(superTenantDomain);
if (!isSuperTenantUser) {
String errorMsg = "Cross Tenant resource access is not allowed for this request. User " + username + " is not allowed to access resources in " + targetTenantDomain + " as the requester is not a super " + "tenant user";
log.error(errorMsg);
ErrorDTO errorDTO = getErrorDTO(RestApiConstants.STATUS_FORBIDDEN_MESSAGE_DEFAULT, 403l, errorMsg);
throw new ForbiddenException(errorDTO);
}
// check whether the user has super tenant admin role
boolean isSuperAdminRoleNameExist = false;
try {
isSuperAdminRoleNameExist = APIUtil.isUserInRole(username, superAdminRole);
} catch (UserStoreException | APIManagementException e) {
RestApiUtil.handleInternalServerError("Error in checking whether the user has admin role", e, log);
}
if (!isSuperAdminRoleNameExist) {
String errorMsg = "Cross Tenant resource access is not allowed for this request. User " + username + " is not allowed to access resources in " + targetTenantDomain + " as the requester is not a " + "super tenant admin";
log.error(errorMsg);
ErrorDTO errorDTO = getErrorDTO(RestApiConstants.STATUS_FORBIDDEN_MESSAGE_DEFAULT, 403l, errorMsg);
throw new ForbiddenException(errorDTO);
}
}
use of org.wso2.carbon.user.api.UserStoreException in project carbon-apimgt by wso2.
the class ApplicationsApiServiceImpl method applicationsImportPost.
/**
* Import an Application which has been exported to a zip file
*
* @param fileInputStream Content stream of the zip file which contains exported Application
* @param fileDetail Meta information of the zip file
* @param preserveOwner If true, preserve the original owner of the application
* @param skipSubscriptions If true, skip subscriptions of the application
* @param appOwner Target owner of the application
* @param skipApplicationKeys Skip application keys while importing
* @param update Update if existing application found or import
* @param messageContext Message Context
* @return imported Application
*/
@Override
public Response applicationsImportPost(InputStream fileInputStream, Attachment fileDetail, Boolean preserveOwner, Boolean skipSubscriptions, String appOwner, Boolean skipApplicationKeys, Boolean update, MessageContext messageContext) throws APIManagementException {
String ownerId;
Application application;
try {
String username = RestApiCommonUtil.getLoggedInUsername();
APIConsumer apiConsumer = RestApiCommonUtil.getConsumer(username);
String extractedFolderPath = CommonUtil.getArchivePathOfExtractedDirectory(fileInputStream, ImportExportConstants.UPLOAD_APPLICATION_FILE_NAME);
String jsonContent = ImportUtils.getApplicationDefinitionAsJson(extractedFolderPath);
// Retrieving the field "data" in api.yaml/json and convert it to a JSON object for further processing
JsonElement configElement = new JsonParser().parse(jsonContent).getAsJsonObject().get(APIConstants.DATA);
ExportedApplication exportedApplication = new Gson().fromJson(configElement, ExportedApplication.class);
// Retrieve the application DTO object from the aggregated exported application
ApplicationDTO applicationDTO = exportedApplication.getApplicationInfo();
if (!StringUtils.isBlank(appOwner)) {
ownerId = appOwner;
} else if (preserveOwner != null && preserveOwner) {
ownerId = applicationDTO.getOwner();
} else {
ownerId = username;
}
if (!MultitenantUtils.getTenantDomain(ownerId).equals(MultitenantUtils.getTenantDomain(username))) {
throw new APIManagementException("Cross Tenant Imports are not allowed", ExceptionCodes.TENANT_MISMATCH);
}
String applicationGroupId = String.join(",", applicationDTO.getGroups());
if (applicationDTO.getGroups() != null && applicationDTO.getGroups().size() > 0) {
ImportUtils.validateOwner(username, applicationGroupId, apiConsumer);
}
String organization = RestApiUtil.getValidatedOrganization(messageContext);
if (APIUtil.isApplicationExist(ownerId, applicationDTO.getName(), applicationGroupId, organization) && update != null && update) {
int appId = APIUtil.getApplicationId(applicationDTO.getName(), ownerId);
Application oldApplication = apiConsumer.getApplicationById(appId);
application = preProcessAndUpdateApplication(ownerId, applicationDTO, oldApplication, oldApplication.getUUID());
} else {
application = preProcessAndAddApplication(ownerId, applicationDTO, organization);
update = Boolean.FALSE;
}
List<APIIdentifier> skippedAPIs = new ArrayList<>();
if (skipSubscriptions == null || !skipSubscriptions) {
skippedAPIs = ImportUtils.importSubscriptions(exportedApplication.getSubscribedAPIs(), ownerId, application, update, apiConsumer, organization);
}
Application importedApplication = apiConsumer.getApplicationById(application.getId());
importedApplication.setOwner(ownerId);
ApplicationInfoDTO importedApplicationDTO = ApplicationMappingUtil.fromApplicationToInfoDTO(importedApplication);
URI location = new URI(RestApiConstants.RESOURCE_PATH_APPLICATIONS + "/" + importedApplicationDTO.getApplicationId());
// check whether keys need to be skipped while import
if (skipApplicationKeys == null || !skipApplicationKeys) {
// if this is an update, old keys will be removed and the OAuth app will be overridden with new values
if (update) {
if (applicationDTO.getKeys().size() > 0 && importedApplication.getKeys().size() > 0) {
importedApplication.getKeys().clear();
}
}
// Add application keys if present and keys does not exists in the current application
if (applicationDTO.getKeys().size() > 0 && importedApplication.getKeys().size() == 0) {
for (ApplicationKeyDTO applicationKeyDTO : applicationDTO.getKeys()) {
ImportUtils.addApplicationKey(ownerId, importedApplication, applicationKeyDTO, apiConsumer, update);
}
}
}
if (skippedAPIs.isEmpty()) {
return Response.created(location).entity(importedApplicationDTO).build();
} else {
APIInfoListDTO skippedAPIListDTO = APIInfoMappingUtil.fromAPIInfoListToDTO(skippedAPIs);
return Response.created(location).status(207).entity(skippedAPIListDTO).build();
}
} catch (URISyntaxException | UserStoreException | APIImportExportException e) {
throw new APIManagementException("Error while importing Application", e);
} catch (UnsupportedEncodingException e) {
throw new APIManagementException("Error while Decoding apiId", e);
} catch (IOException e) {
throw new APIManagementException("Error while reading the application definition", e);
}
}
use of org.wso2.carbon.user.api.UserStoreException in project carbon-apimgt by wso2.
the class SettingsMappingUtil method fromSettingstoDTO.
public SettingsDTO fromSettingstoDTO(Boolean isUserAvailable, Boolean moneatizationEnabled, boolean recommendationEnabled, boolean anonymousEnabled, String organization) throws APIManagementException {
SettingsDTO settingsDTO = new SettingsDTO();
settingsDTO.setScopes(GetScopeList());
settingsDTO.setApplicationSharingEnabled(APIUtil.isMultiGroupAppSharingEnabled());
settingsDTO.setRecommendationEnabled(recommendationEnabled);
settingsDTO.setMapExistingAuthApps(APIUtil.isMapExistingAuthAppsEnabled());
settingsDTO.setMonetizationEnabled(moneatizationEnabled);
SettingsIdentityProviderDTO identityProviderDTO = new SettingsIdentityProviderDTO();
identityProviderDTO.setExternal(APIUtil.getIdentityProviderConfig() != null);
settingsDTO.setIdentityProvider(identityProviderDTO);
settingsDTO.setIsAnonymousModeEnabled(anonymousEnabled);
APIManagerConfiguration config = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration();
boolean enableChangePassword = Boolean.parseBoolean(config.getFirstProperty(APIConstants.ENABLE_CHANGE_PASSWORD));
settingsDTO.setIsPasswordChangeEnabled(enableChangePassword);
String username = RestApiCommonUtil.getLoggedInUsername();
String tenantDomain = MultitenantUtils.getTenantDomain(username);
int tenantId = APIUtil.getTenantIdFromTenantDomain(tenantDomain);
String userStorePasswordPattern = null;
String passwordPolicyPattern = null;
int passwordPolicyMinLength = -1;
int passwordPolicyMaxLength = -1;
try {
// Get password pattern from the UserStoreManager configuration
RealmConfiguration realmConfiguration = null;
RealmService realmService = ServiceReferenceHolder.getInstance().getRealmService();
if (realmService != null && tenantId != MultitenantConstants.INVALID_TENANT_ID) {
UserStoreManager userStoreManager = null;
userStoreManager = (UserStoreManager) realmService.getTenantUserRealm(tenantId).getUserStoreManager();
realmConfiguration = userStoreManager.getRealmConfiguration();
}
if (realmConfiguration != null) {
String passwordJavaRegEx = realmConfiguration.getUserStoreProperty(APIConstants.PASSWORD_JAVA_REGEX_PROPERTY);
if (passwordJavaRegEx != null && !passwordJavaRegEx.trim().isEmpty()) {
userStorePasswordPattern = passwordJavaRegEx;
}
}
// Get password pattern from the Password policy
Property passwordPolicyEnabledProperty = FrameworkUtils.getResidentIdpConfiguration(APIConstants.IS_PASSWORD_POLICY_ENABLED_PROPERTY, tenantDomain);
boolean isPasswordPolicyEnabled = Boolean.parseBoolean(passwordPolicyEnabledProperty.getValue());
if (isPasswordPolicyEnabled) {
passwordPolicyPattern = FrameworkUtils.getResidentIdpConfiguration(APIConstants.PASSWORD_POLICY_PATTERN_PROPERTY, tenantDomain).getValue();
passwordPolicyMinLength = Integer.parseInt(FrameworkUtils.getResidentIdpConfiguration(APIConstants.PASSWORD_POLICY_MIN_LENGTH_PROPERTY, tenantDomain).getValue());
passwordPolicyMaxLength = Integer.parseInt(FrameworkUtils.getResidentIdpConfiguration(APIConstants.PASSWORD_POLICY_MAX_LENGTH_PROPERTY, tenantDomain).getValue());
}
} catch (UserStoreException e) {
String errorMessage = "Error occurred in getting userRealm for the tenant: " + tenantId;
throw new APIManagementException(errorMessage, e);
} catch (FrameworkException e) {
String errorMessage = "Error occurred in getting Resident Idp Configurations for tenant: " + tenantId;
throw new APIManagementException(errorMessage, e);
}
settingsDTO.setUserStorePasswordPattern(userStorePasswordPattern);
settingsDTO.setPasswordPolicyPattern(passwordPolicyPattern);
settingsDTO.setPasswordPolicyMinLength(passwordPolicyMinLength);
settingsDTO.setPasswordPolicyMaxLength(passwordPolicyMaxLength);
if (isUserAvailable) {
settingsDTO.setGrantTypes(APIUtil.getGrantTypes());
Map<String, Environment> environments = APIUtil.getEnvironments(organization);
if (environments.isEmpty()) {
settingsDTO.apiGatewayEndpoint("http://localhost:8280, https://localhost:8243");
} else {
for (Map.Entry<String, Environment> entry : environments.entrySet()) {
Environment environment = environments.get(entry.getKey());
if (environment.isDefault()) {
settingsDTO.apiGatewayEndpoint(environment.getApiGatewayEndpoint());
break;
}
}
if (settingsDTO.getApiGatewayEndpoint() == null) {
Map.Entry<String, Environment> entry = environments.entrySet().iterator().next();
Environment environment = environments.get(entry.getKey());
settingsDTO.apiGatewayEndpoint(environment.getApiGatewayEndpoint());
}
}
}
return settingsDTO;
}
use of org.wso2.carbon.user.api.UserStoreException in project carbon-apimgt by wso2.
the class OAuthJwtAuthenticatorImpl method handleScopeValidation.
/**
* Handle scope validation
*
* @param accessToken JWT token
* @param signedJWTInfo : Signed token info
* @param message : cxf Message
*/
private boolean handleScopeValidation(Message message, SignedJWTInfo signedJWTInfo, String accessToken) throws APIManagementException, ParseException {
String maskedToken = message.get(RestApiConstants.MASKED_TOKEN).toString();
OAuthTokenInfo oauthTokenInfo = new OAuthTokenInfo();
oauthTokenInfo.setAccessToken(accessToken);
oauthTokenInfo.setEndUserName(signedJWTInfo.getJwtClaimsSet().getSubject());
String scopeClaim = signedJWTInfo.getJwtClaimsSet().getStringClaim(JwtTokenConstants.SCOPE);
if (scopeClaim != null) {
String orgId = RestApiUtil.resolveOrganization(message);
String[] scopes = scopeClaim.split(JwtTokenConstants.SCOPE_DELIMITER);
scopes = java.util.Arrays.stream(scopes).filter(s -> s.contains(orgId)).map(s -> s.replace(APIConstants.URN_CHOREO + orgId + ":", "")).toArray(size -> new String[size]);
oauthTokenInfo.setScopes(scopes);
if (validateScopes(message, oauthTokenInfo)) {
// Add the user scopes list extracted from token to the cxf message
message.getExchange().put(RestApiConstants.USER_REST_API_SCOPES, oauthTokenInfo.getScopes());
// If scope validation successful then set tenant name and user name to current context
String tenantDomain = MultitenantUtils.getTenantDomain(oauthTokenInfo.getEndUserName());
int tenantId;
PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
RealmService realmService = (RealmService) carbonContext.getOSGiService(RealmService.class, null);
try {
String username = oauthTokenInfo.getEndUserName();
if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
// when the username is an email in supertenant, it has at least 2 occurrences of '@'
long count = username.chars().filter(ch -> ch == '@').count();
// in the case of email, there will be more than one '@'
boolean isEmailUsernameEnabled = Boolean.parseBoolean(CarbonUtils.getServerConfiguration().getFirstProperty("EnableEmailUserName"));
if (isEmailUsernameEnabled || (username.endsWith(SUPER_TENANT_SUFFIX) && count <= 1)) {
username = MultitenantUtils.getTenantAwareUsername(username);
}
}
if (log.isDebugEnabled()) {
log.debug("username = " + username + "masked token " + maskedToken);
}
tenantId = realmService.getTenantManager().getTenantId(tenantDomain);
carbonContext.setTenantDomain(tenantDomain);
carbonContext.setTenantId(tenantId);
carbonContext.setUsername(username);
message.put(RestApiConstants.SUB_ORGANIZATION, orgId);
if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
APIUtil.loadTenantConfigBlockingMode(tenantDomain);
}
return true;
} catch (UserStoreException e) {
log.error("Error while retrieving tenant id for tenant domain: " + tenantDomain, e);
}
log.debug("Scope validation success for the token " + maskedToken);
return true;
}
log.error("scopes validation failed for the token" + maskedToken);
return false;
}
log.error("scopes validation failed for the token" + maskedToken);
return false;
}
Aggregations