<commit_before>/*
 * Copyright (c) 2013, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.wso2.carbon.identity.oauth.endpoint.token;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.cxf.interceptor.InInterceptors;
import org.apache.oltu.oauth2.as.response.OAuthASResponse;
import org.apache.oltu.oauth2.as.response.OAuthASResponse.OAuthTokenResponseBuilder;
import org.apache.oltu.oauth2.common.OAuth;
import org.apache.oltu.oauth2.common.error.OAuthError;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.OAuthResponse;
import org.apache.oltu.oauth2.common.message.types.GrantType;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.identity.oauth.client.authn.filter.OAuthClientAuthenticatorProxy;
import org.wso2.carbon.identity.oauth.common.OAuth2ErrorCodes;
import org.wso2.carbon.identity.oauth.common.OAuthConstants;
import org.wso2.carbon.identity.oauth.common.exception.OAuthClientException;
import org.wso2.carbon.identity.oauth.endpoint.OAuthRequestWrapper;
import org.wso2.carbon.identity.oauth.endpoint.exception.InvalidApplicationClientException;
import org.wso2.carbon.identity.oauth.endpoint.exception.InvalidRequestParentException;
import org.wso2.carbon.identity.oauth.endpoint.exception.TokenEndpointAccessDeniedException;
import org.wso2.carbon.identity.oauth.endpoint.exception.TokenEndpointBadRequestException;
import org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil;
import org.wso2.carbon.identity.oauth2.ResponseHeader;
import org.wso2.carbon.identity.oauth2.bean.OAuthClientAuthnContext;
import org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenReqDTO;
import org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenRespDTO;
import org.wso2.carbon.identity.oauth2.model.CarbonOAuthTokenRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;

import static org.apache.commons.lang.StringUtils.isNotBlank;
import static org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil.startSuperTenantFlow;
import static org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil.triggerOnTokenExceptionListeners;
import static org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil.validateOauthApplication;
import static org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil.validateParams;

@Path("/token")
@InInterceptors(classes = OAuthClientAuthenticatorProxy.class)
public class OAuth2TokenEndpoint {

    private static final Log log = LogFactory.getLog(OAuth2TokenEndpoint.class);
    public static final String BEARER = "Bearer";
    private static final String SQL_ERROR = "sql_error";

    @POST
    @Path("/")
    @Consumes("application/x-www-form-urlencoded")
    @Produces("application/json")
    public Response issueAccessToken(@Context HttpServletRequest request,
                                     MultivaluedMap<String, String> paramMap)
            throws OAuthSystemException, InvalidRequestParentException {

        try {
            startSuperTenantFlow();
            validateRepeatedParams(request, paramMap);
            HttpServletRequestWrapper httpRequest = new OAuthRequestWrapper(request, paramMap);

            CarbonOAuthTokenRequest oauthRequest = buildCarbonOAuthTokenRequest(httpRequest);
            validateOAuthApplication(oauthRequest.getoAuthClientAuthnContext());
            OAuth2AccessTokenRespDTO oauth2AccessTokenResp = issueAccessToken(oauthRequest);

            if (oauth2AccessTokenResp.getErrorMsg() != null) {
                return handleErrorResponse(oauth2AccessTokenResp);
            } else {
                return buildTokenResponse(oauth2AccessTokenResp);
            }
        } catch (TokenEndpointBadRequestException | OAuthSystemException | InvalidApplicationClientException e) {
            triggerOnTokenExceptionListeners(e, request, paramMap);
            throw e;
        } finally {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }

    private CarbonOAuthTokenRequest buildCarbonOAuthTokenRequest(HttpServletRequestWrapper httpRequest)
            throws OAuthSystemException, TokenEndpointBadRequestException {

        try {
            return new CarbonOAuthTokenRequest(httpRequest);
        } catch (OAuthProblemException e) {
            return handleInvalidRequest(e);
        }
    }

    private CarbonOAuthTokenRequest handleInvalidRequest(OAuthProblemException e) throws TokenEndpointBadRequestException {

        if (isInvalidRequest(e) || isUnsupportedGrantType(e)) {
            if (log.isDebugEnabled()) {
                log.debug("Error: " + e.getError() + ", description: " + e.getDescription());
            }
        } else {
            log.error("Error while creating the Carbon OAuth token request", e);
        }
        throw new TokenEndpointBadRequestException(e);
    }

    private boolean isUnsupportedGrantType(OAuthProblemException e) {<commit_msg>Fix if Username or Password were not provided in token request, error_description needs to be improved<commit_after>/*
 * Copyright (c) 2013, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.wso2.carbon.identity.oauth.endpoint.token;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.cxf.interceptor.InInterceptors;
import org.apache.oltu.oauth2.as.response.OAuthASResponse;
import org.apache.oltu.oauth2.as.response.OAuthASResponse.OAuthTokenResponseBuilder;
import org.apache.oltu.oauth2.common.OAuth;
import org.apache.oltu.oauth2.common.error.OAuthError;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.OAuthResponse;
import org.apache.oltu.oauth2.common.message.types.GrantType;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.identity.oauth.client.authn.filter.OAuthClientAuthenticatorProxy;
import org.wso2.carbon.identity.oauth.common.OAuth2ErrorCodes;
import org.wso2.carbon.identity.oauth.common.OAuthConstants;
import org.wso2.carbon.identity.oauth.common.exception.OAuthClientException;
import org.wso2.carbon.identity.oauth.endpoint.OAuthRequestWrapper;
import org.wso2.carbon.identity.oauth.endpoint.exception.InvalidApplicationClientException;
import org.wso2.carbon.identity.oauth.endpoint.exception.InvalidRequestParentException;
import org.wso2.carbon.identity.oauth.endpoint.exception.TokenEndpointAccessDeniedException;
import org.wso2.carbon.identity.oauth.endpoint.exception.TokenEndpointBadRequestException;
import org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil;
import org.wso2.carbon.identity.oauth2.ResponseHeader;
import org.wso2.carbon.identity.oauth2.bean.OAuthClientAuthnContext;
import org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenReqDTO;
import org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenRespDTO;
import org.wso2.carbon.identity.oauth2.model.CarbonOAuthTokenRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;

import static org.apache.commons.lang.StringUtils.isNotBlank;
import static org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil.startSuperTenantFlow;
import static org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil.triggerOnTokenExceptionListeners;
import static org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil.validateOauthApplication;
import static org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil.validateParams;

@Path("/token")
@InInterceptors(classes = OAuthClientAuthenticatorProxy.class)
public class OAuth2TokenEndpoint {

    private static final Log log = LogFactory.getLog(OAuth2TokenEndpoint.class);
    public static final String BEARER = "Bearer";
    private static final String SQL_ERROR = "sql_error";

    @POST
    @Path("/")
    @Consumes("application/x-www-form-urlencoded")
    @Produces("application/json")
    public Response issueAccessToken(@Context HttpServletRequest request,
                                     MultivaluedMap<String, String> paramMap)
            throws OAuthSystemException, InvalidRequestParentException {

        try {
            startSuperTenantFlow();
            validateRepeatedParams(request, paramMap);
            HttpServletRequestWrapper httpRequest = new OAuthRequestWrapper(request, paramMap);

            CarbonOAuthTokenRequest oauthRequest = buildCarbonOAuthTokenRequest(httpRequest);
            validateOAuthApplication(oauthRequest.getoAuthClientAuthnContext());
            OAuth2AccessTokenRespDTO oauth2AccessTokenResp = issueAccessToken(oauthRequest);

            if (oauth2AccessTokenResp.getErrorMsg() != null) {
                return handleErrorResponse(oauth2AccessTokenResp);
            } else {
                return buildTokenResponse(oauth2AccessTokenResp);
            }
        } catch (TokenEndpointBadRequestException | OAuthSystemException | InvalidApplicationClientException e) {
            OAuth2AccessTokenRespDTO oAuth2AccessTokenRespDTO = setOAuth2AccessTokenRespDTO(e);
            triggerOnTokenExceptionListeners(e, request, paramMap);
            return handleErrorResponse(oAuth2AccessTokenRespDTO);

        } finally {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }

    private OAuth2AccessTokenRespDTO setOAuth2AccessTokenRespDTO(Exception e) {

        OAuth2AccessTokenRespDTO oAuth2AccessTokenRespDTO = new OAuth2AccessTokenRespDTO();
        oAuth2AccessTokenRespDTO.setError(true);
        oAuth2AccessTokenRespDTO.setErrorCode(OAuth2ErrorCodes.INVALID_REQUEST);
        oAuth2AccessTokenRespDTO.setErrorMsg(e.getMessage());
        return oAuth2AccessTokenRespDTO;
    }

    private CarbonOAuthTokenRequest buildCarbonOAuthTokenRequest(HttpServletRequestWrapper httpRequest)
            throws OAuthSystemException, TokenEndpointBadRequestException {

        try {
            return new CarbonOAuthTokenRequest(httpRequest);
        } catch (OAuthProblemException e) {
            return handleInvalidRequest(e);
        }
    }

    private CarbonOAuthTokenRequest handleInvalidRequest(OAuthProblemException e) throws TokenEndpointBadRequestException {

        if (isInvalidRequest(e) || isUnsupportedGrantType(e)) {
            if (log.isDebugEnabled()) {
                log.debug("Error: " + e.getError() + ", description: " + e.getDescription());
            }
        } else {
            log.error("Error while creating the Carbon OAuth token request", e);
        }
        throw new TokenEndpointBadRequestException(e.getDescription(), e.getError(), e);
    }

    private boolean isUnsupportedGrantType(OAuthProblemException e) {
{'fraction_non_alphanumeric': 0.08841940532081377, 'fraction_numerical': 0.00970266040688576, 'mean_word_length': 4.320982514571191, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 6, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3879419', 'n_tokens_mistral': 3726, 'n_tokens_neox': 3632, 'n_words': 657}