security: encode request parameters, enforce HTTPS, add timeouts (#2)

- query values (zone names, subdomains) are URL-encoded, zone and
  record IDs must be alphanumeric: prevents query parameter injection
  and path traversal
- zone names and subdomains with whitespace, control characters or
  \ ? # & ; | < > " ' ` are rejected with an IllegalArgumentException
- withBaseUrl only accepts HTTPS (plain HTTP only for loopback hosts),
  no query/fragment, trailing slash is removed
- connect and response timeouts (defaults 10 s / 30 s), configurable
  via withConnectTimeout / withResponseTimeout; values below 1 ms or
  overflowing milliseconds are rejected
- null credentials throw an IllegalArgumentException, build() without
  authentication an IllegalStateException
- tests, README and changelog updated

refs #2

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
thischwaandClaude Opus 5.5 committed 2026-11-04 12:48:54 +01:00
1 parent f6c0544d9a
commit c7f27f2ac0
10 files changed
+441 -38

No files matched your search

+13
View File
@@ -62,6 +62,19 @@ CfDnsClient cfDnsClient = new CfDnsClientBuilder()
.build();
```
#### Further options:
```java
CfDnsClient cfDnsClient = new CfDnsClientBuilder()
.withApiTokenAuth("your-api-token")
.withBaseUrl("https://custom-api.example.com/client/v4") // must use HTTPS
.withConnectTimeout(Duration.ofSeconds(5)) // default: 10 s
.withResponseTimeout(Duration.ofSeconds(15)) // default: 30 s
.withEmptyResultThrowsException(true) // default: false
.build();
```
`build()` throws an `IllegalStateException` if no authentication is configured.
The client is thread-safe and should be reused, it holds a pool of HTTP connections.
`CfDnsClient` implements `AutoCloseable`, call `close()` (or use try-with-resources) to release the connections:
+5
View File
@@ -6,10 +6,15 @@
- `recordList(zone, String subdomain, RecordType... types)` and `recordList(zone, String subdomain)` → `recordListBySubdomain(zone, subdomain, types...)`
- `recordList(zone, RecordType... types)` → `recordListByType(zone, types...)`
- `recordList(zone)` and `recordList(zone, PagingRequest)` remain unchanged
- `withBaseUrl` only accepts HTTPS URLs (plain HTTP only for loopback hosts like `localhost`), otherwise an `IllegalArgumentException` is thrown
- `build()` throws an `IllegalStateException` if no authentication was configured, `null` credentials throw an `IllegalArgumentException`
- zone names and subdomains with whitespace, control characters or `\ ? # & ; | < > " ' `` ` `` are rejected with an `IllegalArgumentException`, zone and record IDs must be alphanumeric
- timestamps of `RecordEntity` and `ZoneEntity` (`createdOn`, `modifiedOn`, `activatedOn`) are of type `java.time.Instant` instead of `LocalDateTime`, so the time zone (UTC) isn't lost anymore
- Cloudflare responses with HTTP status 404 throw a `CloudflareNotFoundException` (independent of `emptyResultThrowsException`)
- unexpected runtime exceptions aren't wrapped into a `CloudflareApiException("Unexpected error!")` anymore
- batch DELETE sends only the record IDs, batch PATCH sends all writable attributes which aren't `null` (before: only the content)
- security: query values (zone names, subdomains) are URL-encoded and IDs are validated, which prevents query parameter injection and path traversal
- connect and response timeouts (defaults: 10 s / 30 s), configurable via `withConnectTimeout` / `withResponseTimeout`
- `CfDnsClient` uses one shared HTTP client with connection pooling instead of a new one per request and implements `AutoCloseable`, call `close()` to release the connections
- `CloudflareApiException` provides the HTTP status code (`getStatusCode()`) and the errors reported by Cloudflare (`getErrors()`)
- `RecordEntity` supports the attributes `priority` (MX, URI), `data` (e.g. SRV incl. its priority, CAA), `comment` and `tags`; they are also considered by batch operations, as is `proxied`
@@ -4,6 +4,7 @@ import codes.thischwa.cf.model.AbstractResponse;
import codes.thischwa.cf.model.ResponseResultInfo;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.List;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
@@ -12,8 +13,11 @@ import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPatch;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.classic.methods.HttpPut;
import org.apache.hc.client5.http.config.ConnectionConfig;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
import org.apache.hc.core5.http.ClassicHttpRequest;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.ContentType;
@@ -22,6 +26,7 @@ import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.message.BasicClassicHttpRequest;
import org.apache.hc.core5.util.Timeout;
import org.jetbrains.annotations.NotNull;
import tools.jackson.core.JacksonException;
import tools.jackson.databind.ObjectMapper;
@@ -52,10 +57,24 @@ abstract class CfBasicHttpClient implements AutoCloseable {
* @param auth the authentication mechanism to use
*/
CfBasicHttpClient(@NotNull String baseUrl, @NotNull CfDnsClientBuilder.CfAuth auth) {
this(baseUrl, auth, CfDnsClientBuilder.DEFAULT_CONNECT_TIMEOUT,
CfDnsClientBuilder.DEFAULT_RESPONSE_TIMEOUT);
}
/**
* Creates a new Cloudflare HTTP client with the specified base URL, authentication and timeouts.
*
* @param baseUrl the base URL for the Cloudflare API
* @param auth the authentication mechanism to use
* @param connectTimeout the timeout for establishing a connection
* @param responseTimeout the timeout for waiting for the response data
*/
CfBasicHttpClient(@NotNull String baseUrl, @NotNull CfDnsClientBuilder.CfAuth auth,
@NotNull Duration connectTimeout, @NotNull Duration responseTimeout) {
this.baseUrl = baseUrl;
this.auth = auth;
this.objectMapper = JsonConf.initObjectMapper();
this.httpClient = createHttpClient();
this.httpClient = createHttpClient(connectTimeout, responseTimeout);
}
/**
@@ -69,16 +88,32 @@ abstract class CfBasicHttpClient implements AutoCloseable {
httpClient.close();
}
private CloseableHttpClient createHttpClient() {
return HttpClients.custom().addRequestInterceptorFirst((request, context, execChain) -> {
request.addHeader(HttpHeaders.ACCEPT_CHARSET, "UTF-8");
request.addHeader(HttpHeaders.ACCEPT_ENCODING, "gzip");
request.addHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.getMimeType());
request.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType());
if (request instanceof ClassicHttpRequest classicRequest) {
auth.applyAuth(classicRequest);
}
}).build();
private CloseableHttpClient createHttpClient(Duration connectTimeout, Duration responseTimeout) {
Timeout connect = Timeout.ofMilliseconds(connectTimeout.toMillis());
Timeout response = Timeout.ofMilliseconds(responseTimeout.toMillis());
ConnectionConfig connectionConfig = ConnectionConfig.custom()
.setConnectTimeout(connect)
.setSocketTimeout(response)
.build();
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(connect)
.setResponseTimeout(response)
.build();
return HttpClients.custom()
.setConnectionManager(PoolingHttpClientConnectionManagerBuilder.create()
.setDefaultConnectionConfig(connectionConfig)
.build())
.setDefaultRequestConfig(requestConfig)
.addRequestInterceptorFirst((request, context, execChain) -> {
request.addHeader(HttpHeaders.ACCEPT_CHARSET, "UTF-8");
request.addHeader(HttpHeaders.ACCEPT_ENCODING, "gzip");
request.addHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.getMimeType());
request.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType());
if (request instanceof ClassicHttpRequest classicRequest) {
auth.applyAuth(classicRequest);
}
})
.build();
}
private <T extends AbstractResponse> T executeRequest(ClassicHttpRequest request,
@@ -15,6 +15,7 @@ import codes.thischwa.cf.model.ResponseEntity;
import codes.thischwa.cf.model.ResultInfo;
import codes.thischwa.cf.model.ZoneEntity;
import codes.thischwa.cf.model.ZoneMultipleResponse;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
@@ -23,6 +24,7 @@ import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.Nullable;
@@ -125,13 +127,46 @@ public class CfDnsClient extends CfBasicHttpClient {
*/
CfDnsClient(boolean emptyResultThrowsException, String baseUrl, CfDnsClientBuilder.CfAuth auth,
int recordsPerPage) {
super(baseUrl, auth);
this(emptyResultThrowsException, baseUrl, auth, recordsPerPage,
CfDnsClientBuilder.DEFAULT_CONNECT_TIMEOUT, CfDnsClientBuilder.DEFAULT_RESPONSE_TIMEOUT);
}
/**
* Constructs a new instance of {@code CfDnsClient} with all settings.
*/
CfDnsClient(boolean emptyResultThrowsException, String baseUrl, CfDnsClientBuilder.CfAuth auth,
int recordsPerPage, Duration connectTimeout, Duration responseTimeout) {
super(baseUrl, auth, connectTimeout, responseTimeout);
this.responseValidator = new ResponseValidator(emptyResultThrowsException);
this.emptyResultThrowsException = emptyResultThrowsException;
this.recordsPerPage = recordsPerPage;
}
/**
* Characters which can't be part of a DNS name, but are typical for injection attempts. Further
* validation is done by Cloudflare; the values are URL-encoded anyway. A slash isn't rejected,
* because it's valid in classless reverse delegation names (RFC 2317).
*/
private static final Pattern INVALID_NAME_CHARS = Pattern.compile("[\\s\\p{Cntrl}\\\\?#&;|<>\"'`]");
/**
* Validates a zone name or subdomain before it's used in a request.
*
* @throws IllegalArgumentException if the name is {@code null}, blank or contains invalid
* characters
*/
private static String validateName(String name, String kind) {
if (name == null || name.isBlank()) {
throw new IllegalArgumentException(kind + " must not be null or blank");
}
if (INVALID_NAME_CHARS.matcher(name).find()) {
throw new IllegalArgumentException("Invalid characters in " + kind + ": " + name);
}
return name;
}
private static String buildFqdn(ZoneEntity zone, String subdomain) {
validateName(subdomain, "subdomain");
if (APEX.equals(subdomain)) {
return zone.getName();
}
@@ -169,6 +204,7 @@ public class CfDnsClient extends CfBasicHttpClient {
* @return a ZoneOperations instance for chaining operations
* @throws CloudflareNotFoundException if the zone doesn't exist
* @throws CloudflareApiException if the zone cannot be accessed
* @throws IllegalArgumentException if the name is blank or contains invalid characters
*/
public ZoneOperations zone(String zoneName) throws CloudflareApiException {
ZoneEntity zoneEntity = zoneGet(zoneName);
@@ -215,10 +251,11 @@ public class CfDnsClient extends CfBasicHttpClient {
* is enabled.
* @throws CloudflareApiException If an error occurs while making the API request or
* processing the response.
* @throws IllegalArgumentException if the name is blank or contains invalid characters
*/
@Nullable
public ZoneEntity zoneGet(String name) throws CloudflareApiException {
String endpoint = CfRequest.ZONE_INFO.buildPath(name);
String endpoint = CfRequest.ZONE_INFO.buildPath(validateName(name, "zone name"));
ZoneMultipleResponse response = getRequest(endpoint, ZoneMultipleResponse.class);
checkResponse(response, true);
List<ZoneEntity> zones = response.getResult();
@@ -271,6 +308,7 @@ public class CfDnsClient extends CfBasicHttpClient {
* @throws CloudflareNotFoundException if no records were found and 'emptyResultThrowsException'
* is enabled
* @throws CloudflareApiException if an error occurs while interacting with the Cloudflare API
* @throws IllegalArgumentException if the subdomain is blank or contains invalid characters
*/
public List<RecordEntity> recordListBySubdomain(ZoneEntity zone, String subdomain,
@Nullable RecordType... types)
@@ -312,6 +350,7 @@ public class CfDnsClient extends CfBasicHttpClient {
* @return The created RecordEntity object containing details of the newly created DNS record.
* @throws CloudflareApiException If an error occurs while communicating with the Cloudflare API
* or creating the record.
* @throws IllegalArgumentException if the subdomain is blank or contains invalid characters
*/
public RecordEntity recordCreateSubdomain(ZoneEntity zone, String subdomain, int ttl, RecordType type,
String content) throws CloudflareApiException {
@@ -451,6 +490,7 @@ public class CfDnsClient extends CfBasicHttpClient {
* @param subdomain The subdomain relative to the zone for which the records are being checked.
* @param recordTypes The types of DNS records that should be deleted if they exist.
* @throws CloudflareApiException If an error occurs during API communication.
* @throws IllegalArgumentException if the subdomain is blank or contains invalid characters
*/
public void recordDeleteTypeIfExists(ZoneEntity zone, String subdomain, RecordType... recordTypes)
throws CloudflareApiException {
@@ -1,7 +1,10 @@
package codes.thischwa.cf;
import java.net.URI;
import java.time.Duration;
import java.util.Locale;
import java.util.Set;
import org.apache.hc.core5.http.ClassicHttpRequest;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
@@ -16,8 +19,25 @@ public class CfDnsClientBuilder {
*/
public static final String DEFAULT_BASEURL = "https://api.cloudflare.com/client/v4";
/**
* The default timeout for establishing a connection.
*/
public static final Duration DEFAULT_CONNECT_TIMEOUT = Duration.ofSeconds(10);
/**
* The default timeout for waiting for the response data.
*/
public static final Duration DEFAULT_RESPONSE_TIMEOUT = Duration.ofSeconds(30);
/**
* Hosts for which plain HTTP is allowed (e.g. for local tests).
*/
private static final Set<String> LOOPBACK_HOSTS = Set.of("localhost", "127.0.0.1", "[::1]", "::1");
private boolean emptyResultThrowsException;
private CfAuth auth;
private Duration connectTimeout = DEFAULT_CONNECT_TIMEOUT;
private Duration responseTimeout = DEFAULT_RESPONSE_TIMEOUT;
@Nullable
private String baseUrl;
@@ -42,14 +62,89 @@ public class CfDnsClientBuilder {
* Sets the base URL to be used by the {@code CfDnsClient}.
* This method allows configuring the base URL for API requests, overriding any default value.
*
* @param baseUrl the base URL to be used for API requests
* <p>To protect the credentials, the URL must use HTTPS. Plain HTTP is only allowed for
* loopback hosts (e.g. {@code localhost}) for testing purposes.
*
* @param baseUrl the base URL to be used for API requests, {@code null} resets it to
* {@link #DEFAULT_BASEURL}
* @return the current instance of {@code CfDnsClientBuilder}, enabling method chaining
* @throws IllegalArgumentException if the URL is invalid or doesn't use HTTPS
*/
public CfDnsClientBuilder withBaseUrl(String baseUrl) {
this.baseUrl = baseUrl;
public CfDnsClientBuilder withBaseUrl(@Nullable String baseUrl) {
this.baseUrl = baseUrl == null ? null : validateBaseUrl(baseUrl);
return this;
}
/**
* Sets the timeout for establishing a connection. Default is {@link #DEFAULT_CONNECT_TIMEOUT}.
*
* @param connectTimeout the connect timeout, must be positive
* @return the current instance of {@code CfDnsClientBuilder}, enabling method chaining
* @throws IllegalArgumentException if the timeout is {@code null}, zero or negative
*/
public CfDnsClientBuilder withConnectTimeout(Duration connectTimeout) {
this.connectTimeout = validateTimeout(connectTimeout, "Connect timeout");
return this;
}
/**
* Sets the timeout for waiting for the response data. Default is
* {@link #DEFAULT_RESPONSE_TIMEOUT}.
*
* @param responseTimeout the response timeout, must be positive
* @return the current instance of {@code CfDnsClientBuilder}, enabling method chaining
* @throws IllegalArgumentException if the timeout is {@code null}, zero or negative
*/
public CfDnsClientBuilder withResponseTimeout(Duration responseTimeout) {
this.responseTimeout = validateTimeout(responseTimeout, "Response timeout");
return this;
}
private static Duration validateTimeout(Duration timeout, String name) {
if (timeout == null || timeout.isZero() || timeout.isNegative()) {
throw new IllegalArgumentException(name + " must be positive: " + timeout);
}
long millis;
try {
millis = timeout.toMillis();
} catch (ArithmeticException e) {
throw new IllegalArgumentException(name + " is too large: " + timeout, e);
}
// the HTTP client works with milliseconds, 0 ms would disable the timeout
if (millis < 1) {
throw new IllegalArgumentException(name + " must be at least 1 ms: " + timeout);
}
return timeout;
}
private static String validateBaseUrl(String baseUrl) {
URI uri;
try {
uri = URI.create(baseUrl.strip());
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Invalid base URL: " + baseUrl, e);
}
String scheme = uri.getScheme() == null ? "" : uri.getScheme().toLowerCase(Locale.ROOT);
String host = uri.getHost();
if (host == null || host.isBlank()) {
throw new IllegalArgumentException("Base URL must contain a host: " + baseUrl);
}
if (uri.getRawQuery() != null || uri.getRawFragment() != null) {
throw new IllegalArgumentException("Base URL must not contain a query or fragment: " + baseUrl);
}
boolean https = "https".equals(scheme);
boolean loopbackHttp = "http".equals(scheme) && LOOPBACK_HOSTS.contains(host.toLowerCase(Locale.ROOT));
if (!https && !loopbackHttp) {
throw new IllegalArgumentException("Base URL must use HTTPS: " + baseUrl);
}
String normalized = uri.toString();
// avoid double slashes when appending the endpoint paths
while (normalized.endsWith("/")) {
normalized = normalized.substring(0, normalized.length() - 1);
}
return normalized;
}
/**
* Configures the authentication method for the {@code CfDnsClient} to use an API token.
* This is the recommended way to authenticate with the Cloudflare API, as it provides
@@ -92,10 +187,16 @@ public class CfDnsClientBuilder {
* @return a new instance of {@code CfDnsClient} configured with the
* specified options such as base URL, authentication details,
* and the exception-handling policy for empty results.
* @throws IllegalStateException if no authentication was configured
*/
public CfDnsClient build() {
if (auth == null) {
throw new IllegalStateException(
"No authentication configured, use withApiTokenAuth(...) or withEmailKeyAuth(...)");
}
String url = baseUrl == null ? DEFAULT_BASEURL : baseUrl;
return new CfDnsClient(emptyResultThrowsException, url, auth);
return new CfDnsClient(emptyResultThrowsException, url, auth, CfDnsClient.RECORDS_PER_PAGE,
connectTimeout, responseTimeout);
}
/**
@@ -128,8 +229,8 @@ public class CfDnsClientBuilder {
* @param apiToken the Cloudflare API token
* @throws IllegalArgumentException if the API token is null or blank
*/
ApiTokenAuth(@NotNull String apiToken) {
if (apiToken.isBlank()) {
ApiTokenAuth(String apiToken) {
if (apiToken == null || apiToken.isBlank()) {
throw new IllegalArgumentException("API token must not be null or blank!");
}
this.apiToken = apiToken;
@@ -157,11 +258,11 @@ public class CfDnsClientBuilder {
* @param authKey the API key of the Cloudflare account
* @throws IllegalArgumentException if email or key is null or blank
*/
EmailKeyAuth(@NotNull String authEmail, @NotNull String authKey) {
if (authEmail.isBlank()) {
EmailKeyAuth(String authEmail, String authKey) {
if (authEmail == null || authEmail.isBlank()) {
throw new IllegalArgumentException("Authentication email must not be null or blank!");
}
if (authKey.isBlank()) {
if (authKey == null || authKey.isBlank()) {
throw new IllegalArgumentException("Authentication key must not be null or blank!");
}
this.authEmail = authEmail;
+51 -15
View File
@@ -1,5 +1,9 @@
package codes.thischwa.cf;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import lombok.Getter;
/**
@@ -18,46 +22,54 @@ public enum CfRequest {
* name. The endpoint path supports a placeholder for the zone name, which needs to be provided to
* construct the complete path.
*/
ZONE_INFO("/zones?name=%s"),
ZONE_INFO("/zones?name={value}"),
/**
* Represents the API endpoint path for retrieving information about DNS records within a
* specific DNS zone. The endpoint path includes a placeholder for the zone identifier, which
* needs to be provided to construct the complete path.
*/
RECORD_LIST("/zones/%s/dns_records"),
RECORD_LIST("/zones/{id}/dns_records"),
/**
* Represents the API endpoint path for retrieving information about a DNS record within a
* specific DNS zone by its name. The endpoint path includes placeholders for the zone identifier
* and the record name, which need to be provided to construct the complete path.
*/
RECORD_LIST_NAME("/zones/%s/dns_records?name=%s"),
RECORD_LIST_NAME("/zones/{id}/dns_records?name={value}"),
/**
* Represents the API endpoint path for creating a new DNS record within a specific DNS zone. The
* endpoint path includes a placeholder for the zone identifier, which needs to be provided to
* construct the complete path.
*/
RECORD_CREATE("/zones/%s/dns_records"),
RECORD_CREATE("/zones/{id}/dns_records"),
/**
* Represents the API endpoint path for updating an existing DNS record within a specific DNS
* zone. The endpoint path includes placeholders for the zone identifier and the record
* identifier, which need to be provided to construct the complete path.
*/
RECORD_UPDATE("/zones/%s/dns_records/%s"),
RECORD_UPDATE("/zones/{id}/dns_records/{id}"),
/**
* Represents the API endpoint path for performing batch operations on DNS records within a specific zone.
* The placeholder "%s" in the path is intended to be replaced by a zone identifier.
* The placeholder in the path is intended to be replaced by a zone identifier.
* This constant is used to construct the URL for interacting with the batch DNS records API.
*/
RECORD_BATCH("/zones/%s/dns_records/batch"),
RECORD_BATCH("/zones/{id}/dns_records/batch"),
/**
* Represents the API endpoint path for deleting an existing DNS record within a specific DNS
* zone. The endpoint path includes placeholders for the zone identifier and the record
* identifier, which need to be provided to construct the complete path.
*/
RECORD_DELETE("/zones/%s/dns_records/%s");
RECORD_DELETE("/zones/{id}/dns_records/{id}");
private static final String ID_PLACEHOLDER = "{id}";
private static final Pattern PLACEHOLDER = Pattern.compile("\\{(id|value)}");
/**
* Allowed characters of Cloudflare identifiers (zone and record IDs). Prevents e.g. path
* traversal with IDs like "../..".
*/
private static final Pattern ID_PATTERN = Pattern.compile("[A-Za-z0-9]{1,64}");
private static final char VAR_IDENTIFICATION = '%';
private final String path;
CfRequest(String path) {
@@ -65,21 +77,45 @@ public enum CfRequest {
}
/**
* Constructs the complete API endpoint path by formatting the base path with the provided
* arguments.
* Constructs the complete API endpoint path by replacing the placeholders with the provided
* arguments. Identifiers ({@code {id}}) are validated, query values ({@code {value}}) are
* URL-encoded.
*
* @param vars the arguments to format the path string with; these are typically specific
* identifiers or parameters required by the API endpoint.
* @param vars the arguments to replace the placeholders with, in the order of the placeholders
* @return the fully constructed API endpoint path as a string.
* @throws IllegalArgumentException if the number of arguments doesn't match the placeholders, an
* argument is {@code null} or an identifier is invalid
*/
String buildPath(Object... vars) {
long varCount = path.chars().filter(c -> c == VAR_IDENTIFICATION).count();
Matcher matcher = PLACEHOLDER.matcher(path);
long varCount = matcher.results().count();
if (varCount != vars.length) {
throw new IllegalArgumentException(
String.format(
"The number of variables (%d) does not match the number of parameters (%d) in the path string: %s",
vars.length, varCount, path));
}
return String.format(path, vars);
matcher.reset();
StringBuilder sb = new StringBuilder();
int i = 0;
while (matcher.find()) {
Object arg = vars[i++];
if (arg == null) {
throw new IllegalArgumentException("Path variable must not be null: " + path);
}
String value = arg.toString();
String replacement;
if (ID_PLACEHOLDER.equals(matcher.group())) {
if (!ID_PATTERN.matcher(value).matches()) {
throw new IllegalArgumentException("Invalid identifier: " + value);
}
replacement = value;
} else {
replacement = URLEncoder.encode(value, StandardCharsets.UTF_8);
}
matcher.appendReplacement(sb, Matcher.quoteReplacement(replacement));
}
matcher.appendTail(sb);
return sb.toString();
}
}
@@ -11,7 +11,9 @@ import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.SocketTimeoutException;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
@@ -33,12 +35,22 @@ class CfBasicHttpClientErrorTest {
private final AtomicInteger requestCount = new AtomicInteger();
private volatile int status;
private volatile String body;
private volatile String lastPath;
private volatile long delayMillis;
@BeforeEach
void setUp() throws IOException {
server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
server.createContext("/", exchange -> {
requestCount.incrementAndGet();
lastPath = exchange.getRequestURI().getRawPath();
if (delayMillis > 0) {
try {
Thread.sleep(delayMillis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(status, bytes.length);
try (OutputStream out = exchange.getResponseBody()) {
@@ -125,4 +137,35 @@ class CfBasicHttpClientErrorTest {
assertEquals(CloudflareApiException.NO_STATUS_CODE, e.getStatusCode());
assertTrue(e.getErrors().isEmpty());
}
@Test
void trailingSlashOfBaseUrlIsRemoved() throws Exception {
respond(200, ZONE_JSON);
try (CfDnsClient slashClient = new CfDnsClientBuilder()
.withApiTokenAuth("test-token")
.withBaseUrl("http://localhost:" + server.getAddress().getPort() + "/client/v4/")
.build()) {
slashClient.zoneList();
}
assertEquals("/client/v4/zones", lastPath);
}
@Test
void responseTimeoutIsApplied() throws Exception {
respond(200, ZONE_JSON);
delayMillis = 2000;
try (CfDnsClient timeoutClient = new CfDnsClientBuilder()
.withApiTokenAuth("test-token")
.withBaseUrl("http://localhost:" + server.getAddress().getPort())
.withResponseTimeout(Duration.ofMillis(200))
.build()) {
long start = System.nanoTime();
CloudflareApiException e = assertThrows(CloudflareApiException.class, timeoutClient::zoneList);
long elapsedMillis = (System.nanoTime() - start) / 1_000_000;
assertInstanceOf(SocketTimeoutException.class, e.getCause());
assertTrue(elapsedMillis < 1500, "timeout not applied, elapsed: " + elapsedMillis);
} finally {
delayMillis = 0;
}
}
}
@@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.time.Duration;
import org.junit.jupiter.api.Test;
/**
@@ -147,4 +148,57 @@ class CfDnsClientBuilderTest {
assertNotNull(client);
}
@Test
void testBaseUrlMustUseHttps() {
CfDnsClientBuilder builder = new CfDnsClientBuilder().withApiTokenAuth("test-token");
assertThrows(IllegalArgumentException.class, () -> builder.withBaseUrl("http://api.example.com"));
assertThrows(IllegalArgumentException.class, () -> builder.withBaseUrl("ftp://api.example.com"));
assertThrows(IllegalArgumentException.class, () -> builder.withBaseUrl("api.example.com"));
assertThrows(IllegalArgumentException.class, () -> builder.withBaseUrl("https://"));
assertThrows(IllegalArgumentException.class, () -> builder.withBaseUrl("https://api example.com"));
assertThrows(IllegalArgumentException.class, () -> builder.withBaseUrl("https://api.example.com/v4?x=1"));
assertThrows(IllegalArgumentException.class, () -> builder.withBaseUrl("https://api.example.com/v4#x"));
}
@Test
void testBaseUrlAllowsHttpForLoopbackOnly() {
assertNotNull(new CfDnsClientBuilder().withApiTokenAuth("t").withBaseUrl("http://localhost:8080").build());
assertNotNull(new CfDnsClientBuilder().withApiTokenAuth("t").withBaseUrl("http://127.0.0.1:8080/v4").build());
assertNotNull(new CfDnsClientBuilder().withApiTokenAuth("t").withBaseUrl("HTTPS://API.example.com/").build());
assertNotNull(new CfDnsClientBuilder().withApiTokenAuth("t").withBaseUrl(null).build());
}
@Test
void testInvalidTimeoutsAreRejected() {
CfDnsClientBuilder builder = new CfDnsClientBuilder();
assertThrows(IllegalArgumentException.class, () -> builder.withConnectTimeout(null));
assertThrows(IllegalArgumentException.class, () -> builder.withConnectTimeout(Duration.ZERO));
assertThrows(IllegalArgumentException.class, () -> builder.withResponseTimeout(Duration.ofSeconds(-1)));
// would become 0 ms = no timeout at all
assertThrows(IllegalArgumentException.class, () -> builder.withResponseTimeout(Duration.ofNanos(500_000)));
assertThrows(IllegalArgumentException.class, () -> builder.withConnectTimeout(Duration.ofNanos(1)));
// would overflow when converted to milliseconds
assertThrows(IllegalArgumentException.class,
() -> builder.withResponseTimeout(Duration.ofSeconds(Long.MAX_VALUE)));
assertNotNull(builder.withApiTokenAuth("t").withResponseTimeout(Duration.ofMillis(1)).build());
assertNotNull(builder.withApiTokenAuth("t")
.withConnectTimeout(Duration.ofSeconds(1))
.withResponseTimeout(Duration.ofSeconds(2))
.build());
}
@Test
void testNullCredentialsAreRejected() {
assertThrows(IllegalArgumentException.class, () -> new CfDnsClientBuilder().withApiTokenAuth(null));
assertThrows(IllegalArgumentException.class, () -> new CfDnsClientBuilder().withEmailKeyAuth(null, "key"));
assertThrows(IllegalArgumentException.class, () -> new CfDnsClientBuilder().withEmailKeyAuth("a@b.de", null));
}
@Test
void testBuildWithoutAuthFails() {
assertThrows(IllegalStateException.class, () -> new CfDnsClientBuilder().build());
assertThrows(IllegalStateException.class,
() -> new CfDnsClientBuilder().withBaseUrl("https://api.example.com").build());
}
}
@@ -731,4 +731,52 @@ class CfDnsClientMockTest {
assertEquals("srv1", sent.getPatches().get(0).getId());
assertEquals(10, sent.getPatches().get(0).getPriority());
}
@Test
void testInvalidSubdomainIsRejectedBeforeRequest() throws Exception {
CfDnsClient spyClient = spy(client);
ZoneEntity zone = createTestZone();
for (String sub : List.of("; rm -rf /", "| cat /etc/passwd", "`shutdown -h now`",
"<script>alert('x')</script>", "\"quoted\"", "a b", "x?y", "x#y", "x&y", "x\ty", " ", "")) {
assertThrows(IllegalArgumentException.class, () -> spyClient.recordListBySubdomain(zone, sub), sub);
assertThrows(IllegalArgumentException.class,
() -> spyClient.recordCreateSubdomain(zone, sub, 60, RecordType.A, "1.2.3.4"), sub);
}
assertThrows(IllegalArgumentException.class, () -> spyClient.recordListBySubdomain(zone, null));
assertThrows(IllegalArgumentException.class, () -> spyClient.zoneGet("example.com&account.id=1"));
assertThrows(IllegalArgumentException.class, () -> spyClient.zoneGet(" "));
verify(spyClient, never()).getRequest(anyString(), any());
verify(spyClient, never()).postRequest(anyString(), any(), any());
}
@Test
void testUnusualButValidSubdomainIsEncoded() throws Exception {
CfDnsClient spyClient = spy(client);
doReturn(recordResponse(List.of(), new ResultInfo(0)))
.when(spyClient).getRequest(anyString(), eq(RecordMultipleResponse.class));
spyClient.recordListBySubdomain(createTestZone(), "$(reboot)");
spyClient.recordListBySubdomain(createTestZone(), "0/26");
verify(spyClient).getRequest(eq("/zones/" + TEST_ZONE_ID
+ "/dns_records?name=%24%28reboot%29.example.com&page=1&per_page=" + CfDnsClient.RECORDS_PER_PAGE),
eq(RecordMultipleResponse.class));
verify(spyClient).getRequest(eq("/zones/" + TEST_ZONE_ID
+ "/dns_records?name=0%2F26.example.com&page=1&per_page=" + CfDnsClient.RECORDS_PER_PAGE),
eq(RecordMultipleResponse.class));
}
@Test
void testRecordIdPathTraversalIsRejected() throws Exception {
CfDnsClient spyClient = spy(client);
ZoneEntity zone = createTestZone();
assertThrows(IllegalArgumentException.class, () -> spyClient.recordDelete(zone, "../.."));
RecordEntity rec = RecordEntity.build("../..", "1.2.3.4");
assertThrows(IllegalArgumentException.class, () -> spyClient.recordUpdate(zone, rec));
ZoneEntity badZone = zone("../../accounts", "example.com");
assertThrows(IllegalArgumentException.class, () -> spyClient.recordList(badZone));
verify(spyClient, never()).deleteRequest(anyString(), any());
verify(spyClient, never()).patchRequest(anyString(), any(), any());
verify(spyClient, never()).getRequest(anyString(), any());
}
}
@@ -55,4 +55,32 @@ public class CfRequestTest {
IllegalArgumentException.class,
() -> CfRequest.RECORD_UPDATE.buildPath("zone123"));
}
@Test
public void testQueryValueIsUrlEncoded() {
assertEquals("/zones?name=example.com%26account.id%3D1",
CfRequest.ZONE_INFO.buildPath("example.com&account.id=1"));
assertEquals("/zones/zone123/dns_records?name=..%2F..%2Fx.example.com",
CfRequest.RECORD_LIST_NAME.buildPath("zone123", "../../x.example.com"));
assertEquals("/zones/zone123/dns_records?name=%24%28reboot%29.example.com",
CfRequest.RECORD_LIST_NAME.buildPath("zone123", "$(reboot).example.com"));
assertEquals("/zones/zone123/dns_records?name=%F0%9F%A5%B7.example.com",
CfRequest.RECORD_LIST_NAME.buildPath("zone123", "\uD83E\uDD77.example.com"));
assertEquals("/zones/zone123/dns_records?name=*.example.com",
CfRequest.RECORD_LIST_NAME.buildPath("zone123", "*.example.com"));
}
@Test
public void testInvalidIdentifiersAreRejected() {
for (String id : new String[] {"..", "../..", "a/b", "a b", "id?x=1", "id#x", "", "%2e%2e",
"a".repeat(65)}) {
assertThrows(IllegalArgumentException.class,
() -> CfRequest.RECORD_DELETE.buildPath("zone123", id), "id: " + id);
assertThrows(IllegalArgumentException.class,
() -> CfRequest.RECORD_LIST.buildPath(id), "zone id: " + id);
}
assertThrows(IllegalArgumentException.class, () -> CfRequest.RECORD_LIST.buildPath((Object) null));
assertEquals("/zones/0123456789abcdef0123456789abcdef/dns_records",
CfRequest.RECORD_LIST.buildPath("0123456789abcdef0123456789abcdef"));
}
}