feat: convert Unicode subdomains to Punycode

Unicode (IDN) subdomains are converted via IDN.toASCII with ALLOW_UNASSIGNED, so newer code points like emojis are supported. Adds mock and live integration tests, renames CfClientTest to CfClientIntegrationTest.

Co-authored-by: Junie <junie@jetbrains.com>
This commit is contained in:
thischwaandJunie committed 2026-11-07 14:04:56 +01:00
1 parent be0512111d
commit 37321c6f9a
6 files changed
+101 -11

No files matched your search

+1
View File
@@ -17,6 +17,7 @@
- unexpected runtime exceptions aren't wrapped into a `CloudflareApiException("Unexpected error!")` anymore - 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) - 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 - security: query values (zone names, subdomains) are URL-encoded and IDs are validated, which prevents query parameter injection and path traversal
- Unicode subdomains are converted to Punycode before requests are sent
- connect and response timeouts (defaults: 10 s / 30 s), configurable via `withConnectTimeout` / `withResponseTimeout` - 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 - `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()`) - `CloudflareApiException` provides the HTTP status code (`getStatusCode()`) and the errors reported by Cloudflare (`getErrors()`)
+1 -1
View File
@@ -17,7 +17,7 @@ _Generated on 2026-11-06 13:29:26 UTC_
| ✅ | codes.thischwa.cf.CfBasicHttpClientErrorTest | 7 | 7 | 0 | 0 | | ✅ | codes.thischwa.cf.CfBasicHttpClientErrorTest | 7 | 7 | 0 | 0 |
| ✅ | codes.thischwa.cf.CfBasicHttpClientTest | 9 | 9 | 0 | 0 | | ✅ | codes.thischwa.cf.CfBasicHttpClientTest | 9 | 9 | 0 | 0 |
| ✅ | codes.thischwa.cf.CfClientPenTest | 4 | 4 | 0 | 0 | | ✅ | codes.thischwa.cf.CfClientPenTest | 4 | 4 | 0 | 0 |
| ✅ | codes.thischwa.cf.CfClientTest | 18 | 18 | 0 | 0 | | ✅ | codes.thischwa.cf.CfClientIntegrationTest | 18 | 18 | 0 | 0 |
| ✅ | codes.thischwa.cf.CfDnsClientBuilderTest | 21 | 21 | 0 | 0 | | ✅ | codes.thischwa.cf.CfDnsClientBuilderTest | 21 | 21 | 0 | 0 |
| ✅ | codes.thischwa.cf.CfDnsClientMockTest | 41 | 41 | 0 | 0 | | ✅ | codes.thischwa.cf.CfDnsClientMockTest | 41 | 41 | 0 | 0 |
| ✅ | codes.thischwa.cf.CfRequestTest | 10 | 10 | 0 | 0 | | ✅ | codes.thischwa.cf.CfRequestTest | 10 | 10 | 0 | 0 |
@@ -15,6 +15,7 @@ import codes.thischwa.cf.model.ResponseEntity;
import codes.thischwa.cf.model.ResultInfo; import codes.thischwa.cf.model.ResultInfo;
import codes.thischwa.cf.model.ZoneEntity; import codes.thischwa.cf.model.ZoneEntity;
import codes.thischwa.cf.model.ZoneMultipleResponse; import codes.thischwa.cf.model.ZoneMultipleResponse;
import java.net.IDN;
import java.time.Duration; import java.time.Duration;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
@@ -176,7 +177,17 @@ public class CfDnsClient extends CfBasicHttpClient {
if (APEX.equals(subdomain)) { if (APEX.equals(subdomain)) {
return zone.getName(); return zone.getName();
} }
return subdomain + "." + zone.getName(); String asciiSubdomain = subdomain;
if (!subdomain.chars().allMatch(character -> character <= 0x7f)) {
try {
// IDN implements IDNA2003 (Unicode 3.2), newer code points (e.g. emojis) must be allowed
asciiSubdomain = IDN.toASCII(subdomain, IDN.ALLOW_UNASSIGNED);
} catch (IllegalArgumentException exception) {
throw new IllegalArgumentException("Invalid internationalized subdomain: " + subdomain,
exception);
}
}
return asciiSubdomain + "." + zone.getName();
} }
/** /**
@@ -318,15 +329,17 @@ public class CfDnsClient extends CfBasicHttpClient {
* Optionally, filters by one or more DNS record types. * Optionally, filters by one or more DNS record types.
* *
* @param zone The zone entity containing information about the domain zone. * @param zone The zone entity containing information about the domain zone.
* @param subdomain The subdomain relative to the zone (e.g. "www" for "www.example.com"), * @param subdomain The subdomain relative to the zone (e.g. "www" for "www.example.com");
* or {@link #APEX} for the zone apex. * Unicode subdomains are converted to Punycode. {@link #APEX} indicates the
* zone apex.
* @param types Optional DNS record types to filter the results. If none are given, records of * @param types Optional DNS record types to filter the results. If none are given, records of
* all types are returned. * all types are returned.
* @return A list of {@code RecordEntity} objects representing the DNS records for the specified domain. * @return A list of {@code RecordEntity} objects representing the DNS records for the specified domain.
* @throws CloudflareNotFoundException if no records were found and 'emptyResultThrowsException' * @throws CloudflareNotFoundException if no records were found and 'emptyResultThrowsException'
* is enabled * is enabled
* @throws CloudflareApiException if an error occurs while interacting with the Cloudflare API * @throws CloudflareApiException if an error occurs while interacting with the Cloudflare API
* @throws IllegalArgumentException if the subdomain is blank or contains invalid characters * @throws IllegalArgumentException if the subdomain is blank, contains invalid characters or
* cannot be converted to Punycode
*/ */
public List<RecordEntity> recordListBySubdomain(ZoneEntity zone, String subdomain, public List<RecordEntity> recordListBySubdomain(ZoneEntity zone, String subdomain,
@Nullable RecordType... types) @Nullable RecordType... types)
@@ -361,8 +374,9 @@ public class CfDnsClient extends CfBasicHttpClient {
* Creates a new DNS record for a given subdomain within the specified zone. * Creates a new DNS record for a given subdomain within the specified zone.
* *
* @param zone The ZoneEntity representing the DNS zone where the record is to be created. * @param zone The ZoneEntity representing the DNS zone where the record is to be created.
* @param subdomain The subdomain relative to the zone (e.g. "api" for "api.example.com"), * @param subdomain The subdomain relative to the zone (e.g. "api" for "api.example.com");
* or {@link #APEX} for the zone apex. * Unicode subdomains are converted to Punycode. {@link #APEX} indicates the
* zone apex.
* @param ttl The time-to-live (TTL) value for the DNS record in seconds. * @param ttl The time-to-live (TTL) value for the DNS record in seconds.
* @param type The RecordType specifying the type of the DNS record (e.g., A, AAAA, CNAME). * @param type The RecordType specifying the type of the DNS record (e.g., A, AAAA, CNAME).
* @param content The content of the DNS record (e.g., IP address for A/AAAA records, target * @param content The content of the DNS record (e.g., IP address for A/AAAA records, target
@@ -370,7 +384,8 @@ public class CfDnsClient extends CfBasicHttpClient {
* @return The created RecordEntity object containing details of the newly created DNS record. * @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 * @throws CloudflareApiException If an error occurs while communicating with the Cloudflare API
* or creating the record. * or creating the record.
* @throws IllegalArgumentException if the subdomain is blank or contains invalid characters * @throws IllegalArgumentException if the subdomain is blank, contains invalid characters or
* cannot be converted to Punycode
*/ */
public RecordEntity recordCreateSubdomain(ZoneEntity zone, String subdomain, int ttl, RecordType type, public RecordEntity recordCreateSubdomain(ZoneEntity zone, String subdomain, int ttl, RecordType type,
String content) throws CloudflareApiException { String content) throws CloudflareApiException {
@@ -21,8 +21,7 @@ public interface ZoneOperations {
/** /**
* Selects a record with specific types within the zone for further operations. * Selects a record with specific types within the zone for further operations.
* <p> * <p>The type filter does not restrict a subsequent {@link RecordOperations#delete(RecordType...)} call;
* The type filter does not restrict a subsequent {@link RecordOperations#delete(RecordType...)} call;
* that method uses its own type arguments, and calling it without arguments deletes all record types * that method uses its own type arguments, and calling it without arguments deletes all record types
* for the selected subdomain. A {@link CloudflareApiException} from an individual deletion is * for the selected subdomain. A {@link CloudflareApiException} from an individual deletion is
* logged and does not stop later attempts; see {@link RecordOperations#delete(RecordType...)}. * logged and does not stop later attempts; see {@link RecordOperations#delete(RecordType...)}.
@@ -16,6 +16,7 @@ import codes.thischwa.cf.model.PagingRequest;
import codes.thischwa.cf.model.RecordEntity; import codes.thischwa.cf.model.RecordEntity;
import codes.thischwa.cf.model.RecordType; import codes.thischwa.cf.model.RecordType;
import codes.thischwa.cf.model.ZoneEntity; import codes.thischwa.cf.model.ZoneEntity;
import java.net.IDN;
import java.time.Instant; import java.time.Instant;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
@@ -30,7 +31,7 @@ import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@Slf4j @Slf4j
public class CfClientTest { public class CfClientIntegrationTest {
private static final String ZONE_STR = "mein-d-ns.de"; private static final String ZONE_STR = "mein-d-ns.de";
private static final String SLD_STR = "devsld"; private static final String SLD_STR = "devsld";
@@ -642,6 +643,39 @@ public class CfClientTest {
} }
} }
@Test
void testIdnSubdomain() throws Exception {
ZoneEntity zone = client.zoneGet(ZONE_STR);
String idnSub = "bücher-" + System.currentTimeMillis();
String punycodeSub = IDN.toASCII(idnSub);
assertTrue(punycodeSub.startsWith("xn--"), punycodeSub);
try {
// the Unicode subdomain is sent as Punycode, Cloudflare returns the Punycode name
RecordEntity rec = client.recordCreateSubdomain(zone, idnSub, TTL, RecordType.A, "130.0.0.30");
assertNotNull(rec.getId());
assertEquals(punycodeSub + "." + ZONE_STR, rec.getName());
assertEquals(punycodeSub, rec.getSubdomain());
// the record is found by the Unicode and by the Punycode subdomain
List<RecordEntity> byUnicode = client.recordListBySubdomain(zone, idnSub, RecordType.A);
assertEquals(1, byUnicode.size());
assertEquals(rec.getId(), byUnicode.get(0).getId());
assertEquals("130.0.0.30", byUnicode.get(0).getContent());
List<RecordEntity> byPunycode = client.recordListBySubdomain(zone, punycodeSub, RecordType.A);
assertEquals(1, byPunycode.size());
assertEquals(rec.getId(), byPunycode.get(0).getId());
// delete by the Unicode subdomain
client.recordDeleteTypeIfExists(zone, idnSub, RecordType.A);
assertThrows(CloudflareNotFoundException.class,
() -> client.recordListBySubdomain(zone, idnSub, RecordType.A));
} finally {
try {
client.recordDeleteTypeIfExists(zone, punycodeSub, RecordType.A);
} catch (Exception e) { /* ignore */ }
}
}
@Test @Test
void testTypeFilter() throws Exception { void testTypeFilter() throws Exception {
ZoneEntity zone = client.zoneGet(ZONE_STR); ZoneEntity zone = client.zoneGet(ZONE_STR);
@@ -10,6 +10,7 @@ import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoExtension;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.net.IDN;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@@ -787,6 +788,12 @@ class CfDnsClientMockTest {
() -> spyClient.recordCreateSubdomain(zone, sub, 60, RecordType.A, "1.2.3.4"), sub); () -> spyClient.recordCreateSubdomain(zone, sub, 60, RecordType.A, "1.2.3.4"), sub);
} }
assertThrows(IllegalArgumentException.class, () -> spyClient.recordListBySubdomain(zone, null)); assertThrows(IllegalArgumentException.class, () -> spyClient.recordListBySubdomain(zone, null));
String tooLongIdnLabel = "ä".repeat(64);
assertThrows(IllegalArgumentException.class,
() -> spyClient.recordListBySubdomain(zone, tooLongIdnLabel));
assertThrows(IllegalArgumentException.class,
() -> spyClient.recordCreateSubdomain(zone, tooLongIdnLabel, 60, RecordType.A,
"1.2.3.4"));
assertThrows(IllegalArgumentException.class, () -> spyClient.zoneGet("example.com&account.id=1")); assertThrows(IllegalArgumentException.class, () -> spyClient.zoneGet("example.com&account.id=1"));
assertThrows(IllegalArgumentException.class, () -> spyClient.zoneGet(" ")); assertThrows(IllegalArgumentException.class, () -> spyClient.zoneGet(" "));
verify(spyClient, never()).getRequest(anyString(), any()); verify(spyClient, never()).getRequest(anyString(), any());
@@ -810,6 +817,40 @@ class CfDnsClientMockTest {
eq(RecordMultipleResponse.class)); eq(RecordMultipleResponse.class));
} }
@Test
void testIdnSubdomainIsConvertedToPunycode() throws Exception {
CfDnsClient spyClient = spy(client);
ZoneEntity zone = createTestZone();
doReturn(recordResponse(List.of(), new ResultInfo(0)))
.when(spyClient).getRequest(anyString(), eq(RecordMultipleResponse.class));
doReturn(singleResponse(RecordEntity.build(
"xn--bcher-kva.example.com", RecordType.A, 60, "1.2.3.4")))
.when(spyClient).postRequest(anyString(), any(), eq(RecordSingleResponse.class));
spyClient.recordListBySubdomain(zone, "bücher");
spyClient.recordListBySubdomain(zone, "shop.bücher");
spyClient.recordListBySubdomain(zone, "xn--bcher-kva");
// code points newer than IDNA2003 (Unicode 3.2) like emojis must not be rejected
spyClient.recordListBySubdomain(zone, "emoji-🥷-忍者");
spyClient.recordCreateSubdomain(zone, "bücher", 60, RecordType.A, "1.2.3.4");
String base = "/zones/" + TEST_ZONE_ID + "/dns_records?name=";
String suffix = "&order=name&direction=asc&page=1&per_page=" + CfDnsClient.RECORDS_PER_PAGE;
verify(spyClient, times(2)).getRequest(eq(base + "xn--bcher-kva.example.com" + suffix),
eq(RecordMultipleResponse.class));
verify(spyClient).getRequest(eq(base + "shop.xn--bcher-kva.example.com" + suffix),
eq(RecordMultipleResponse.class));
String emojiPunycode = IDN.toASCII("emoji-🥷-忍者", IDN.ALLOW_UNASSIGNED);
assertTrue(emojiPunycode.startsWith("xn--"), emojiPunycode);
verify(spyClient).getRequest(eq(base + emojiPunycode + ".example.com" + suffix),
eq(RecordMultipleResponse.class));
ArgumentCaptor<Object> payload = ArgumentCaptor.forClass(Object.class);
verify(spyClient).postRequest(eq("/zones/" + TEST_ZONE_ID + "/dns_records"),
payload.capture(), eq(RecordSingleResponse.class));
assertEquals("xn--bcher-kva.example.com", ((RecordEntity) payload.getValue()).getName());
}
@Test @Test
void testRecordIdPathTraversalIsRejected() throws Exception { void testRecordIdPathTraversalIsRejected() throws Exception {
CfDnsClient spyClient = spy(client); CfDnsClient spyClient = spy(client);