Search in sources :

Example 1 with Policy

use of io.apiman.gateway.engine.beans.Policy in project apiman by apiman.

the class ActionResourceImpl method publishApi.

/**
 * Publishes an API to the gateway.
 * @param action
 */
private void publishApi(ActionBean action) throws ActionException, NotAuthorizedException {
    securityContext.checkPermissions(PermissionType.apiAdmin, action.getOrganizationId());
    ApiVersionBean versionBean;
    try {
        versionBean = orgs.getApiVersion(action.getOrganizationId(), action.getEntityId(), action.getEntityVersion());
    } catch (ApiVersionNotFoundException e) {
        // $NON-NLS-1$
        throw ExceptionFactory.actionException(Messages.i18n.format("ApiNotFound"));
    }
    // Validate that it's ok to perform this action - API must be Ready.
    if (!versionBean.isPublicAPI() && versionBean.getStatus() != ApiStatus.Ready) {
        // $NON-NLS-1$
        throw ExceptionFactory.actionException(Messages.i18n.format("InvalidApiStatus"));
    }
    if (versionBean.isPublicAPI()) {
        if (versionBean.getStatus() == ApiStatus.Retired || versionBean.getStatus() == ApiStatus.Created) {
            // $NON-NLS-1$
            throw ExceptionFactory.actionException(Messages.i18n.format("InvalidApiStatus"));
        }
        if (versionBean.getStatus() == ApiStatus.Published) {
            Date modOn = versionBean.getModifiedOn();
            Date publishedOn = versionBean.getPublishedOn();
            int c = modOn.compareTo(publishedOn);
            if (c <= 0) {
                // $NON-NLS-1$
                throw ExceptionFactory.actionException(Messages.i18n.format("ApiRePublishNotRequired"));
            }
        }
    }
    Api gatewayApi = new Api();
    gatewayApi.setEndpoint(versionBean.getEndpoint());
    gatewayApi.setEndpointType(versionBean.getEndpointType().toString());
    if (versionBean.getEndpointContentType() != null) {
        gatewayApi.setEndpointContentType(versionBean.getEndpointContentType().toString());
    }
    gatewayApi.setEndpointProperties(versionBean.getEndpointProperties());
    gatewayApi.setOrganizationId(versionBean.getApi().getOrganization().getId());
    gatewayApi.setApiId(versionBean.getApi().getId());
    gatewayApi.setVersion(versionBean.getVersion());
    gatewayApi.setPublicAPI(versionBean.isPublicAPI());
    gatewayApi.setParsePayload(versionBean.isParsePayload());
    gatewayApi.setKeysStrippingDisabled(versionBean.getDisableKeysStrip());
    boolean hasTx = false;
    try {
        if (versionBean.isPublicAPI()) {
            List<Policy> policiesToPublish = new ArrayList<>();
            List<PolicySummaryBean> apiPolicies = query.getPolicies(action.getOrganizationId(), action.getEntityId(), action.getEntityVersion(), PolicyType.Api);
            storage.beginTx();
            hasTx = true;
            for (PolicySummaryBean policySummaryBean : apiPolicies) {
                PolicyBean apiPolicy = storage.getPolicy(PolicyType.Api, action.getOrganizationId(), action.getEntityId(), action.getEntityVersion(), policySummaryBean.getId());
                Policy policyToPublish = new Policy();
                policyToPublish.setPolicyJsonConfig(apiPolicy.getConfiguration());
                policyToPublish.setPolicyImpl(apiPolicy.getDefinition().getPolicyImpl());
                policiesToPublish.add(policyToPublish);
            }
            gatewayApi.setApiPolicies(policiesToPublish);
        }
    } catch (StorageException e) {
        // $NON-NLS-1$
        throw ExceptionFactory.actionException(Messages.i18n.format("PublishError"), e);
    } finally {
        if (hasTx) {
            storage.rollbackTx();
        }
    }
    // Publish the API to all relevant gateways
    try {
        storage.beginTx();
        Set<ApiGatewayBean> gateways = versionBean.getGateways();
        if (gateways == null) {
            // $NON-NLS-1$
            throw new PublishingException("No gateways specified for API!");
        }
        for (ApiGatewayBean apiGatewayBean : gateways) {
            IGatewayLink gatewayLink = createGatewayLink(apiGatewayBean.getGatewayId());
            gatewayLink.publishApi(gatewayApi);
            gatewayLink.close();
        }
        versionBean.setStatus(ApiStatus.Published);
        versionBean.setPublishedOn(new Date());
        ApiBean api = storage.getApi(action.getOrganizationId(), action.getEntityId());
        if (api == null) {
            // $NON-NLS-1$ //$NON-NLS-2$
            throw new PublishingException("Error: could not find API - " + action.getOrganizationId() + "=>" + action.getEntityId());
        }
        if (api.getNumPublished() == null) {
            api.setNumPublished(1);
        } else {
            api.setNumPublished(api.getNumPublished() + 1);
        }
        storage.updateApi(api);
        storage.updateApiVersion(versionBean);
        storage.createAuditEntry(AuditUtils.apiPublished(versionBean, securityContext));
        storage.commitTx();
    } catch (PublishingException e) {
        storage.rollbackTx();
        // $NON-NLS-1$
        throw ExceptionFactory.actionException(Messages.i18n.format("PublishError"), e);
    } catch (Exception e) {
        storage.rollbackTx();
        // $NON-NLS-1$
        throw ExceptionFactory.actionException(Messages.i18n.format("PublishError"), e);
    }
    log.debug(// $NON-NLS-1$
    String.format(// $NON-NLS-1$
    "Successfully published API %s on specified gateways: %s", versionBean.getApi().getName(), versionBean.getApi()));
}
Also used : Policy(io.apiman.gateway.engine.beans.Policy) PolicySummaryBean(io.apiman.manager.api.beans.summary.PolicySummaryBean) PolicyBean(io.apiman.manager.api.beans.policies.PolicyBean) ArrayList(java.util.ArrayList) Date(java.util.Date) IGatewayLink(io.apiman.manager.api.gateway.IGatewayLink) ApiVersionNotFoundException(io.apiman.manager.api.rest.exceptions.ApiVersionNotFoundException) StorageException(io.apiman.manager.api.core.exceptions.StorageException) GatewayNotFoundException(io.apiman.manager.api.rest.exceptions.GatewayNotFoundException) NotAuthorizedException(io.apiman.manager.api.rest.exceptions.NotAuthorizedException) ActionException(io.apiman.manager.api.rest.exceptions.ActionException) PlanVersionNotFoundException(io.apiman.manager.api.rest.exceptions.PlanVersionNotFoundException) PublishingException(io.apiman.gateway.engine.beans.exceptions.PublishingException) ClientVersionNotFoundException(io.apiman.manager.api.rest.exceptions.ClientVersionNotFoundException) ApiVersionNotFoundException(io.apiman.manager.api.rest.exceptions.ApiVersionNotFoundException) ApiBean(io.apiman.manager.api.beans.apis.ApiBean) ApiGatewayBean(io.apiman.manager.api.beans.apis.ApiGatewayBean) PublishingException(io.apiman.gateway.engine.beans.exceptions.PublishingException) Api(io.apiman.gateway.engine.beans.Api) ApiVersionBean(io.apiman.manager.api.beans.apis.ApiVersionBean) StorageException(io.apiman.manager.api.core.exceptions.StorageException)

Example 2 with Policy

use of io.apiman.gateway.engine.beans.Policy in project apiman by apiman.

the class ApiRequestExecutorImpl method loadPolicies.

/**
 * Get/resolve the list of policies into a list of policies with config.  This operation is
 * done asynchronously so that plugins can be downloaded if needed.  Any errors in resolving
 * the policies will be reported back via the policyErrorHandler.
 */
private void loadPolicies(final IAsyncHandler<List<PolicyWithConfiguration>> handler) {
    final Set<Integer> totalCounter = new HashSet<>();
    final Set<Integer> errorCounter = new TreeSet<>();
    final List<PolicyWithConfiguration> rval = new ArrayList<>(policies.size());
    final List<Throwable> errors = new ArrayList<>(policies.size());
    final int numPolicies = policies.size();
    int index = 0;
    // If there aren't any policies, then no need to asynchronously load them!
    if (policies.isEmpty()) {
        handler.handle(policyImpls);
        return;
    }
    for (final Policy policy : policies) {
        rval.add(null);
        errors.add(null);
        final int localIdx = index++;
        policyFactory.loadPolicy(policy.getPolicyImpl(), (IAsyncResult<IPolicy> result) -> {
            if (result.isSuccess()) {
                IPolicy policyImpl = result.getResult();
                // Test whether pipeline contains any data policies. Connectors can use this for Content-Length pass-through.
                if (policyImpl instanceof IDataPolicy) {
                    hasDataPolicy = true;
                }
                try {
                    Object policyConfig = policyFactory.loadConfig(policyImpl, policy.getPolicyImpl(), policy.getPolicyJsonConfig());
                    PolicyWithConfiguration pwc = new PolicyWithConfiguration(policyImpl, policyConfig);
                    rval.set(localIdx, pwc);
                } catch (Throwable t) {
                    errors.set(localIdx, t);
                    errorCounter.add(localIdx);
                }
            } else {
                Throwable error = result.getError();
                errors.set(localIdx, error);
                errorCounter.add(localIdx);
            }
            totalCounter.add(localIdx);
            // Have we done them all?
            if (totalCounter.size() == numPolicies) {
                // the fully resolved list of policies.
                if (!errorCounter.isEmpty()) {
                    int errorIdx = errorCounter.iterator().next();
                    Throwable error = errors.get(errorIdx);
                    // TODO add some logging here to indicate which policy error'd out
                    // Policy errorPolicy = policies.get(errorIdx);
                    policyErrorHandler.handle(error);
                } else {
                    handler.handle(rval);
                }
            }
        });
    }
}
Also used : IDataPolicy(io.apiman.gateway.engine.policy.IDataPolicy) Policy(io.apiman.gateway.engine.beans.Policy) IPolicy(io.apiman.gateway.engine.policy.IPolicy) IPolicy(io.apiman.gateway.engine.policy.IPolicy) ArrayList(java.util.ArrayList) TreeSet(java.util.TreeSet) IDataPolicy(io.apiman.gateway.engine.policy.IDataPolicy) IAsyncResult(io.apiman.gateway.engine.async.IAsyncResult) PolicyWithConfiguration(io.apiman.gateway.engine.policy.PolicyWithConfiguration) HashSet(java.util.HashSet)

Example 3 with Policy

use of io.apiman.gateway.engine.beans.Policy in project apiman by apiman.

the class ContractService method aggregateContractPolicies.

/**
 * Aggregates the API, client, and plan policies into a single ordered list.
 */
public List<Policy> aggregateContractPolicies(ContractSummaryBean contractBean) {
    try {
        List<Policy> policies = new ArrayList<>();
        PolicyType[] types = new PolicyType[] { PolicyType.Client, PolicyType.Plan, PolicyType.Api };
        for (PolicyType policyType : types) {
            String org, id, ver;
            switch(policyType) {
                case Client:
                    {
                        org = contractBean.getClientOrganizationId();
                        id = contractBean.getClientId();
                        ver = contractBean.getClientVersion();
                        break;
                    }
                case Plan:
                    {
                        org = contractBean.getApiOrganizationId();
                        id = contractBean.getPlanId();
                        ver = contractBean.getPlanVersion();
                        break;
                    }
                case Api:
                    {
                        org = contractBean.getApiOrganizationId();
                        id = contractBean.getApiId();
                        ver = contractBean.getApiVersion();
                        break;
                    }
                default:
                    {
                        // $NON-NLS-1$
                        throw new RuntimeException("Missing case for switch!");
                    }
            }
            List<PolicySummaryBean> clientPolicies = query.getPolicies(org, id, ver, policyType);
            for (PolicySummaryBean policySummaryBean : clientPolicies) {
                PolicyBean policyBean = storage.getPolicy(policyType, org, id, ver, policySummaryBean.getId());
                Policy policy = new Policy();
                policy.setPolicyJsonConfig(policyBean.getConfiguration());
                policy.setPolicyImpl(policyBean.getDefinition().getPolicyImpl());
                policies.add(policy);
            }
        }
        return policies;
    } catch (Exception e) {
        throw ExceptionFactory.actionException(Messages.i18n.format("ErrorAggregatingPolicies", contractBean.getClientId() + "->" + contractBean.getApiDescription()), // $NON-NLS-1$ //$NON-NLS-2$
        e);
    }
}
Also used : Policy(io.apiman.gateway.engine.beans.Policy) PolicyType(io.apiman.manager.api.beans.policies.PolicyType) PolicySummaryBean(io.apiman.manager.api.beans.summary.PolicySummaryBean) PolicyBean(io.apiman.manager.api.beans.policies.PolicyBean) ArrayList(java.util.ArrayList) InvalidClientStatusException(io.apiman.manager.api.rest.exceptions.InvalidClientStatusException) StorageException(io.apiman.manager.api.core.exceptions.StorageException) SystemErrorException(io.apiman.manager.api.rest.exceptions.SystemErrorException) ContractNotFoundException(io.apiman.manager.api.rest.exceptions.ContractNotFoundException) NotAuthorizedException(io.apiman.manager.api.rest.exceptions.NotAuthorizedException) ClientNotFoundException(io.apiman.manager.api.rest.exceptions.ClientNotFoundException) GatewayAuthenticationException(io.apiman.manager.api.gateway.GatewayAuthenticationException) AbstractRestException(io.apiman.manager.api.rest.exceptions.AbstractRestException) PlanNotFoundException(io.apiman.manager.api.rest.exceptions.PlanNotFoundException) OrganizationNotFoundException(io.apiman.manager.api.rest.exceptions.OrganizationNotFoundException) ApiNotFoundException(io.apiman.manager.api.rest.exceptions.ApiNotFoundException) ContractAlreadyExistsException(io.apiman.manager.api.rest.exceptions.ContractAlreadyExistsException)

Example 4 with Policy

use of io.apiman.gateway.engine.beans.Policy in project apiman by apiman.

the class DefaultEngineFactoryTest method setup.

@Before
public void setup() {
    Policy policyBean = mock(Policy.class);
    given(policyBean.getPolicyImpl()).willReturn(PassthroughPolicy.QUALIFIED_NAME);
    given(policyBean.getPolicyJsonConfig()).willReturn("{}");
    mockBufferInbound = mock(IApimanBuffer.class);
    given(mockBufferInbound.toString()).willReturn("stottie");
    mockBufferOutbound = mock(IApimanBuffer.class);
    given(mockBufferOutbound.toString()).willReturn("bacon");
    policyList = new ArrayList<>();
    policyList.add(policyBean);
    mockBodyHandler = mock(IAsyncHandler.class);
    mockEndHandler = mock(IAsyncHandler.class);
}
Also used : PassthroughPolicy(io.apiman.gateway.engine.util.PassthroughPolicy) Policy(io.apiman.gateway.engine.beans.Policy) IApimanBuffer(io.apiman.gateway.engine.io.IApimanBuffer) IAsyncHandler(io.apiman.gateway.engine.async.IAsyncHandler) Before(org.junit.Before)

Example 5 with Policy

use of io.apiman.gateway.engine.beans.Policy in project apiman by apiman.

the class SecureRegistryWrapper method registerClient.

/**
 * @see io.apiman.gateway.engine.IRegistry#registerClient(io.apiman.gateway.engine.beans.Client, io.apiman.gateway.engine.async.IAsyncResultHandler)
 */
@Override
public void registerClient(Client client, IAsyncResultHandler<Void> handler) {
    Set<Contract> contracts = client.getContracts();
    if (contracts != null) {
        for (Contract contract : contracts) {
            List<Policy> policies = contract.getPolicies();
            encryptPolicies(client.getOrganizationId(), client.getClientId(), client.getVersion(), EntityType.ClientApp, policies);
        }
    }
    delegate.registerClient(client, handler);
    if (contracts != null) {
        for (Contract contract : contracts) {
            List<Policy> policies = contract.getPolicies();
            decryptPolicies(client.getOrganizationId(), client.getClientId(), client.getVersion(), EntityType.ClientApp, policies);
        }
    }
}
Also used : Policy(io.apiman.gateway.engine.beans.Policy) Contract(io.apiman.gateway.engine.beans.Contract) ApiContract(io.apiman.gateway.engine.beans.ApiContract)

Aggregations

Policy (io.apiman.gateway.engine.beans.Policy)17 IPolicy (io.apiman.gateway.engine.policy.IPolicy)7 ArrayList (java.util.ArrayList)7 Api (io.apiman.gateway.engine.beans.Api)6 PolicyBean (io.apiman.manager.api.beans.policies.PolicyBean)6 StorageException (io.apiman.manager.api.core.exceptions.StorageException)5 IPolicyProbeResponse (io.apiman.gateway.engine.beans.IPolicyProbeResponse)4 PublishingException (io.apiman.gateway.engine.beans.exceptions.PublishingException)4 IPolicyFactory (io.apiman.gateway.engine.policy.IPolicyFactory)4 IPolicyProbe (io.apiman.gateway.engine.policy.IPolicyProbe)4 PolicyContextImpl (io.apiman.gateway.engine.policy.PolicyContextImpl)4 ProbeContext (io.apiman.gateway.engine.policy.ProbeContext)4 PolicySummaryBean (io.apiman.manager.api.beans.summary.PolicySummaryBean)4 NotAuthorizedException (io.apiman.manager.api.rest.exceptions.NotAuthorizedException)4 ApiGatewayBean (io.apiman.manager.api.beans.apis.ApiGatewayBean)3 ApiVersionBean (io.apiman.manager.api.beans.apis.ApiVersionBean)3 PolicyType (io.apiman.manager.api.beans.policies.PolicyType)3 IGatewayLink (io.apiman.manager.api.gateway.IGatewayLink)3 ActionException (io.apiman.manager.api.rest.exceptions.ActionException)3 ApiVersionNotFoundException (io.apiman.manager.api.rest.exceptions.ApiVersionNotFoundException)3