Skip to content
Merged
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
18 changes: 14 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -445,9 +445,11 @@ In case that you want to use an integrator or mock server, you can specify your
final CustomEnvironment environment = CustomEnvironment.builder()
.checkoutApi(create("https://the.base.uri/")) // the uri for all Checkout operations
.oAuthAuthorizationApi(create("https://the.oauth.uri/connect/token")) // the uri used for OAUTH authorization, only required for OAuth operations
.filesApi(create("https://the.files.uri/")) // the uri used for Files operations, only required for Accounts module
.transfersApi(create("https://the.transfers.uri/")) // the uri used for Transfer operations, only required for Transfers module
.balancesApi(create("https://the.balances.uri/")) // the uri used for Balances operations, only required for Balances module
.filesApi(create("https://the.files.uri/")) // the uri used for Files operations (Accounts module)
.transfersApi(create("https://the.transfers.uri/")) // the uri used for Transfers operations
.balancesApi(create("https://the.balances.uri/")) // the uri used for Balances operations
.forwardApi(create("https://the.forward.uri/")) // the uri used for Forward operations
.identityApi(create("https://the.identity.uri/")) // the uri used for Identity operations
.sandbox(false) // flag to determine if Sanbox or Production configured, default false
.build();

Expand All @@ -459,7 +461,15 @@ final CheckoutApi checkoutApi = CheckoutSdk.builder()
.build();
```

You don't need to specify all the previous URI's, only the ones for the modules that you're going to use.
The SDK creates a client for every module when it is built, so set `checkoutApi`, `filesApi`, `transfersApi`,
`balancesApi`, `forwardApi` and `identityApi`, also for the modules you do not call; `oAuthAuthorizationApi` is only
needed for OAuth. Each of the six API settings must be an absolute `http` or `https` URI with an ASCII host written
without percent-encoding, an optional port from 1 to 65535 and no user information, and its path must not hold dot
segments, encoded separators or encoded control characters; a query or fragment on it is not sent. Set
`oAuthAuthorizationApi` to the absolute `https` token URI of your environment. With `environmentSubdomain`, the hosts of `checkoutApi` and `oAuthAuthorizationApi` must be
domain names (ASCII letters, digits, `-` and `_`), not IP addresses. Request paths are resolved against the base directory (the path
up to the last `/`), which is kept: end the URI with `/` when it has a path, otherwise its last segment is replaced. A
missing or invalid URI fails `build()` with a `CheckoutArgumentException` that names the setting.

## Custom HttpClient

Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/checkout/AbstractCheckoutApmApi.java
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public SepaClient sepaClient() {

private ApiClient getBaseApiClient(final CheckoutConfiguration configuration) {

return new ApiClientImpl(configuration, new BaseUriStrategy(configuration));
return new ApiClientImpl(configuration, new BaseUriStrategy(configuration), "checkoutApi");
}

private static class BaseUriStrategy implements UriStrategy {
Expand Down
26 changes: 17 additions & 9 deletions src/main/java/com/checkout/AbstractClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ public abstract class AbstractClient {

private static final char[] HEX = "0123456789ABCDEF".toCharArray();
private static final String INVALID_PATH_PARAMETER =
"Invalid path parameter: it must be valid text, not null, empty, '.' or '..'";
"Invalid path parameter: it must be valid text, not null, empty, '.' or '..', "
+ "and must not contain '/', '\\' or ASCII control characters";

protected final ApiClient apiClient;
protected final CheckoutConfiguration configuration;
Expand Down Expand Up @@ -37,8 +38,9 @@ protected SdkAuthorization sdkAuthorization() {
*
* @param pathParams the path segments, in order
* @return the request path, relative to the base URI
* @throws CheckoutArgumentException if a parameter is null, empty, "." or "..", or is not valid
* UTF-16 text (an unpaired surrogate)
* @throws CheckoutArgumentException if a parameter is null, empty, "." or "..", contains "/", {@code \}
* or an ASCII control character (U+0000 to U+001F, U+007F), or is not
* valid UTF-16 text (an unpaired surrogate)
*/
protected static String buildPath(final String... pathParams) {
final StringBuilder path = new StringBuilder();
Expand All @@ -53,17 +55,18 @@ protected static String buildPath(final String... pathParams) {

/**
* Percent-encodes a path parameter as UTF-8, keeping only the RFC 3986 unreserved characters
* (letters, digits, "-", ".", "_" and "~"), so the result is exactly one path segment.
* (letters, digits, "-", ".", "_" and "~"), so the result is exactly one path segment. "/",
* {@code \} and ASCII control characters are refused rather than encoded.
*/
private static String encodePathSegment(final String pathParam) {
if (pathParam == null || pathParam.isEmpty() || ".".equals(pathParam) || "..".equals(pathParam)
|| hasUnpairedSurrogate(pathParam)) {
|| hasForbiddenCharacter(pathParam) || hasUnpairedSurrogate(pathParam)) {
throw new CheckoutArgumentException(INVALID_PATH_PARAMETER);
}
final StringBuilder encoded = new StringBuilder(pathParam.length());
for (final byte b : pathParam.getBytes(StandardCharsets.UTF_8)) {
final int c = b & 0xFF;
if (isUnreserved(c)) {
if (UriCharacters.isUnreserved(c)) {
encoded.append((char) c);
} else {
encoded.append('%').append(HEX[c >> 4]).append(HEX[c & 0x0F]);
Expand All @@ -72,9 +75,14 @@ private static String encodePathSegment(final String pathParam) {
return encoded.toString();
}

private static boolean isUnreserved(final int c) {
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')
|| c == '-' || c == '.' || c == '_' || c == '~';
private static boolean hasForbiddenCharacter(final String value) {
for (int i = 0; i < value.length(); i++) {
final char c = value.charAt(i);
if (c == '/' || c == '\\' || c <= 0x1F || c == 0x7F) {
return true;
}
}
return false;
}

private static boolean hasUnpairedSurrogate(final String value) {
Expand Down
67 changes: 38 additions & 29 deletions src/main/java/com/checkout/ApacheHttpClientTransport.java
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@
import java.util.concurrent.Executor;
import java.util.stream.Collectors;
import java.util.function.Supplier;
import java.util.regex.Pattern;
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
import io.github.resilience4j.ratelimiter.RateLimiter;
import io.github.resilience4j.retry.Retry;
Expand All @@ -64,9 +63,9 @@ class ApacheHttpClientTransport implements Transport {
private static final String PURPOSE = "purpose";
private static final String PATH = "path";
private static final String INVALID_REQUEST_PATH = "Invalid request path";
private static final Pattern ENCODED_QUERY = Pattern.compile("[A-Za-z0-9._~*+%=&-]+");

private final URI baseUri;
private final String baseDirectory;
private final CloseableHttpClient httpClient;
private final Executor executor;
private final TransportConfiguration transportConfiguration;
Expand All @@ -75,15 +74,27 @@ class ApacheHttpClientTransport implements Transport {

private static final ThreadLocal<RequestMetrics> telemetryData = ThreadLocal.withInitial(RequestMetrics::new);

/**
* @param baseUri the base URI every request path is resolved against
* @param baseUriSetting the name of the setting the base URI comes from ("filesApi"), used in
* errors instead of the value
* @param httpClientBuilder the HTTP client builder
* @param executor the executor for asynchronous calls
* @param transportConfiguration the transport configuration
* @param configuration the SDK configuration
* @throws CheckoutArgumentException if the base URI is missing or invalid (see {@link BaseUri#normalise})
*/
ApacheHttpClientTransport(
final URI baseUri,
final String baseUriSetting,
final HttpClientBuilder httpClientBuilder,
final Executor executor,
final TransportConfiguration transportConfiguration,
final CheckoutConfiguration configuration
) {
CheckoutUtils.validateParams("baseUri", baseUri, "httpClientBuilder", httpClientBuilder, "executor", executor);
this.baseUri = withRootPath(baseUri);
CheckoutUtils.validateParams(baseUriSetting, baseUri, "httpClientBuilder", httpClientBuilder, "executor", executor);
this.baseUri = BaseUri.normalise(baseUri, baseUriSetting);
this.baseDirectory = directoryOf(this.baseUri);
this.httpClient = httpClientBuilder
.setRedirectStrategy(new CustomAwsRedirectStrategy())
.build();
Expand Down Expand Up @@ -386,16 +397,19 @@ private HttpUriRequest buildRequest(final ClientOperation clientOperation, final

/**
* Resolves a request path against the base URI. The path must be relative and made of non-empty
* segments, none of them "." or ".." (also when percent-encoded or followed by ";"). It may end with
* an already encoded query ("?name=value&amp;..." made only of unreserved characters, "%", "+", "="
* and "&amp;"), and never with a "#". The resolved URL must keep the scheme, host, port and base path
* of the base URI.
* segments of unreserved characters and "%XX" escapes, none of them "." or ".." (also when
* percent-encoded) and none containing an encoded "/", {@code \} or ASCII control character. It may
* end with an already encoded query ("?name=value&amp;..." made only of unreserved characters, "*",
* "+", "=", "&amp;" and "%" followed by two hex digits), and never with a "#". The resolved URL keeps
* the scheme and authority of the base URI, and its base directory (the path up to the last "/") is
* kept: a base URI without a trailing slash has its last path segment replaced, as
* {@link URI#resolve(String)} (RFC 3986) defines.
*
* @param path the request path, as built by {@code AbstractClient.buildPath}
* @return the absolute request URL
* @throws CheckoutArgumentException if the path is invalid or resolves outside the base URI
*/
String getRequestUrl(final String path) {
private String getRequestUrl(final String path) {
validateRequestPath(path);
final URI resolved = baseUri.resolve(path);
if (!isUnderBaseUri(resolved)) {
Expand All @@ -409,47 +423,42 @@ String getRequestUrl(final String path) {
}

/**
* A base URI with no path ("https://api.example.com") resolves "payments" to the host
* "api.example.compayments"; the root path "/" keeps the request on the configured host.
* The base directory (the path up to the last "/") that {@link URI#resolve(String)} keeps, read from a resolved probe so it
* matches resolve exactly (it drops the last segment and collapses empty ones). Used only by the
* defence-in-depth check in {@link #isUnderBaseUri(URI)}.
*/
private static URI withRootPath(final URI baseUri) {
final String path = baseUri.getRawPath();
return baseUri.isAbsolute() && !baseUri.isOpaque() && (path == null || path.isEmpty()) ? baseUri.resolve("/") : baseUri;
private static String directoryOf(final URI baseUri) {
final String probe = baseUri.resolve("probe").getRawPath();
return probe.substring(0, probe.length() - "probe".length());
}

private static void validateRequestPath(final String path) {
if (path == null || path.isEmpty() || path.indexOf('#') >= 0) {
throw new CheckoutArgumentException(INVALID_REQUEST_PATH);
}
final int queryStart = path.indexOf('?');
if (queryStart >= 0 && !ENCODED_QUERY.matcher(path.substring(queryStart + 1)).matches()) {
if (queryStart >= 0 && !UriCharacters.isPercentEncoded(path.substring(queryStart + 1), UriCharacters.QUERY_EXTRA)) {
throw new CheckoutArgumentException(INVALID_REQUEST_PATH);
}
final String pathOnly = queryStart >= 0 ? path.substring(0, queryStart) : path;
for (final String segment : pathOnly.split("/", -1)) {
if (isEmptyOrDotSegment(segment)) {
if (segment.isEmpty() || UriCharacters.isDotSegment(segment) || !UriCharacters.isPercentEncoded(segment, "")
|| UriCharacters.hasEncodedSeparatorOrControl(segment)) {
throw new CheckoutArgumentException(INVALID_REQUEST_PATH);
}
}
}

private static boolean isEmptyOrDotSegment(final String segment) {
final int parameters = segment.indexOf(';');
final String name = (parameters >= 0 ? segment.substring(0, parameters) : segment).replaceAll("(?i)%2e", ".");
return name.isEmpty() || ".".equals(name) || "..".equals(name);
}

/**
* True when the URL has the scheme, host and port of the base URI and a path under the base URI's
* directory, the part of its path that {@link URI#resolve(String)} keeps.
* True when the URL has the scheme and authority of the base URI and a path under the base URI's
* directory. The raw authority is compared because {@link URI#getHost()} is null for host names
* that are not valid DNS names, such as those with "_". Defence in depth: a path that passed
* {@link #validateRequestPath(String)} always resolves under the base URI, so this check is not
* expected to fail; it guards against a change to either rule.
*/
private boolean isUnderBaseUri(final URI resolved) {
final String basePath = baseUri.getRawPath() == null ? "" : baseUri.getRawPath();
final String baseDirectory = basePath.substring(0, basePath.lastIndexOf('/') + 1);
return baseUri.getScheme().equalsIgnoreCase(resolved.getScheme())
&& baseUri.getHost() != null
&& baseUri.getHost().equalsIgnoreCase(resolved.getHost())
&& baseUri.getPort() == resolved.getPort()
&& baseUri.getRawAuthority().equalsIgnoreCase(resolved.getRawAuthority())
&& resolved.getRawPath() != null
&& resolved.getRawPath().startsWith(baseDirectory)
&& resolved.getRawFragment() == null;
Expand Down
18 changes: 17 additions & 1 deletion src/main/java/com/checkout/ApiClientImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,27 @@ public class ApiClientImpl implements ApiClient {
private final CheckoutConfiguration configuration;
private final java.util.concurrent.Executor executor;

/**
* Creates an API client for the base URI the strategy returns.
*
* @param configuration the SDK configuration
* @param uriStrategy the strategy returning the base URI
* @throws CheckoutArgumentException if the base URI is missing or invalid; the error names
* "uriStrategy", never the URI
*/
public ApiClientImpl(final CheckoutConfiguration configuration, final UriStrategy uriStrategy) {
this(configuration, uriStrategy, "uriStrategy");
}

/**
* Creates an API client for the base URI the strategy returns, naming the setting it comes from in
* errors ("filesApi") instead of the URI.
*/
ApiClientImpl(final CheckoutConfiguration configuration, final UriStrategy uriStrategy, final String baseUriSetting) {
this.serializer = new GsonSerializer();
this.configuration = configuration;
this.executor = configuration.getExecutor();
this.transport = new ApacheHttpClientTransport(uriStrategy.getUri(), configuration.getHttpClientBuilder(), configuration.getExecutor(), configuration.getTransportConfiguration(), configuration);
this.transport = new ApacheHttpClientTransport(uriStrategy.getUri(), baseUriSetting, configuration.getHttpClientBuilder(), configuration.getExecutor(), configuration.getTransportConfiguration(), configuration);
}

@Override
Expand Down
Loading
Loading