Search in sources :

Example 1 with PersistenceEmptyResultSetException

use of net.petafuel.styx.core.persistence.PersistenceEmptyResultSetException in project styx by petafuel.

the class AccessTokenFilter method checkToken.

@Override
public boolean checkToken(String tokenHash) {
    AccessToken accessToken;
    try {
        accessToken = PersistentAccessToken.get(tokenHash);
    } catch (PersistenceEmptyResultSetException persistenceEmptyResultSetException) {
        // if there was no matching token found in the database, always return unauthorized
        ResponseEntity responseEntity = new ResponseEntity(ResponseConstant.UNAUTHORIZED, ResponseCategory.ERROR, ResponseOrigin.CLIENT);
        throw new StyxException(responseEntity);
    }
    if (accessToken.getLastUsedOn() == null && (TimeUnit.MILLISECONDS.toSeconds(new Date().getTime() - accessToken.getCreatedAt().getTime())) > accessToken.getExpiresIn()) {
        MasterToken masterToken = PersistentClientApp.get(accessToken.getClientMasterToken());
        LOG.warn("Access token expired before first usage, invalidated. master={}, access_token_created={}, serviceBinding={}", masterToken.getName(), accessToken.getCreatedAt(), accessToken.getServiceType());
        PersistentAccessToken.setValid(tokenHash, false);
        return false;
    }
    // get master token and check restrictions
    MasterToken masterToken = PersistentClientApp.get(accessToken.getClientMasterToken());
    checkRestrictions(masterToken, accessToken.getServiceType());
    // check if maxUsages is reached
    checkMaxUsages(masterToken, accessToken);
    // log necessary token information
    LOG.info("Request sent with following token information: accessToken={} valid={} serviceType={} usages={} clientReference={} createdAt={} masterTokenName={} masterTokenEnabled={}", accessToken.getId(), accessToken.isValid(), accessToken.getServiceType(), accessToken.getUsages(), accessToken.getClientReference(), accessToken.getCreatedAt(), masterToken.getName(), masterToken.isEnabled());
    // get service requirements from Target-Resource class or method
    List<XS2ATokenType> serviceRequirements = null;
    if (ri.getResourceMethod().getAnnotation(CheckAccessToken.class) != null) {
        serviceRequirements = Arrays.asList(ri.getResourceMethod().getAnnotation(CheckAccessToken.class).allowedServices());
    } else if (ri.getResourceClass().getAnnotation(CheckAccessToken.class) != null) {
        serviceRequirements = Arrays.asList(ri.getResourceClass().getAnnotation(CheckAccessToken.class).allowedServices());
    }
    // Get all TokenTypeMapperSPI implementations
    List<TokenTypeMapperSPI> tokenTypeMapperImpls = new TokenTypeMapperService().providers();
    TokenTypeMapperSPI concreteTokenTypeMapper = tokenTypeMapperImpls.stream().filter(tokenTypeMapperSPI -> tokenTypeMapperSPI.getMapping(accessToken.getServiceType()) != null).findFirst().orElse(null);
    if (concreteTokenTypeMapper == null || (serviceRequirements != null && !serviceRequirements.contains(concreteTokenTypeMapper.getMapping(accessToken.getServiceType())))) {
        if (concreteTokenTypeMapper == null) {
            LOG.error("There was not TokenTypeMapperSPI implementation found within the classpath, tokens cannot be validated against access controll");
        }
        ResponseEntity responseEntity = new ResponseEntity(ResponseConstant.STYX_TOKEN_ACCESS_VIOLATION, ResponseCategory.ERROR, ResponseOrigin.CLIENT);
        throw new StyxException(responseEntity);
    }
    // update lastUsedOn and increase usages of accessToken
    if (ri.getResourceClass().isAnnotationPresent(CheckAccessToken.class) && ri.getResourceClass().getAnnotation(CheckAccessToken.class).incrementUsage()) {
        PersistentAccessToken.updateLastUsedOn(tokenHash);
    }
    return accessToken.isValid() && masterToken.isEnabled();
}
Also used : ResponseEntity(net.petafuel.styx.api.exception.ResponseEntity) MasterToken(net.petafuel.styx.core.persistence.models.MasterToken) CheckAccessToken(net.petafuel.styx.api.filter.authentication.boundary.CheckAccessToken) TokenTypeMapperSPI(net.petafuel.styx.spi.tokentypemapper.spi.TokenTypeMapperSPI) AccessToken(net.petafuel.styx.core.persistence.models.AccessToken) CheckAccessToken(net.petafuel.styx.api.filter.authentication.boundary.CheckAccessToken) PersistentAccessToken(net.petafuel.styx.core.persistence.layers.PersistentAccessToken) PersistenceEmptyResultSetException(net.petafuel.styx.core.persistence.PersistenceEmptyResultSetException) TokenTypeMapperService(net.petafuel.styx.spi.tokentypemapper.TokenTypeMapperService) XS2ATokenType(net.petafuel.styx.spi.tokentypemapper.api.XS2ATokenType) StyxException(net.petafuel.styx.api.exception.StyxException) Date(java.util.Date)

Example 2 with PersistenceEmptyResultSetException

use of net.petafuel.styx.core.persistence.PersistenceEmptyResultSetException in project styx by petafuel.

the class PreAuthAccessFilter method filter.

/**
 * Supressing java:S3776 -> need to rework logic to reduce code complexity
 *
 * @param containerRequestContext
 */
@Override
@SuppressWarnings("java:S3776")
public void filter(ContainerRequestContext containerRequestContext) {
    XS2AStandard xs2AStandard = (XS2AStandard) containerRequestContext.getProperty(XS2AStandard.class.getName());
    IOParser ioParser = new IOParser(xs2AStandard.getAspsp());
    ImplementerOption ioPreAuthRequired = ioParser.get("IO6");
    if (ioPreAuthRequired != null && ioPreAuthRequired.getOptions().get(IOParser.Option.REQUIRED)) {
        LOG.info("ASPSP bic={} requires pre-auth", xs2AStandard.getAspsp().getBic());
        // preauth is available and required for this bank -> check if preauth id is present
        String preAuthIdString = containerRequestContext.getHeaderString(PRE_AUTH_ID);
        if (preAuthIdString == null || "".equals(preAuthIdString)) {
            throw new StyxException(new ResponseEntity("The requested aspsps requires a pre-step authorisation, preAuthId Header is missing", ResponseConstant.STYX_PREAUTH_HEADER_REQUIRED, ResponseCategory.ERROR, ResponseOrigin.CLIENT));
        }
        try {
            UUID preAuthId = UUID.fromString(preAuthIdString);
            OAuthSession oAuthSession = PersistentOAuthSession.getById(preAuthId);
            LOG.info("Loaded state={} oauth_session", oAuthSession.getState());
            STYX03.setPreauthId(preAuthId);
            if (oAuthSession.getAccessToken() == null || oAuthSession.getAccessTokenExpiresAt() == null) {
                throw new PersistenceEmptyResultSetException("The access_token data should be set");
            }
            if (oAuthSession.getAccessTokenExpiresAt().before(new Date())) {
                if (oAuthSession.getRefreshTokenExpiresAt().after(new Date())) {
                    oAuthSession = refreshToken(oAuthSession);
                } else {
                    throw new OAuthTokenExpiredException(OAuthTokenExpiredException.MESSAGE);
                }
            }
            // Add the Authorization: <type> <credentials> header to the request context so we can use it later on demand
            Map<String, String> additionalHeaders = new HashMap<>();
            additionalHeaders.put(XS2AHeader.AUTHORIZATION, oAuthSession.getTokenType() + " " + oAuthSession.getAccessToken());
            containerRequestContext.setProperty(PreAuthAccessFilter.class.getName(), additionalHeaders);
            LOG.info("Successfully attached pre-auth from oAuthSessionState={}", oAuthSession.getState());
        } catch (PersistenceEmptyResultSetException noOauthSessionFound) {
            throw new StyxException(new ResponseEntity("There was no valid pre-step authorisation found for the specified preAuthId", ResponseConstant.STYX_PREAUTH_NOT_AVAILABLE, ResponseCategory.ERROR, ResponseOrigin.CLIENT));
        } catch (OAuthTokenExpiredException tokenExpired) {
            throw new StyxException(new ResponseEntity(tokenExpired.getMessage(), ResponseConstant.STYX_PREAUTH_EXPIRED, ResponseCategory.ERROR, ResponseOrigin.CLIENT));
        }
    }
}
Also used : XS2AStandard(net.petafuel.styx.core.banklookup.XS2AStandard) OAuthTokenExpiredException(net.petafuel.styx.core.xs2a.exceptions.OAuthTokenExpiredException) HashMap(java.util.HashMap) PersistentOAuthSession(net.petafuel.styx.core.persistence.layers.PersistentOAuthSession) OAuthSession(net.petafuel.styx.core.xs2a.oauth.entities.OAuthSession) PersistenceEmptyResultSetException(net.petafuel.styx.core.persistence.PersistenceEmptyResultSetException) ImplementerOption(net.petafuel.styx.core.banklookup.sad.entities.ImplementerOption) StyxException(net.petafuel.styx.api.exception.StyxException) Date(java.util.Date) ResponseEntity(net.petafuel.styx.api.exception.ResponseEntity) IOParser(net.petafuel.styx.core.ioprocessing.IOParser) UUID(java.util.UUID)

Example 3 with PersistenceEmptyResultSetException

use of net.petafuel.styx.core.persistence.PersistenceEmptyResultSetException in project styx by petafuel.

the class OAuthCallbackProcessor method handlePreStepOAuth2.

/**
 * Legacy method to handle pre-step authentication for Sparda, might be deprecated in the future
 *
 * @param code         received from the bank
 * @param state        received from the bank - matches in styx database
 * @param error        received from the bank on error
 * @param errorMessage received from the bank on error
 * @param path         to be used as redirect url to styx
 * @return returns a jaxrs response object to be returned to a client
 */
public static Response handlePreStepOAuth2(String code, String state, String error, String errorMessage, String path) {
    OAuthSession oAuthSession = new OAuthSession();
    try {
        oAuthSession = PersistentOAuthSession.getByState(state);
    } catch (PersistenceEmptyResultSetException oauthSessionNotFound) {
        LOG.warn("Error retrieving oAuthSession within prestep callback error={}", oauthSessionNotFound.getMessage());
        error += " " + STYX_PREAUTH_NOT_AVAILABLE.name();
    }
    if (error == null && handleSuccessfulOAuth2(code, state, path)) {
        RedirectStatus redirectStatus = new RedirectStatus(StatusType.SUCCESS, oAuthSession.getState(), RedirectStep.PREAUTH);
        return StatusHelper.createStatusRedirection(redirectStatus);
    } else {
        LOG.error(FAILED_OAUTH2, error, errorMessage, state);
        RedirectStatus redirectStatus = new RedirectStatus(StatusType.ERROR, oAuthSession.getState(), RedirectStep.PREAUTH);
        return StatusHelper.createStatusRedirection(redirectStatus);
    }
}
Also used : RedirectStatus(net.petafuel.styx.api.v1.status.entity.RedirectStatus) PersistentOAuthSession(net.petafuel.styx.core.persistence.layers.PersistentOAuthSession) OAuthSession(net.petafuel.styx.core.xs2a.oauth.entities.OAuthSession) PersistenceEmptyResultSetException(net.petafuel.styx.core.persistence.PersistenceEmptyResultSetException)

Example 4 with PersistenceEmptyResultSetException

use of net.petafuel.styx.core.persistence.PersistenceEmptyResultSetException in project styx by petafuel.

the class PersistentAccessToken method get.

/**
 * @param accessToken this should be the hashed styx access token
 * @return accesstoken with metadata
 * @throws PersistenceException               if any sql error happened
 * @throws PersistenceEmptyResultSetException if there was no matching token found in the database
 */
public static AccessToken get(String accessToken) {
    Connection connection = Persistence.getInstance().getConnection();
    AccessToken model = new AccessToken();
    try (PreparedStatement query = connection.prepareStatement("SELECT * FROM get_token(?);")) {
        query.setString(1, accessToken);
        try (ResultSet resultSet = query.executeQuery()) {
            if (resultSet.next()) {
                model = dbToModel(resultSet);
            } else {
                throw new PersistenceEmptyResultSetException("No entry found matching the specified token");
            }
        }
    } catch (SQLException e) {
        logSQLError(e);
    }
    return model;
}
Also used : SQLException(java.sql.SQLException) AccessToken(net.petafuel.styx.core.persistence.models.AccessToken) PersistenceEmptyResultSetException(net.petafuel.styx.core.persistence.PersistenceEmptyResultSetException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement)

Example 5 with PersistenceEmptyResultSetException

use of net.petafuel.styx.core.persistence.PersistenceEmptyResultSetException in project styx by petafuel.

the class PreAuthResource method getPreStepAuthentication.

/**
 * @param preauthId this id should match a state column within the oauth_sessions table
 * @return a GetPreStepResponse Object which contains certain values from an OAuthSession object
 */
@GET
@CheckAccessToken(allowedServices = { XS2ATokenType.AIS, XS2ATokenType.PIS, XS2ATokenType.AISPIS, XS2ATokenType.PIIS })
@Path("/preauth/{preauthId}")
public Response getPreStepAuthentication(@NotBlank @PathParam("preauthId") String preauthId) {
    OAuthSession oAuthSession;
    try {
        oAuthSession = PersistentOAuthSession.getById(UUID.fromString(preauthId));
    } catch (PersistenceEmptyResultSetException unknownPreauth) {
        throw new StyxException(new ResponseEntity(ResponseConstant.STYX_PREAUTH_NOT_FOUND, ResponseCategory.ERROR, ResponseOrigin.CLIENT));
    }
    LOG.info("Successfully retrieved preauth from oauth_session state={}", oAuthSession.getState());
    return Response.status(ResponseConstant.OK).entity(new GetPreStepResponse(oAuthSession)).build();
}
Also used : ResponseEntity(net.petafuel.styx.api.exception.ResponseEntity) GetPreStepResponse(net.petafuel.styx.api.v1.preauth.entity.GetPreStepResponse) PersistentOAuthSession(net.petafuel.styx.core.persistence.layers.PersistentOAuthSession) OAuthSession(net.petafuel.styx.core.xs2a.oauth.entities.OAuthSession) PersistenceEmptyResultSetException(net.petafuel.styx.core.persistence.PersistenceEmptyResultSetException) StyxException(net.petafuel.styx.api.exception.StyxException) Path(javax.ws.rs.Path) ApplicationPath(javax.ws.rs.ApplicationPath) CheckAccessToken(net.petafuel.styx.api.filter.authentication.boundary.CheckAccessToken) GET(javax.ws.rs.GET)

Aggregations

PersistenceEmptyResultSetException (net.petafuel.styx.core.persistence.PersistenceEmptyResultSetException)5 ResponseEntity (net.petafuel.styx.api.exception.ResponseEntity)3 StyxException (net.petafuel.styx.api.exception.StyxException)3 PersistentOAuthSession (net.petafuel.styx.core.persistence.layers.PersistentOAuthSession)3 OAuthSession (net.petafuel.styx.core.xs2a.oauth.entities.OAuthSession)3 Date (java.util.Date)2 CheckAccessToken (net.petafuel.styx.api.filter.authentication.boundary.CheckAccessToken)2 AccessToken (net.petafuel.styx.core.persistence.models.AccessToken)2 Connection (java.sql.Connection)1 PreparedStatement (java.sql.PreparedStatement)1 ResultSet (java.sql.ResultSet)1 SQLException (java.sql.SQLException)1 HashMap (java.util.HashMap)1 UUID (java.util.UUID)1 ApplicationPath (javax.ws.rs.ApplicationPath)1 GET (javax.ws.rs.GET)1 Path (javax.ws.rs.Path)1 GetPreStepResponse (net.petafuel.styx.api.v1.preauth.entity.GetPreStepResponse)1 RedirectStatus (net.petafuel.styx.api.v1.status.entity.RedirectStatus)1 XS2AStandard (net.petafuel.styx.core.banklookup.XS2AStandard)1