/** * Builds a cached request id composed by the API key followed by the HTTP * verb and the destination. In the case where there's no API key the ID * will contain ApiOrgId + ApiId + ApiVersion */ private static String buildCacheID(ApiRequest request) { StringBuilder req = new StringBuilder(); if (request.getContract() != null) { req.append(request.getApiKey()); } else { req.append(request.getApiOrgId()).append(KEY_SEPARATOR).append(request.getApiId()) .append(KEY_SEPARATOR).append(request.getApiVersion()); } req.append(KEY_SEPARATOR).append(request.getType()).append(KEY_SEPARATOR) .append(request.getDestination()); return req.toString(); }
/** * @return the thread-local api request */ public static final ApiRequest getApiRequest() { ApiRequest request = apiRequest.get(); if (request == null) { request = new ApiRequest(); apiRequest.set(request); } request.setApiKey(null); request.setUrl(null); request.setDestination(null); request.getHeaders().clear(); request.setRawRequest(null); request.setRemoteAddr(null); request.setType(null); request.setTransportSecure(false); return request; }
public static ApiRequest buildRequest(HttpServerRequest req, boolean isTransportSecure) { ApiRequest apimanRequest = new ApiRequest(); apimanRequest.setApiKey(parseApiKey(req)); apimanRequest.setRemoteAddr(req.remoteAddress().host()); apimanRequest.setType(req.method().toString()); apimanRequest.setTransportSecure(isTransportSecure); multimapToMap(apimanRequest.getHeaders(), req.headers(), IGNORESET); multimapToMap(apimanRequest.getQueryParams(), req.params(), Collections.<String>emptySet()); parsePath(req, apimanRequest); return apimanRequest; }
/** * @return an API request */ public ApiRequest createApiRequest() { ApiRequest request = new ApiRequest(); request.setApiOrgId(orgId); request.setApiId(apiId); request.setApiVersion(String.valueOf(version)); request.setTransportSecure(true); return request; }
/** * Checks the API unique identifier against what this contract expects (org id, id, version). * Returns true if they match. * @param request the request * @return true if the given request matches this contract */ public boolean matches(ApiRequest request) { String apiOrgId = request.getApiOrgId(); String apiId = request.getApiId(); String apiVersion = request.getApiVersion(); return matches(apiOrgId, apiId, apiVersion); }
/** * Reads a {@link ApiRequest} from information found in the inbound * portion of the http request. * @param request the undertow http server request * @return a valid {@link ApiRequest} * @throws IOException */ protected ApiRequest readRequest(HttpServletRequest request) throws Exception { ApiRequestPathInfo pathInfo = getEngine().getApiRequestPathParser().parseEndpoint(request.getPathInfo(), wrapMultiMap(request));//parseApiRequestPath(request); if (pathInfo.orgId == null) { throw new Exception(Messages.i18n.format("GatewayServlet.InvalidApiEndpoint")); //$NON-NLS-1$ } QueryMap queryParams = parseApiRequestQueryParams(request.getQueryString()); String apiKey = getApiKey(request, queryParams); ApiRequest srequest = GatewayThreadContext.getApiRequest(); srequest.setApiKey(apiKey); srequest.setApiOrgId(pathInfo.orgId); srequest.setApiId(pathInfo.apiId); srequest.setApiVersion(pathInfo.apiVersion); srequest.setUrl(request.getRequestURL().toString()); srequest.setDestination(pathInfo.resource); srequest.setQueryParams(queryParams); readHeaders(srequest, request); srequest.setRawRequest(request); srequest.setRemoteAddr(request.getRemoteAddr()); srequest.setTransportSecure(request.isSecure()); return srequest; }
requestMetric.setUrl(request.getUrl()); requestMetric.setResource(request.getDestination()); requestMetric.setMethod(request.getType()); requestMetric.setApiOrgId(request.getApiOrgId()); requestMetric.setApiId(request.getApiId()); requestMetric.setApiVersion(request.getApiVersion()); if (request.getApiKey() == null) { registry.getApi(request.getApiOrgId(), request.getApiId(), request.getApiVersion(), (IAsyncResult<Api> apiResult) -> { if (apiResult.isSuccess()) { request.setApi(api); policies = api.getApiPolicies(); policyImpls = new ArrayList<>(policies.size()); String apiOrgId = request.getApiOrgId(); String apiId = request.getApiId(); String apiVersion = request.getApiVersion(); String apiKey = request.getApiKey(); registry.getContract(apiOrgId, apiId, apiVersion, apiKey, (IAsyncResult<ApiContract> contractResult) -> { if (contractResult.isSuccess()) { requestMetric.setClientVersion(apiContract.getClient().getVersion()); requestMetric.setPlanId(apiContract.getPlan()); requestMetric.setContractId(request.getApiKey()); request.setContract(apiContract); request.setApi(api);
String endpoint = ApimanPathUtils.join(api.getEndpoint(), request.getDestination()); if (request.getQueryParams() != null && !request.getQueryParams().isEmpty()) { String delim = "?"; //$NON-NLS-1$ for (Entry<String, String> entry : request.getQueryParams()) { endpoint += delim + entry.getKey(); if (entry.getValue() != null) { if (request.getType().equalsIgnoreCase("PUT") || request.getType().equalsIgnoreCase("POST")) { //$NON-NLS-1$ //$NON-NLS-2$ connection.setDoOutput(true); } else { connection.setRequestMethod(request.getType()); for (Entry<String, String> entry : request.getHeaders()) { String hkey = entry.getKey(); String hval = entry.getValue();
srequest.setUrl("http://localhost:8080" + ptRequest.resource()); //$NON-NLS-1$ srequest.setDestination(ptRequest.resource()); srequest.setType(ptRequest.method().name()); srequest.getHeaders().putAll(ptRequest.headers()); srequest.getQueryParams().putAll(ptRequest.queryParams());
if (request.getContract() == null) { builder.append("PUBLIC||"); //$NON-NLS-1$ builder.append("||"); //$NON-NLS-1$ builder.append(request.getApiOrgId()); builder.append("||"); //$NON-NLS-1$ builder.append(request.getApiId()); builder.append("||"); //$NON-NLS-1$ builder.append(request.getApiVersion()); if (config.getGranularity() == RateLimitingGranularity.User) { String header = config.getUserHeader(); if (!request.getHeaders().containsKey(header)) { return NO_USER_AVAILABLE; String user = request.getHeaders().get(header); builder.append("||"); //$NON-NLS-1$ builder.append(user); } else if (config.getGranularity() == RateLimitingGranularity.Ip) { builder.append("||"); //$NON-NLS-1$ builder.append(request.getRemoteAddr()); } else if (config.getGranularity() == RateLimitingGranularity.Api) { } else { builder.append(request.getApiKey()); if (config.getGranularity() == RateLimitingGranularity.User) { String header = config.getUserHeader(); String user = request.getHeaders().get(header); if (user == null) { return NO_USER_AVAILABLE; } else {
echoResponse.setHeaders(request.getHeaders()); echoResponse.setMethod(request.getType()); echoResponse.setResource(request.getDestination()); echoResponse.setUri("urn:" + request.getDestination()); String errorCode = request.getHeaders().get("X-Echo-ErrorCode"); if (errorCode != null) { int ec = new Integer(errorCode); String errorMsg = request.getHeaders().get("X-Echo-ErrorMessage"); apiResponse.setCode(ec); apiResponse.setMessage(errorMsg);
private static void parsePath(HttpServerRequest request, ApiRequest apimanRequest) { // NB: The apiman version of the headers has already been parsed, so the headers have already been filtered/modified. // Therefore we wrap the original inbound headers (just get) to efficiently access the necessary data. ApiRequestPathInfo parsedPath = requestPathParser.parseEndpoint(request.path(), wrapMultiMap(request.headers())); apimanRequest.setApiOrgId(parsedPath.orgId); apimanRequest.setApiId(parsedPath.apiId); apimanRequest.setApiVersion(parsedPath.apiVersion); apimanRequest.setUrl(request.absoluteURI()); apimanRequest.setDestination(parsedPath.resource); }
/** * @see io.apiman.gateway.engine.policies.AbstractMappedPolicy#doApply(io.apiman.gateway.engine.beans.ApiRequest, io.apiman.gateway.engine.policy.IPolicyContext, java.lang.Object, io.apiman.gateway.engine.policy.IPolicyChain) */ @Override protected void doApply(ApiRequest request, IPolicyContext context, URLRewritingConfig config, IPolicyChain<ApiRequest> chain) { if (config.isProcessRequestUrl()) { request.setDestination(request.getDestination().replaceAll(config.getFromRegex(), config.getToReplacement())); } if (config.isProcessRequestHeaders()) { replaceHeaders(config, request.getHeaders()); } super.doApply(request, context, config, chain); }
/** * Validates that the contract being used for the request is valid against the * api information included in the request. Basically the request includes * information indicating which specific api is being invoked. This method * ensures that the api information in the contract matches the requested * api. * @param request the request to validate */ protected void validateRequest(ApiRequest request) throws InvalidContractException { ApiContract contract = request.getContract(); boolean matches = true; if (!contract.getApi().getOrganizationId().equals(request.getApiOrgId())) { matches = false; } if (!contract.getApi().getApiId().equals(request.getApiId())) { matches = false; } if (!contract.getApi().getVersion().equals(request.getApiVersion())) { matches = false; } if (!matches) { throw new InvalidContractException(Messages.i18n.format("EngineImpl.InvalidContractForApi", //$NON-NLS-1$ request.getApiOrgId(), request.getApiId(), request.getApiVersion())); } }
public HttpConnector connect() { String endpoint = ApimanPathUtils.join(apiPath, destination + queryParams(apiRequest.getQueryParams())); logger.debug("Connecting to {0} | ssl?: {1} port: {2} verb: {3} path: {4}", apiHost, options.isSsl(), apiPort, HttpMethod.valueOf(apiRequest.getType()), endpoint); clientRequest = client.request(HttpMethod.valueOf(apiRequest.getType()), apiPort, apiHost, if (options.hasDataPolicy() || !apiRequest.getHeaders().containsKey("Content-Length")) { clientRequest.headers().remove("Content-Length"); clientRequest.setChunked(true); apiRequest.getHeaders() .forEach(e -> { if (!connectorConfig.getSuppressedRequestHeaders().contains(e.getKey())) {
/** * @see io.apiman.gateway.engine.policies.AbstractMappedPolicy#doApply(io.apiman.gateway.engine.beans.ApiRequest, * io.apiman.gateway.engine.policy.IPolicyContext, java.lang.Object, * io.apiman.gateway.engine.policy.IPolicyChain) */ @Override protected void doApply(ApiRequest request, IPolicyContext context, IgnoredResourcesConfig config, IPolicyChain<ApiRequest> chain) { if (!satisfiesAnyPath(config, request.getDestination(), request.getType())) { super.doApply(request, context, config, chain); } else { IPolicyFailureFactoryComponent ffactory = context .getComponent(IPolicyFailureFactoryComponent.class); String msg = Messages.i18n.format("IgnoredResourcesPolicy.PathIgnored", //$NON-NLS-1$ request.getDestination()); PolicyFailure failure = ffactory.createFailure(PolicyFailureType.NotFound, PolicyFailureCodes.PATHS_TO_IGNORE, msg); chain.doFailure(failure); } }
/** * Strips the API key from the request (both the http headers and the query params). */ private void stripApiKey() { request.getHeaders().remove("X-API-Key"); //$NON-NLS-1$ request.getQueryParams().remove("apikey"); //$NON-NLS-1$ }
/** * Reads the inbound request headers from the request and sets them on * the {@link ApiRequest}. * @param request * @param request */ protected void readHeaders(ApiRequest srequest, HttpServletRequest request) { Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String hname = headerNames.nextElement(); Enumeration<String> headerValues = request.getHeaders(hname); while (headerValues.hasMoreElements()) { String hval = headerValues.nextElement(); if (hname != null && hname.equalsIgnoreCase("accept") && hval != null && hval.startsWith("application/apiman.")) { //$NON-NLS-1$ //$NON-NLS-2$ if (hval.contains("+json")) { //$NON-NLS-1$ hval = "application/json"; //$NON-NLS-1$ } else if (hval.contains("+xml")) { //$NON-NLS-1$ hval = "text/xml"; //$NON-NLS-1$ } } if (hname != null && hname.equalsIgnoreCase("X-API-Version")) { //$NON-NLS-1$ continue; } srequest.getHeaders().add(hname, hval); } } }
/** * Gets the remote address for comparison. * @param request the request * @param config the config */ protected String getRemoteAddr(ApiRequest request, IPListConfig config) { String httpHeader = config.getHttpHeader(); if (httpHeader != null && httpHeader.trim().length() > 0) { String value = (String) request.getHeaders().get(httpHeader); if (value != null) { return value; } } return request.getRemoteAddr(); }
/** * Construct an {@link HttpConnector} instance. The {@link #resultHandler} must remain exclusive to a * given instance. * * @param vertx a vertx * @param client the vertx http client * @param api an API * @param request a request with fields filled * @param options the connector options * @param connectorConfig the dynamic connector configuration as possibly modified by policies * @param resultHandler a handler, called when reading is permitted */ public HttpConnector(Vertx vertx, HttpClient client, ApiRequest request, Api api, ApimanHttpConnectorOptions options, IConnectorConfig connectorConfig, IAsyncResultHandler<IApiConnectionResponse> resultHandler) { this.client = client; this.api = api; this.apiRequest = request; this.connectorConfig = connectorConfig; this.resultHandler = resultHandler; this.exceptionHandler = new ExceptionHandler(); this.apiEndpoint = options.getUri(); this.options = options; apiHost = apiEndpoint.getHost(); apiPort = getPort(); apiPath = apiEndpoint.getPath().isEmpty() || apiEndpoint.getPath().equals("/") ? "" : apiEndpoint.getPath(); destination = apiRequest.getDestination() == null ? "" : apiRequest.getDestination(); verifyConnection(); }