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
7 changes: 5 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -466,8 +466,11 @@ The SDK creates a client for every module when it is built, so set `checkoutApi`
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
`oAuthAuthorizationApi` to the absolute `https` token URI of your environment, with an ASCII host written without
percent-encoding, no user information and an optional port from 1 to 65535; a local mock server can use `http` on
`localhost`, `127.0.0.0/8` or `[::1]` only, and any other `http` URI throws `CheckoutArgumentException` when the SDK is
built. 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.

Expand Down
111 changes: 109 additions & 2 deletions src/main/java/com/checkout/ApacheHttpClientTransport.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,18 @@
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.ByteArrayOutputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
Expand All @@ -54,6 +60,10 @@
import static org.apache.http.HttpHeaders.CONTENT_TYPE;
import static org.apache.http.HttpHeaders.USER_AGENT;

/**
* The Apache HttpClient transport: builds and sends every API request with the SDK headers, retries and telemetry,
* and logs each request and response.
*/
@Slf4j
class ApacheHttpClientTransport implements Transport {

Expand All @@ -63,6 +73,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 int MAX_DECODING_ROUNDS = 3;
private static final Set<String> LOGGED_RESPONSE_HEADERS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
"cko-request-id", "cko-version", "content-type", "content-length", "date")));

private final URI baseUri;
private final String baseDirectory;
Expand Down Expand Up @@ -227,12 +240,16 @@ private Response performCall(final SdkAuthorization authorization,
return performCall(authorization, requestBody, request, clientOperation, null);
}

/**
* Sends the request and logs the operation with its path and the response status with the allowlisted response
* headers.
*/
private Response performCall(final SdkAuthorization authorization,
final Object requestBody,
final HttpUriRequest request,
final ClientOperation clientOperation,
final IHeaders customHeaders) {
log.info("{}: {}", clientOperation, request.getURI());
log.info("{}: {}", clientOperation, loggablePath(request.getURI().getRawPath()));
request.setHeader(USER_AGENT, PROJECT_NAME + "/" + getVersionFromManifest());
request.setHeader(ACCEPT, getAcceptHeader(clientOperation));
request.setHeader(AUTHORIZATION, authorization.getAuthorizationHeader());
Expand Down Expand Up @@ -268,7 +285,8 @@ private Response performCall(final SdkAuthorization authorization,

try (final CloseableHttpResponse response = httpClient.execute(request)) {
long elapsed = System.currentTimeMillis() - startTime;
log.info("Response: " + response.getStatusLine().getStatusCode() + " " + Arrays.toString(response.getAllHeaders()));
log.info("Response: " + response.getStatusLine().getStatusCode() + " "
+ escapeForLog(Arrays.toString(loggableResponseHeaders(response.getAllHeaders()))));

updateTelemetryData(currentRequestId, elapsed);

Expand Down Expand Up @@ -341,6 +359,95 @@ private Header[] sanitiseHeaders(final Header[] headers) {
.toArray(Header[]::new);
}

/**
* The request path written to the log: path segments that hold an at sign, as an email address does ("@", also
* percent-encoded once or more, or its full-width or small form), are masked, and control characters, Unicode
* format characters and line or paragraph separators are percent-encoded.
*/
static String loggablePath(final String rawPath) {
if (rawPath == null || rawPath.isEmpty()) {
return rawPath;
}
final String[] segments = rawPath.split("/", -1);
for (int i = 0; i < segments.length; i++) {
if (holdsAtSign(segments[i])) {
segments[i] = "***";
}
}
return escapeForLog(String.join("/", segments));
}

/**
* Whether the segment, decoded up to {@value #MAX_DECODING_ROUNDS} times, contains an at sign ("@", full-width or
* small form). A segment that still changes after the last decoding is treated as holding one.
*/
private static boolean holdsAtSign(final String segment) {
String value = segment;
for (int round = 0; round <= MAX_DECODING_ROUNDS; round++) {
if (value.indexOf('@') >= 0 || value.indexOf('\uFF20') >= 0 || value.indexOf('\uFE6B') >= 0) {
return true;
}
final String decoded = percentDecode(value);
if (decoded.equals(value)) {
return false;
}
value = decoded;
}
return true;
}

/**
* Decodes every "%XX" escape as UTF-8 and keeps any other character, malformed escapes included.
*/
private static String percentDecode(final String value) {
final ByteArrayOutputStream bytes = new ByteArrayOutputStream(value.length());
int i = 0;
while (i < value.length()) {
final boolean escape = value.charAt(i) == '%' && i + 2 < value.length();
final int high = escape ? Character.digit(value.charAt(i + 1), 16) : -1;
final int low = high >= 0 ? Character.digit(value.charAt(i + 2), 16) : -1;
if (low >= 0) {
bytes.write(high * 16 + low);
i += 3;
} else {
final int codePoint = value.codePointAt(i);
final byte[] encoded = new String(Character.toChars(codePoint)).getBytes(StandardCharsets.UTF_8);
bytes.write(encoded, 0, encoded.length);
i += Character.charCount(codePoint);
}
}
return new String(bytes.toByteArray(), StandardCharsets.UTF_8);
}

/**
* Percent-encodes the control characters, Unicode format characters and line or paragraph separators of a log
* value; any other character, a space included, is kept.
*/
static String escapeForLog(final String value) {
final StringBuilder escaped = new StringBuilder(value.length());
value.codePoints().forEach(c -> {
final int type = Character.getType(c);
if (Character.isISOControl(c) || type == Character.FORMAT || type == Character.LINE_SEPARATOR
|| type == Character.PARAGRAPH_SEPARATOR) {
for (final byte b : new String(Character.toChars(c)).getBytes(StandardCharsets.UTF_8)) {
escaped.append('%').append(String.format("%02X", b & 0xFF));
}
} else {
escaped.appendCodePoint(c);
}
});
return escaped.toString();
}

/**
* Response headers written to the log: only the headers of a fixed allowlist.
*/
private static Header[] loggableResponseHeaders(final Header[] headers) {
return Arrays.stream(headers)
.filter(it -> LOGGED_RESPONSE_HEADERS.contains(it.getName().toLowerCase(Locale.ROOT)))
.toArray(Header[]::new);
}

private String getAcceptHeader(final ClientOperation clientOperation) {
switch (clientOperation) {
case GET:
Expand Down
28 changes: 14 additions & 14 deletions src/main/java/com/checkout/BaseUri.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ final class BaseUri {
+ "and a path without dot segments, encoded separators or encoded control characters";
private static final String INVALID_SUBDOMAIN_URI = "Invalid URI for %s: the environment subdomain can only be "
+ "added to an absolute URI whose host is a domain name of ASCII letters, digits, \"-\" and \"_\", "
+ "written without percent-encoding, not an IP address, with an optional port from 1 to 65535";
+ "written without percent-encoding, not an IP address, with no user information and an optional port "
+ "from 1 to 65535";
private static final int MAX_PORT = 65535;

private BaseUri() {
Expand Down Expand Up @@ -57,37 +58,36 @@ static URI normalise(final URI baseUri, final String setting) {
}

/**
* Prepends the subdomain to the host of the URI, refusing an authority that holds a "%" and a host
* that is not a domain name (see {@link #isDomainName(String)}). Port, raw path, raw query and raw
* fragment of the given URI are copied without decoding (callers pass {@code checkoutApi} already
* normalised); user information is not copied, as before (base URIs refuse it in
* {@link #normalise(URI, String)} before they get here).
* Prepends the subdomain to the host of the URI, refusing an authority that holds user information or
* a "%" and a host that is not a domain name (see {@link #isDomainName(String)}). Port, raw path, raw
* query and raw fragment of the given URI are copied without decoding (callers pass {@code checkoutApi}
* already normalised).
*
* @param uri the configured URI
* @param subdomain the subdomain, already validated
* @param setting the name of the setting the URI comes from, used in errors instead of the value
* @return the URI on the subdomain host
* @throws CheckoutArgumentException if the URI is missing, not absolute with an authority, its
* authority holds a "%", its port is out of range, or its host is not a
* domain name
* authority holds user information or a "%", its port is out of range,
* or its host is not a domain name
*/
static URI withSubdomain(final URI uri, final String subdomain, final String setting) {
if (uri == null) {
throw new CheckoutArgumentException(setting + " cannot be null");
}
final String authority = uri.getRawAuthority();
if (uri.getScheme() == null || uri.isOpaque() || authority == null || authority.indexOf('%') >= 0) {
if (uri.getScheme() == null || uri.isOpaque() || authority == null || authority.indexOf('@') >= 0
|| authority.indexOf('%') >= 0) {
throw invalid(INVALID_SUBDOMAIN_URI, setting);
}
final int hostStart = authority.lastIndexOf('@') + 1;
final String host = hostOf(authority.substring(hostStart));
final String host = hostOf(authority);
if (host == null || !isDomainName(host)) {
throw invalid(INVALID_SUBDOMAIN_URI, setting);
}
final StringBuilder rebuilt = new StringBuilder()
.append(uri.getScheme()).append("://")
.append(subdomain).append('.')
.append(authority.substring(hostStart));
.append(authority);
if (uri.getRawPath() != null) {
rebuilt.append(uri.getRawPath());
}
Expand All @@ -111,7 +111,7 @@ static URI withSubdomain(final URI uri, final String subdomain, final String set
* @return the host (an IPv6 literal keeps its brackets), or null when the host is empty or the port
* is not a number from 1 to 65535 (leading zeros allowed); an empty port after ":" is allowed
*/
private static String hostOf(final String hostAndPort) {
static String hostOf(final String hostAndPort) {
final int hostEnd = hostAndPort.startsWith("[") ? hostAndPort.indexOf(']') + 1 : hostAndPort.indexOf(':');
final String host = hostEnd < 0 ? hostAndPort : hostAndPort.substring(0, hostEnd);
final String port = hostEnd < 0 ? "" : hostAndPort.substring(hostEnd);
Expand Down Expand Up @@ -159,7 +159,7 @@ private static boolean isAsciiLetter(final char c) {
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
}

private static boolean isVisibleAscii(final String value) {
static boolean isVisibleAscii(final String value) {
for (int i = 0; i < value.length(); i++) {
final char c = value.charAt(i);
if (c <= ' ' || c > '~') {
Expand Down
25 changes: 25 additions & 0 deletions src/main/java/com/checkout/CheckoutAuthorizationException.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,37 @@

import static java.lang.String.format;

/**
* Raised when the credentials cannot authorize a request: the operation needs another authorization type, or the
* OAuth token request fails or returns an invalid token response.
*/
public final class CheckoutAuthorizationException extends CheckoutException {

/**
* Creates the exception.
*
* @param message the error message
*/
public CheckoutAuthorizationException(final String message) {
super(message);
}

/**
* Creates the exception with the failure that caused it.
*
* @param message the error message
* @param cause the underlying failure, for example the I/O error of the token request
*/
public CheckoutAuthorizationException(final String message, final Throwable cause) {
super(message, cause);
}

/**
* The exception for an operation that needs an authorization type the credentials do not provide.
*
* @param authorizationType the authorization type the operation needs
* @return the exception
*/
public static CheckoutAuthorizationException invalidAuthorization(final SdkAuthorizationType authorizationType) {
return new CheckoutAuthorizationException(format("Operation requires %s authorization type", authorizationType));
}
Expand Down
5 changes: 3 additions & 2 deletions src/main/java/com/checkout/EnvironmentSubdomain.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,12 @@ public final class EnvironmentSubdomain {
* Moves the environment's base URIs to the merchant-specific subdomain. {@code checkoutApi} is
* validated and normalised first with the same rules as every base URI; the rebuilt URIs keep the port,
* path, query and fragment of that URI (normalised for {@code checkoutApi}, as configured for
* {@code oAuthAuthorizationApi}) without decoding, and leave out any user information.
* {@code oAuthAuthorizationApi}) without decoding. A URI with user information is refused.
*
* @param environment the environment whose {@code checkoutApi} and {@code oAuthAuthorizationApi} are moved
* @param subdomain the merchant-specific subdomain, typically the client ID without the "cli_" prefix
* @throws CheckoutArgumentException if the subdomain is invalid, a URI is missing or invalid, or its host
* @throws CheckoutArgumentException if the subdomain is invalid, a URI is missing or invalid (user
* information included), or its host
* cannot take a subdomain (empty, an IPv6 literal or an IPv4 address);
* the error names the setting, never the value
*/
Expand Down
Loading
Loading