Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support to access organization resources in tenant perspective #295

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion components/org.wso2.carbon.identity.auth.service/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
<groupId>org.wso2.carbon.identity.auth.rest</groupId>
<artifactId>identity-carbon-auth-rest</artifactId>
<relativePath>../../pom.xml</relativePath>
<version>1.9.15-SNAPSHOT</version>
<version>1.9.14</version>
</parent>

<modelVersion>4.0.0</modelVersion>
Expand Down Expand Up @@ -215,6 +215,7 @@
version="${org.wso2.carbon.identity.oauth.import.version.range}",
org.wso2.carbon.identity.organization.management.service; version="${org.wso2.carbon.identity.organization.management.core.version.range}",
org.wso2.carbon.identity.organization.management.service.exception; version="${org.wso2.carbon.identity.organization.management.core.version.range}",
org.wso2.carbon.identity.organization.management.service.constant; version="${org.wso2.carbon.identity.organization.management.core.version.range}",
org.wso2.carbon.identity.handler.event.account.lock.exception;
version="${identity.event.handler.account.lock.version.range}",
com.nimbusds.jwt; version="${nimbusds.osgi.version.range}",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
import org.wso2.carbon.identity.auth.service.AuthenticationResult;
import org.wso2.carbon.identity.auth.service.AuthenticationStatus;
import org.wso2.carbon.identity.auth.service.handler.AuthenticationHandler;
import org.wso2.carbon.identity.auth.service.internal.AuthenticationServiceHolder;
import org.wso2.carbon.identity.auth.service.util.AuthConfigurationUtil;
import org.wso2.carbon.identity.auth.service.util.Constants;
import org.wso2.carbon.identity.core.bean.context.MessageContext;
Expand All @@ -55,8 +56,11 @@
import org.wso2.carbon.identity.oauth2.token.bindings.TokenBinding;
import org.wso2.carbon.identity.oauth2.util.OAuth2Util;
import org.wso2.carbon.identity.oauth2.validators.RefreshTokenValidator;
import org.wso2.carbon.identity.organization.management.service.exception.OrganizationManagementException;
import org.wso2.carbon.identity.organization.management.service.constant.OrganizationManagementConstants;

import java.text.ParseException;
import java.util.Arrays;
import java.util.Map;
import java.util.Optional;

Expand Down Expand Up @@ -173,8 +177,21 @@ protected AuthenticationResult doAuthenticate(MessageContext messageContext) {
ServiceProvider serviceProvider = null;
String serviceProviderName = null;
String serviceProviderUUID = null;
String applicationResidentTenantDomain = null;
try {
serviceProvider = OAuth2Util.getServiceProvider(oAuth2IntrospectionResponseDTO.getClientId());
// Getting the accessing tenant domain from the authenticated user through the introspection
// response where the token is introspected.
if (authorizedUser != null) {
applicationResidentTenantDomain = authorizedUser.getTenantDomain();
serviceProvider = OAuth2Util.getServiceProvider(
oAuth2IntrospectionResponseDTO.getClientId(), applicationResidentTenantDomain);
boolean isB2BSharedApp = Arrays.stream(serviceProvider.getSpProperties()).anyMatch(
property -> "isAppShared".equals(property.getName()) &&
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

isAppShared - > Use a contant

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use the existing contant

Boolean.parseBoolean(property.getValue()));
authenticationContext.addParameter("isB2BAppShared", isB2BSharedApp);
} else {
serviceProvider = OAuth2Util.getServiceProvider(oAuth2IntrospectionResponseDTO.getClientId());
}
if (serviceProvider != null) {
serviceProviderName = serviceProvider.getApplicationName();
serviceProviderUUID = serviceProvider.getApplicationResourceId();
Expand All @@ -193,8 +210,14 @@ protected AuthenticationResult doAuthenticate(MessageContext messageContext) {

String serviceProviderTenantDomain = null;
try {
serviceProviderTenantDomain =
OAuth2Util.getTenantDomainOfOauthApp(oAuth2IntrospectionResponseDTO.getClientId());
if (StringUtils.isNotEmpty(applicationResidentTenantDomain)) {
serviceProviderTenantDomain =
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove the method because we are extracting the tenant domain from above

OAuth2Util.getTenantDomainOfOauthApp(oAuth2IntrospectionResponseDTO.getClientId(),
applicationResidentTenantDomain);
} else {
serviceProviderTenantDomain =
OAuth2Util.getTenantDomainOfOauthApp(oAuth2IntrospectionResponseDTO.getClientId());
}
} catch (InvalidOAuthClientException | IdentityOAuth2Exception e) {
if (log.isDebugEnabled()) {
log.debug("Error occurred while getting the OAuth App tenantDomain by Consumer key: "
Expand Down
3 changes: 2 additions & 1 deletion components/org.wso2.carbon.identity.authz.valve/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
<groupId>org.wso2.carbon.identity.auth.rest</groupId>
<artifactId>identity-carbon-auth-rest</artifactId>
<relativePath>../../pom.xml</relativePath>
<version>1.9.15-SNAPSHOT</version>
<version>1.9.14</version>
</parent>

<modelVersion>4.0.0</modelVersion>
Expand Down Expand Up @@ -100,6 +100,7 @@
org.wso2.carbon.identity.authz.service.*;version="${org.wso2.carbon.identity.authz.service.version.range}",
org.apache.catalina.*;version="1.7.0",
org.wso2.carbon.identity.organization.management.authz.service; version="${org.wso2.carbon.identity.organization.management.version.range}",
org.wso2.carbon.identity.organization.management.authz.service.util; version="${org.wso2.carbon.identity.organization.management.version.range}",
org.wso2.carbon.identity.organization.management.service.constant; version="${org.wso2.carbon.identity.organization.management.core.version.range}"
</Import-Package>
<Export-Package>!org.wso2.carbon.identity.authz.valve.internal,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
import org.wso2.carbon.identity.organization.management.authz.service.OrganizationManagementAuthorizationContext;
import org.wso2.carbon.identity.organization.management.service.constant.OrganizationManagementConstants;
import org.wso2.carbon.identity.organization.management.service.exception.OrganizationManagementException;
import org.wso2.carbon.identity.organization.management.service.util.OrganizationManagementUtil;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;

import java.io.IOException;
Expand Down Expand Up @@ -85,25 +86,37 @@ public void invoke(Request request, Response response) throws IOException, Servl
}

String requestURI = request.getRequestURI();
if (!isRequestValidForTenant(authenticationContext, authorizationContext, request)) {
String spTenantDomain = null;
String isAppSharedStr = null;
if (authenticationContext.getParameter("serviceProviderTenantDomain") != null) {
spTenantDomain = authenticationContext.getParameter("serviceProviderTenantDomain").toString();
}
if (authenticationContext.getParameter("isAppShared") != null) {
isAppSharedStr = authenticationContext.getParameter("isAppShared").toString();
}
// If the application is not a shared application and the tenant is an organization, skip the
// request validation for the tenant.
if (!isSubOrganizationApp(spTenantDomain, isAppSharedStr)) {
if (!isRequestValidForTenant(authenticationContext, authorizationContext, request)) {
/*
Forbidden the /o/<org-id> path requests if the org level authz failed and
resource is not cross tenant allowed or authenticated user doesn't belong to the accessed resource's org.
*/
if (requestURI.startsWith(ORGANIZATION_PATH_PARAM)) {
if (requestURI.startsWith(ORGANIZATION_PATH_PARAM)) {
APIErrorResponseHandler.handleErrorResponse(authenticationContext, response,
HttpServletResponse.SC_FORBIDDEN, null);
return;
}
if (log.isDebugEnabled()) {
log.debug("Authorization to " + request.getRequestURI()
+ " is denied because the authenticated user belongs to different tenant domain: "
+ authenticationContext.getUser().getTenantDomain()
+ " and cross-domain access for the tenant is disabled.");
}
APIErrorResponseHandler.handleErrorResponse(authenticationContext, response,
HttpServletResponse.SC_FORBIDDEN, null);
HttpServletResponse.SC_UNAUTHORIZED, null);
return;
}
if (log.isDebugEnabled()) {
log.debug("Authorization to " + request.getRequestURI()
+ " is denied because the authenticated user belongs to different tenant domain: "
+ authenticationContext.getUser().getTenantDomain()
+ " and cross-domain access for the tenant is disabled.");
}
APIErrorResponseHandler.handleErrorResponse(authenticationContext, response,
HttpServletResponse.SC_UNAUTHORIZED, null);
return;
}

if (!isUserEmpty(authenticationContext)) {
Expand Down Expand Up @@ -299,4 +312,20 @@ private void startOrganizationBoundTenantFlow(String authorizedOrganization) {
throw new AuthRuntimeException("Error while resolving tenant domain by organization.", e);
}
}

private boolean isSubOrganizationApp (String spTenantDomain, String isAppShared) {

try {
if (StringUtils.isNotEmpty(spTenantDomain) && StringUtils.isNotEmpty(isAppShared)) {
if (OrganizationManagementUtil.isOrganization(spTenantDomain) && !Boolean.parseBoolean(isAppShared)) {
return true;
}
} else {
return false;
}
} catch (OrganizationManagementException e) {
throw new AuthRuntimeException("Error while checking the tenant is an organization.", e);
}
return false;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
<groupId>org.wso2.carbon.identity.auth.rest</groupId>
<artifactId>identity-carbon-auth-rest</artifactId>
<relativePath>../../pom.xml</relativePath>
<version>1.9.15-SNAPSHOT</version>
<version>1.9.14</version>
</parent>

<modelVersion>4.0.0</modelVersion>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,15 @@
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.valves.ValveBase;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.MDC;
import org.wso2.carbon.base.ServerConfiguration;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.identity.base.IdentityRuntimeException;
import org.wso2.carbon.identity.context.rewrite.bean.OrganizationRewriteContext;
import org.wso2.carbon.identity.context.rewrite.bean.RewriteContext;
import org.wso2.carbon.identity.context.rewrite.internal.ContextRewriteValveServiceComponentHolder;
import org.wso2.carbon.identity.core.util.IdentityConfigParser;
Expand All @@ -41,8 +43,10 @@
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
Expand All @@ -59,6 +63,7 @@
public class TenantContextRewriteValve extends ValveBase {

private static List<RewriteContext> contextsToRewrite;
private static List<OrganizationRewriteContext> contextsToRewriteInTenantPerspective;
private static List<String> contextListToOverwriteDispatch;
private static List<String> ignorePathListForOverwriteDispatch;
private static List<String> organizationRoutingOnlySupportedAPIPaths;
Expand All @@ -73,6 +78,7 @@ protected synchronized void startInternal() throws LifecycleException {
super.startInternal();
// Initialize the tenant context rewrite valve.
contextsToRewrite = getContextsToRewrite();
contextsToRewriteInTenantPerspective = getContextsToRewriteInTenantPerspective();
contextListToOverwriteDispatch = getContextListToOverwriteDispatchLocation();
ignorePathListForOverwriteDispatch = getIgnorePathListForOverwriteDispatch();
isTenantQualifiedUrlsEnabled = isTenantQualifiedUrlsEnabled();
Expand Down Expand Up @@ -110,6 +116,26 @@ public void invoke(Request request, Response response) throws IOException, Servl
}
}

outerLoop:
for (OrganizationRewriteContext context : contextsToRewriteInTenantPerspective) {
Pattern patternTenantPerspective = Pattern.compile("^/t/[^/]+/o/[a-f0-9\\-]+?" + context.getContext());
if (patternTenantPerspective.matcher(requestURI).find() && CollectionUtils.isNotEmpty(context.getSubPaths())) {
for (Pattern subPath : context.getSubPaths()) {
if (subPath.matcher(requestURI).find()) {
isContextRewrite = true;
isWebApp = context.isWebApp();
contextToForward = context.getContext();
int startIndex = requestURI.indexOf("/o/") + 3;
int endIndex = requestURI.indexOf("/", startIndex);
String appOrgId = requestURI.substring(startIndex, endIndex);
PrivilegedCarbonContext.getThreadLocalCarbonContext().
setApplicationResidentOrganizationId(appOrgId);
break outerLoop;
}
}
}
}

String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
try {
MDC.put(TENANT_DOMAIN, tenantDomain);
Expand All @@ -135,7 +161,8 @@ public void invoke(Request request, Response response) throws IOException, Servl
Ex-: Request: /t/<tenant-domain>/o/api/server/v1/applications --> /o/server/v1/applications
*/
if (!requestURI.startsWith(ORGANIZATION_PATH_PARAM) &&
requestURI.contains(ORGANIZATION_PATH_PARAM)) {
requestURI.contains(ORGANIZATION_PATH_PARAM) &&
!isOrganizationIdAvailableInTenantPerspective(requestURI)) {
dispatchLocation = "/o" + dispatchLocation;
}
if (contextListToOverwriteDispatch.contains(contextToForward) && !isIgnorePath(dispatchLocation)) {
Expand All @@ -151,7 +178,10 @@ public void invoke(Request request, Response response) throws IOException, Servl
requestURI = requestURI.replace(carbonWebContext + "/", "");
}
//Servlet
requestURI = requestURI.replace("/t/" + tenantDomain, "");
if (StringUtils.isEmpty(PrivilegedCarbonContext.getThreadLocalCarbonContext()
.getApplicationResidentOrganizationId())) {
requestURI = requestURI.replace("/t/" + tenantDomain, "");
}
request.getRequestDispatcher(requestURI).forward(request, response);
}
}
Expand All @@ -176,6 +206,11 @@ public void invoke(Request request, Response response) throws IOException, Servl
}
}

private boolean isOrganizationIdAvailableInTenantPerspective(String requestURI) {

return Pattern.compile("^/t/[^/]+/o/[a-f0-9\\-]+?").matcher(requestURI).find();
}

private void unsetMDCThreadLocals() {

MDC.remove(TENANT_DOMAIN);
Expand Down Expand Up @@ -217,6 +252,51 @@ private List<RewriteContext> getContextsToRewrite() {
return rewriteContexts;
}

private List<OrganizationRewriteContext> getContextsToRewriteInTenantPerspective() {
ShanChathusanda93 marked this conversation as resolved.
Show resolved Hide resolved

List<OrganizationRewriteContext> organizationRewriteContexts = new ArrayList<>();
Map<String, Object> configuration = IdentityConfigParser.getInstance().getConfiguration();
Object webAppBasePathContexts = configuration.get("OrgContextsToRewriteInTenantPerspective.WebApp.Context." +
"BasePath");
setOrganizationRewriteContexts(organizationRewriteContexts, webAppBasePathContexts, true);

Object webAppSubPathContexts = configuration.get("OrgContextsToRewriteInTenantPerspective.WebApp.Context." +
"SubPaths.Path");
setSubPathContexts(organizationRewriteContexts, webAppSubPathContexts);

return organizationRewriteContexts;
}

private void setOrganizationRewriteContexts(List<OrganizationRewriteContext> organizationRewriteContexts,
Object basePathContexts, boolean isWebApp) {

if (basePathContexts != null) {
if (basePathContexts instanceof ArrayList) {
for (String context : (ArrayList<String>) basePathContexts) {
organizationRewriteContexts.add(new OrganizationRewriteContext(isWebApp, context));
}
} else {
organizationRewriteContexts.add(new OrganizationRewriteContext(isWebApp,
basePathContexts.toString()));
}
}
}

private void setSubPathContexts(List<OrganizationRewriteContext> organizationRewriteContexts,
Object subPathContexts) {

if (subPathContexts instanceof ArrayList) {
for (String subPath : (ArrayList<String>) subPathContexts) {
Optional<OrganizationRewriteContext> maybeOrgRewriteContext = organizationRewriteContexts.stream()
.filter(rewriteContext -> subPath.startsWith(rewriteContext.getContext()))
.max(Comparator.comparingInt(rewriteContext -> rewriteContext.getContext().length()));
maybeOrgRewriteContext.ifPresent(
organizationRewriteContext -> organizationRewriteContext.addSubPath(
Pattern.compile("^/t/[^/]+/o/[a-f0-9\\-]+" + subPath)));
}
}
}

/**
* Get context list to overwrite dispatch location.
*
Expand Down
Loading
Loading