Compare commits
30
Commits
88601efa1b
..
v1.0.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e06aa67c24 | ||
|
|
2031aa93e6 | ||
|
|
3f28774944 | ||
|
|
0ddc6b29ce | ||
|
|
b95d9bc5a0 | ||
|
|
980942fac5 | ||
|
|
6dd9a477e5 | ||
|
|
50d8d385f7 | ||
|
|
9de0eaf850 | ||
|
|
d09b5cb98b | ||
|
|
02dee0f720 | ||
|
|
b35517afa7 | ||
|
|
8e4d8ef427 | ||
|
|
1ddc1ce832 | ||
|
|
5488a92c2d | ||
|
|
330f665b97 | ||
|
|
c02ce68df5 | ||
|
|
1a37d308e3 | ||
|
|
a7292153e2 | ||
|
|
848453c04e | ||
|
|
0d78e39a70 | ||
|
|
d802edf6ee | ||
|
|
ff4adb5c4d | ||
|
|
4a3859e17c | ||
|
|
ad641c1573 | ||
|
|
37321c6f9a | ||
|
|
cb3303dab0 | ||
|
|
be0512111d | ||
|
|
6ab318063f | ||
|
|
8515f81621 |
No files matched your search
@@ -7,6 +7,7 @@ on:
|
|||||||
- 'feature/**'
|
- 'feature/**'
|
||||||
pull_request:
|
pull_request:
|
||||||
types: [ opened, synchronize, reopened ]
|
types: [ opened, synchronize, reopened ]
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
defaults:
|
defaults:
|
||||||
run:
|
run:
|
||||||
@@ -25,6 +26,9 @@ jobs:
|
|||||||
uses: ./.gitea/actions/setup-java-maven
|
uses: ./.gitea/actions/setup-java-maven
|
||||||
|
|
||||||
- name: Build and test
|
- name: Build and test
|
||||||
|
env:
|
||||||
|
# required by the live tests (CfClientTest, CfClientPenTest), they are skipped if not set
|
||||||
|
API_TOKEN: ${{ secrets.API_TOKEN }}
|
||||||
run: mvn -B verify
|
run: mvn -B verify
|
||||||
|
|
||||||
- name: Publish Test Report
|
- name: Publish Test Report
|
||||||
|
|||||||
@@ -12,3 +12,4 @@
|
|||||||
cf.yml
|
cf.yml
|
||||||
/docs/apidocs/javadoc.sh
|
/docs/apidocs/javadoc.sh
|
||||||
/.claude/settings.local.json
|
/.claude/settings.local.json
|
||||||
|
/.junie/
|
||||||
@@ -62,6 +62,19 @@ CfDnsClient cfDnsClient = new CfDnsClientBuilder()
|
|||||||
.build();
|
.build();
|
||||||
```
|
```
|
||||||
|
|
||||||
|
#### Further options:
|
||||||
|
```java
|
||||||
|
CfDnsClient cfDnsClient = new CfDnsClientBuilder()
|
||||||
|
.withApiTokenAuth("your-api-token")
|
||||||
|
.withBaseUrl("https://api.cloudflare.com/client/v4") // HTTPS required;
|
||||||
|
.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.
|
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:
|
`CfDnsClient` implements `AutoCloseable`, call `close()` (or use try-with-resources) to release the connections:
|
||||||
|
|
||||||
@@ -82,12 +95,18 @@ List<ZoneEntity> zones = cfDnsClient.zoneList();
|
|||||||
zones.forEach(zone -> System.out.println("Zone: " + zone.getName()));
|
zones.forEach(zone -> System.out.println("Zone: " + zone.getName()));
|
||||||
```
|
```
|
||||||
|
|
||||||
By default, up to 1000 zones are fetched in a single request. Use a `PagingRequest` to control paging:
|
Without a `PagingRequest`, `zoneList()` fetches zones in pages of 50, requesting further pages as needed.
|
||||||
|
Use a `PagingRequest` to retrieve a specific page:
|
||||||
|
|
||||||
```java
|
```java
|
||||||
List<ZoneEntity> zones = cfDnsClient.zoneList(PagingRequest.of(1, 50)); // page 1, 50 zones per page
|
List<ZoneEntity> zones = cfDnsClient.zoneList(PagingRequest.forZones(1, 50)); // page 1, 50 zones per page
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Page numbers start at 1. `PagingRequest` is immutable; use `forRecords(page, perPage)` for DNS records and
|
||||||
|
`forZones(page, perPage)` for zones. Cloudflare accepts page sizes from 5 to 50 for zones and from
|
||||||
|
1 to 5,000,000 for DNS records. `PagingRequest.defaultPaging()` requests page 1 with 50 items; it
|
||||||
|
does not fetch additional pages. Use `next()` or `withPage(page)` to create another page request.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### `zoneGet`
|
### `zoneGet`
|
||||||
@@ -147,10 +166,11 @@ If exactly one record type is given, the filtering is done by Cloudflare, otherw
|
|||||||
List<RecordEntity> allZoneRecords = cfDnsClient.recordList(zone);
|
List<RecordEntity> allZoneRecords = cfDnsClient.recordList(zone);
|
||||||
|
|
||||||
// Get the records of a zone page by page (page 2, 100 records per page)
|
// Get the records of a zone page by page (page 2, 100 records per page)
|
||||||
List<RecordEntity> pagedRecords = cfDnsClient.recordList(zone, PagingRequest.of(2, 100));
|
List<RecordEntity> pagedRecords = cfDnsClient.recordList(zone, PagingRequest.forRecords(2, 100));
|
||||||
```
|
```
|
||||||
|
|
||||||
Without a `PagingRequest`, all pages are fetched and the complete result is returned.
|
Without a `PagingRequest`, all pages are fetched using 1,000 records per page and combined into one result.
|
||||||
|
This large page size can consume substantial memory. If paging remains inconsistent after three attempts, the client logs a warning and may return an incomplete list. Use a smaller `PagingRequest` to retrieve one page at a time; further pages must be requested explicitly.
|
||||||
With a `PagingRequest`, exactly the requested page is returned.
|
With a `PagingRequest`, exactly the requested page is returned.
|
||||||
|
|
||||||
`RecordEntity#getSubdomain()` returns the record name relative to its zone, e.g. `my.sub` for
|
`RecordEntity#getSubdomain()` returns the record name relative to its zone, e.g. `my.sub` for
|
||||||
@@ -260,6 +280,8 @@ cfDnsClient.recordDeleteTypeIfExists(zone, "api", RecordType.A, RecordType.AAAA)
|
|||||||
System.out.println("Deletion attempt completed.");
|
System.out.println("Deletion attempt completed.");
|
||||||
```
|
```
|
||||||
|
|
||||||
|
If no record types are specified, records of all types for the subdomain are selected. Each record deletion is attempted independently: a `CloudflareApiException` from one deletion is logged and later records are still processed. No per-record result is returned, so a normal return does not guarantee that every selected record was deleted. Errors while retrieving the records are still reported; no matching records are treated as a no-op.
|
||||||
|
|
||||||
### Batch Operations
|
### Batch Operations
|
||||||
|
|
||||||
Process multiple DNS record operations (POST, PUT, PATCH, DELETE) in a single batch request.
|
Process multiple DNS record operations (POST, PUT, PATCH, DELETE) in a single batch request.
|
||||||
@@ -412,6 +434,8 @@ client.zone("example.com")
|
|||||||
.delete(RecordType.A, RecordType.AAAA);
|
.delete(RecordType.A, RecordType.AAAA);
|
||||||
```
|
```
|
||||||
|
|
||||||
|
The types passed to `delete` determine which record types are selected; a type filter passed to `getRecord` does not restrict deletion. Calling `delete()` without type arguments selects all record types for that subdomain. A `CloudflareApiException` from an individual deletion is logged and does not stop later attempts; no per-record result is returned.
|
||||||
|
|
||||||
### Advantages of Fluent API
|
### Advantages of Fluent API
|
||||||
|
|
||||||
- **More Readable**: The chain of method calls reads like natural language
|
- **More Readable**: The chain of method calls reads like natural language
|
||||||
|
|||||||
+14
-7
@@ -1,15 +1,24 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
- 0.6.0-SNAPSHOT:
|
- 1.0.0:
|
||||||
- **Breaking Changes**:
|
- **Breaking Changes**:
|
||||||
- `recordList` overloads replaced, because they were ambiguous (e.g. `recordList(zone, null)` didn't compile):
|
- `recordList` overloads replaced, because they were ambiguous (e.g. `recordList(zone, null)` didn't compile):
|
||||||
- `recordList(zone, String subdomain, RecordType... types)` and `recordList(zone, String subdomain)` → `recordListBySubdomain(zone, subdomain, types...)`
|
- `recordList(zone, String subdomain, RecordType... types)` and `recordList(zone, String subdomain)` → `recordListBySubdomain(zone, subdomain, types...)`
|
||||||
- `recordList(zone, RecordType... types)` → `recordListByType(zone, types...)`
|
- `recordList(zone, RecordType... types)` → `recordListByType(zone, types...)`
|
||||||
- `recordList(zone)` and `recordList(zone, PagingRequest)` remain unchanged
|
- `recordList(zone)` and `recordList(zone, PagingRequest)` remain unchanged
|
||||||
|
- `CfDnsClient#recordCreateSld(...)` was removed; use `recordCreateSubdomain(...)`
|
||||||
|
- `PagingRequest` is now an immutable record with `page()` and `perPage()` accessors. The setters and `getPagingParams()` were removed; use `forRecords(...)`, `forZones(...)`, `next()` and `withPage(...)` instead.
|
||||||
|
- `PagingRequest.defaultPaging()` now requests 50 items instead of 1,000. Page numbers and page sizes are validated; zone requests accept 5–50 items per page, while DNS record requests accept 1–5,000,000.
|
||||||
|
- `withBaseUrl` only accepts HTTPS URLs, 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
|
- 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`)
|
- Cloudflare responses with HTTP status 404 throw a `CloudflareNotFoundException` (independent of `emptyResultThrowsException`)
|
||||||
- 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
|
||||||
|
- Unicode subdomains are converted to Punycode before requests are sent
|
||||||
|
- 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()`)
|
||||||
- `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`
|
- `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`
|
||||||
@@ -18,16 +27,14 @@
|
|||||||
- filtering by exactly one record type is done by Cloudflare (`?type=`), unknown record types in responses don't break the client-side filter anymore
|
- filtering by exactly one record type is done by Cloudflare (`?type=`), unknown record types in responses don't break the client-side filter anymore
|
||||||
- updated dependencies: jackson 3.2.4, httpclient5 5.6.4, lombok 1.18.48, logback-classic 1.6.6, mockito-junit-jupiter 5.24.0
|
- updated dependencies: jackson 3.2.4, httpclient5 5.6.4, lombok 1.18.48, logback-classic 1.6.6, mockito-junit-jupiter 5.24.0
|
||||||
- updated maven plugins: maven-compiler-plugin 3.16.0, maven-surefire-plugin 3.6.0, maven-jar-plugin 3.5.1
|
- updated maven plugins: maven-compiler-plugin 3.16.0, maven-surefire-plugin 3.6.0, maven-jar-plugin 3.5.1
|
||||||
- README: fixed fluent API examples, documented paging and further methods
|
- fixed "getRecord" wording in log and exception messages (e.g. "Invalid record type")
|
||||||
- fixed "getRecord" wording in javadoc, log and exception messages (e.g. "Invalid record type")
|
- **Deprecation**: the misleading term "sld" was renamed to "subdomain": `RecordEntity#getSld()` is deprecated for removal; use `RecordEntity#getSubdomain()`
|
||||||
- **Deprecation**: the misleading term "sld" was renamed to "subdomain", the old methods will be removed in a future release:
|
|
||||||
- `RecordEntity#getSld()` → `RecordEntity#getSubdomain()`
|
|
||||||
- `CfDnsClient#recordCreateSld(...)` → `CfDnsClient#recordCreateSubdomain(...)`
|
|
||||||
- `getSubdomain()` returns `"@"` for the zone apex; `CfDnsClient.APEX` can be used to address the zone apex
|
- `getSubdomain()` returns `"@"` for the zone apex; `CfDnsClient.APEX` can be used to address the zone apex
|
||||||
- fixed: API errors were wrapped into a generic "Unexpected error!" exception
|
- fixed: API errors were wrapped into a generic "Unexpected error!" exception
|
||||||
- fixed: `zoneGet` threw an `IndexOutOfBoundsException` for unknown zones, it now returns `null` or throws a `CloudflareNotFoundException` (depending on `emptyResultThrowsException`)
|
- fixed: `zoneGet` threw an `IndexOutOfBoundsException` for unknown zones, it now returns `null` or throws a `CloudflareNotFoundException` (depending on `emptyResultThrowsException`)
|
||||||
- fixed: `getSubdomain()` failed for apex records and records with multi-level subdomains, batch operations now send the full record name
|
- fixed: `getSubdomain()` failed for apex records and records with multi-level subdomains, batch operations now send the full record name
|
||||||
- fixed: `zoneList()` and `recordList(...)` without `PagingRequest` returned only the first page, now all pages are fetched
|
- fixed: `zoneList()` and `recordList(...)` without `PagingRequest` returned only the first page, now all pages are fetched; `recordList(zone, null)` uses a page size of 1,000 to limit response memory use
|
||||||
|
- fixed: DNS records are listed with a stable order (`order=name`), because without it Cloudflare's pages can overlap and miss records; fetched records are de-duplicated and inconsistent pages are fetched again
|
||||||
- fixed: `recordDelete` threw a `NullPointerException` for an empty result
|
- fixed: `recordDelete` threw a `NullPointerException` for an empty result
|
||||||
- 0.5.0:
|
- 0.5.0:
|
||||||
- moved the project to git.mein-gateway.de
|
- moved the project to git.mein-gateway.de
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
|
|
||||||
<groupId>codes.thischwa</groupId>
|
<groupId>codes.thischwa</groupId>
|
||||||
<artifactId>cloudflaredns</artifactId>
|
<artifactId>cloudflaredns</artifactId>
|
||||||
<version>0.6.0-SNAPSHOT</version>
|
<version>1.0.0</version>
|
||||||
<name>CloudflareDNS-java</name>
|
<name>CloudflareDNS-java</name>
|
||||||
<inceptionYear>2025</inceptionYear>
|
<inceptionYear>2025</inceptionYear>
|
||||||
<packaging>jar</packaging>
|
<packaging>jar</packaging>
|
||||||
@@ -51,7 +51,7 @@
|
|||||||
<developerConnection>scm:git:https://git.mein-gateway.de/thischwa/CloudflareDNS-java.git</developerConnection>
|
<developerConnection>scm:git:https://git.mein-gateway.de/thischwa/CloudflareDNS-java.git</developerConnection>
|
||||||
<connection>scm:git:https://git.mein-gateway.de/thischwa/CloudflareDNS-java.git</connection>
|
<connection>scm:git:https://git.mein-gateway.de/thischwa/CloudflareDNS-java.git</connection>
|
||||||
<url>https://git.mein-gateway.de/thischwa/CloudflareDNS-java</url>
|
<url>https://git.mein-gateway.de/thischwa/CloudflareDNS-java</url>
|
||||||
<tag>HEAD</tag>
|
<tag>v1.0.0</tag>
|
||||||
</scm>
|
</scm>
|
||||||
|
|
||||||
<distributionManagement>
|
<distributionManagement>
|
||||||
|
|||||||
+11
-11
@@ -1,6 +1,6 @@
|
|||||||
# Test Report
|
# Test Report
|
||||||
|
|
||||||
_Generated on 2026-11-03 17:19:07 UTC_
|
_Generated on 2026-11-16 18:29:19 UTC_
|
||||||
|
|
||||||
**✅ All tests passed**
|
**✅ All tests passed**
|
||||||
|
|
||||||
@@ -8,24 +8,24 @@ _Generated on 2026-11-03 17:19:07 UTC_
|
|||||||
|
|
||||||
| | Tests | Passed | Failed | Skipped |
|
| | Tests | Passed | Failed | Skipped |
|
||||||
|---|---|---|---|---|
|
|---|---|---|---|---|
|
||||||
| **Total** | 143 | 121 | 0 | 22 |
|
| **Total** | 165 | 165 | 0 | 0 |
|
||||||
|
|
||||||
### Details
|
### Details
|
||||||
|
|
||||||
| Status | Suite | Tests | Passed | Failed | Skipped |
|
| Status | Suite | Tests | Passed | Failed | Skipped |
|
||||||
|---|---|---|---|---|---|
|
|---|---|---|---|---|---|
|
||||||
| ✅ | codes.thischwa.cf.CfBasicHttpClientErrorTest | 5 | 5 | 0 | 0 |
|
| ✅ | codes.thischwa.cf.CfBasicHttpClientErrorTest | 6 | 6 | 0 | 0 |
|
||||||
| ✅ | codes.thischwa.cf.CfBasicHttpClientTest | 9 | 9 | 0 | 0 |
|
| ✅ | codes.thischwa.cf.CfBasicHttpClientTest | 9 | 9 | 0 | 0 |
|
||||||
| ✅ | codes.thischwa.cf.CfClientPenTest | 4 | 0 | 0 | 4 |
|
| ✅ | codes.thischwa.cf.CfClientIntegrationTest | 19 | 19 | 0 | 0 |
|
||||||
| ✅ | codes.thischwa.cf.CfClientTest | 18 | 0 | 0 | 18 |
|
| ✅ | codes.thischwa.cf.CfClientPenTest | 4 | 4 | 0 | 0 |
|
||||||
| ✅ | codes.thischwa.cf.CfDnsClientBuilderTest | 16 | 16 | 0 | 0 |
|
| ✅ | codes.thischwa.cf.CfDnsClientBuilderTest | 21 | 21 | 0 | 0 |
|
||||||
| ✅ | codes.thischwa.cf.CfDnsClientMockTest | 33 | 33 | 0 | 0 |
|
| ✅ | codes.thischwa.cf.CfDnsClientMockTest | 42 | 42 | 0 | 0 |
|
||||||
| ✅ | codes.thischwa.cf.CfRequestTest | 8 | 8 | 0 | 0 |
|
| ✅ | codes.thischwa.cf.CfRequestTest | 10 | 10 | 0 | 0 |
|
||||||
| ✅ | codes.thischwa.cf.ObjectMapperTest | 4 | 4 | 0 | 0 |
|
| ✅ | codes.thischwa.cf.ObjectMapperTest | 4 | 4 | 0 | 0 |
|
||||||
| ✅ | codes.thischwa.cf.ResponseValidatorTest | 11 | 11 | 0 | 0 |
|
| ✅ | codes.thischwa.cf.ResponseValidatorTest | 11 | 11 | 0 | 0 |
|
||||||
| ✅ | codes.thischwa.cf.fluent.FluentApiTest | 15 | 15 | 0 | 0 |
|
| ✅ | codes.thischwa.cf.fluent.FluentApiTest | 15 | 15 | 0 | 0 |
|
||||||
| ✅ | codes.thischwa.cf.model.BatchEntryTest | 2 | 2 | 0 | 0 |
|
| ✅ | codes.thischwa.cf.model.BatchEntryTest | 2 | 2 | 0 | 0 |
|
||||||
| ✅ | codes.thischwa.cf.model.PagingRequestTest | 4 | 4 | 0 | 0 |
|
| ✅ | codes.thischwa.cf.model.PagingRequestTest | 8 | 8 | 0 | 0 |
|
||||||
| ✅ | codes.thischwa.cf.model.RecordEntityTest | 10 | 10 | 0 | 0 |
|
| ✅ | codes.thischwa.cf.model.RecordEntityTest | 10 | 10 | 0 | 0 |
|
||||||
| ✅ | codes.thischwa.cf.model.RecordTypeTest | 3 | 3 | 0 | 0 |
|
| ✅ | codes.thischwa.cf.model.RecordTypeTest | 3 | 3 | 0 | 0 |
|
||||||
| ✅ | codes.thischwa.cf.model.ZoneEntityTest | 1 | 1 | 0 | 0 |
|
| ✅ | codes.thischwa.cf.model.ZoneEntityTest | 1 | 1 | 0 | 0 |
|
||||||
@@ -35,5 +35,5 @@ _Generated on 2026-11-03 17:19:07 UTC_
|
|||||||
| Package | Line Coverage | Branch Coverage |
|
| Package | Line Coverage | Branch Coverage |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| codes.thischwa.cf.fluent | 100% (23/23) | 100% (4/4) |
|
| codes.thischwa.cf.fluent | 100% (23/23) | 100% (4/4) |
|
||||||
| codes.thischwa.cf.model | 100% (97/97) | 93% (13/14) |
|
| codes.thischwa.cf.model | 100% (102/102) | 96% (23/24) |
|
||||||
| codes.thischwa.cf | 91% (304/334) | 84% (114/136) |
|
| codes.thischwa.cf | 97% (441/454) | 88% (189/214) |
|
||||||
@@ -4,6 +4,7 @@ import codes.thischwa.cf.model.AbstractResponse;
|
|||||||
import codes.thischwa.cf.model.ResponseResultInfo;
|
import codes.thischwa.cf.model.ResponseResultInfo;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.time.Duration;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
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.HttpPatch;
|
||||||
import org.apache.hc.client5.http.classic.methods.HttpPost;
|
import org.apache.hc.client5.http.classic.methods.HttpPost;
|
||||||
import org.apache.hc.client5.http.classic.methods.HttpPut;
|
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.CloseableHttpClient;
|
||||||
import org.apache.hc.client5.http.impl.classic.HttpClients;
|
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.ClassicHttpRequest;
|
||||||
import org.apache.hc.core5.http.ClassicHttpResponse;
|
import org.apache.hc.core5.http.ClassicHttpResponse;
|
||||||
import org.apache.hc.core5.http.ContentType;
|
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.EntityUtils;
|
||||||
import org.apache.hc.core5.http.io.entity.StringEntity;
|
import org.apache.hc.core5.http.io.entity.StringEntity;
|
||||||
import org.apache.hc.core5.http.message.BasicClassicHttpRequest;
|
import org.apache.hc.core5.http.message.BasicClassicHttpRequest;
|
||||||
|
import org.apache.hc.core5.util.Timeout;
|
||||||
import org.jetbrains.annotations.NotNull;
|
import org.jetbrains.annotations.NotNull;
|
||||||
import tools.jackson.core.JacksonException;
|
import tools.jackson.core.JacksonException;
|
||||||
import tools.jackson.databind.ObjectMapper;
|
import tools.jackson.databind.ObjectMapper;
|
||||||
@@ -52,10 +57,24 @@ abstract class CfBasicHttpClient implements AutoCloseable {
|
|||||||
* @param auth the authentication mechanism to use
|
* @param auth the authentication mechanism to use
|
||||||
*/
|
*/
|
||||||
CfBasicHttpClient(@NotNull String baseUrl, @NotNull CfDnsClientBuilder.CfAuth auth) {
|
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.baseUrl = baseUrl;
|
||||||
this.auth = auth;
|
this.auth = auth;
|
||||||
this.objectMapper = JsonConf.initObjectMapper();
|
this.objectMapper = JsonConf.initObjectMapper();
|
||||||
this.httpClient = createHttpClient();
|
this.httpClient = createHttpClient(connectTimeout, responseTimeout);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -69,16 +88,32 @@ abstract class CfBasicHttpClient implements AutoCloseable {
|
|||||||
httpClient.close();
|
httpClient.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
private CloseableHttpClient createHttpClient() {
|
private CloseableHttpClient createHttpClient(Duration connectTimeout, Duration responseTimeout) {
|
||||||
return HttpClients.custom().addRequestInterceptorFirst((request, context, execChain) -> {
|
Timeout connect = Timeout.ofMilliseconds(connectTimeout.toMillis());
|
||||||
request.addHeader(HttpHeaders.ACCEPT_CHARSET, "UTF-8");
|
Timeout response = Timeout.ofMilliseconds(responseTimeout.toMillis());
|
||||||
request.addHeader(HttpHeaders.ACCEPT_ENCODING, "gzip");
|
ConnectionConfig connectionConfig = ConnectionConfig.custom()
|
||||||
request.addHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.getMimeType());
|
.setConnectTimeout(connect)
|
||||||
request.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType());
|
.setSocketTimeout(response)
|
||||||
if (request instanceof ClassicHttpRequest classicRequest) {
|
.build();
|
||||||
auth.applyAuth(classicRequest);
|
RequestConfig requestConfig = RequestConfig.custom()
|
||||||
}
|
.setConnectionRequestTimeout(connect)
|
||||||
}).build();
|
.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,
|
private <T extends AbstractResponse> T executeRequest(ClassicHttpRequest request,
|
||||||
|
|||||||
@@ -15,6 +15,8 @@ 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.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
@@ -23,6 +25,7 @@ import java.util.List;
|
|||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.jetbrains.annotations.Nullable;
|
import org.jetbrains.annotations.Nullable;
|
||||||
@@ -74,27 +77,33 @@ import org.jetbrains.annotations.Nullable;
|
|||||||
* .build();
|
* .build();
|
||||||
* </code></pre>
|
* </code></pre>
|
||||||
*
|
*
|
||||||
* <p>Example with custom base URL:
|
* <p>Example specifying the Cloudflare API base URL:
|
||||||
* <pre><code>
|
* <pre><code>
|
||||||
* CfDnsClient cfDnsClient = new CfDnsClientBuilder()
|
* CfDnsClient cfDnsClient = new CfDnsClientBuilder()
|
||||||
* .withApiTokenAuth("your-api-token")
|
* .withApiTokenAuth("your-api-token")
|
||||||
* .withBaseUrl("https://custom-api.example.com")
|
* .withBaseUrl(CfDnsClientBuilder.DEFAULT_BASEURL)
|
||||||
* .build();
|
* .build();
|
||||||
* </code></pre>
|
* </code></pre>
|
||||||
*/
|
*/
|
||||||
@Slf4j
|
@Slf4j
|
||||||
public class CfDnsClient extends CfBasicHttpClient {
|
public class CfDnsClient extends CfBasicHttpClient {
|
||||||
|
|
||||||
/**
|
|
||||||
* Page size used when fetching all zones. Cloudflare allows max. 50 zones per page.
|
|
||||||
*/
|
|
||||||
static final int ZONES_PER_PAGE = 50;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Page size used when fetching all DNS records.
|
* Page size used when fetching all DNS records.
|
||||||
*/
|
*/
|
||||||
static final int RECORDS_PER_PAGE = 1000;
|
static final int RECORDS_PER_PAGE = 1000;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sort order for listing DNS records. Cloudflare doesn't guarantee a stable order without it,
|
||||||
|
* so pages could overlap or miss records.
|
||||||
|
*/
|
||||||
|
static final String RECORD_ORDER = "order=name&direction=asc";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Max. attempts to fetch all pages consistently.
|
||||||
|
*/
|
||||||
|
private static final int MAX_PAGING_ATTEMPTS = 3;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Conventional name for the zone apex (the zone name itself).
|
* Conventional name for the zone apex (the zone name itself).
|
||||||
*/
|
*/
|
||||||
@@ -125,17 +134,60 @@ public class CfDnsClient extends CfBasicHttpClient {
|
|||||||
*/
|
*/
|
||||||
CfDnsClient(boolean emptyResultThrowsException, String baseUrl, CfDnsClientBuilder.CfAuth auth,
|
CfDnsClient(boolean emptyResultThrowsException, String baseUrl, CfDnsClientBuilder.CfAuth auth,
|
||||||
int recordsPerPage) {
|
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.responseValidator = new ResponseValidator(emptyResultThrowsException);
|
||||||
this.emptyResultThrowsException = emptyResultThrowsException;
|
this.emptyResultThrowsException = emptyResultThrowsException;
|
||||||
this.recordsPerPage = recordsPerPage;
|
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) {
|
private static String buildFqdn(ZoneEntity zone, String subdomain) {
|
||||||
|
validateName(subdomain, "subdomain");
|
||||||
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();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -169,6 +221,7 @@ public class CfDnsClient extends CfBasicHttpClient {
|
|||||||
* @return a ZoneOperations instance for chaining operations
|
* @return a ZoneOperations instance for chaining operations
|
||||||
* @throws CloudflareNotFoundException if the zone doesn't exist
|
* @throws CloudflareNotFoundException if the zone doesn't exist
|
||||||
* @throws CloudflareApiException if the zone cannot be accessed
|
* @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 {
|
public ZoneOperations zone(String zoneName) throws CloudflareApiException {
|
||||||
ZoneEntity zoneEntity = zoneGet(zoneName);
|
ZoneEntity zoneEntity = zoneGet(zoneName);
|
||||||
@@ -186,19 +239,30 @@ public class CfDnsClient extends CfBasicHttpClient {
|
|||||||
* @throws CloudflareApiException If an error occurs during the API request or response handling.
|
* @throws CloudflareApiException If an error occurs during the API request or response handling.
|
||||||
*/
|
*/
|
||||||
public List<ZoneEntity> zoneList() throws CloudflareApiException {
|
public List<ZoneEntity> zoneList() throws CloudflareApiException {
|
||||||
return getAllPages(CfRequest.ZONE_LIST.buildPath(), ZoneMultipleResponse.class, ZONES_PER_PAGE);
|
return getAllPages(CfRequest.ZONE_LIST.buildPath(), ZoneMultipleResponse.class,
|
||||||
|
PagingRequest.DEFAULT_PAGE_SIZE);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieves a single page of DNS zones using the provided paging request parameters.
|
* Retrieves a single page of DNS zones using the provided paging request parameters.
|
||||||
|
* Cloudflare requires a page size between 5 and 50 for this endpoint.
|
||||||
*
|
*
|
||||||
* @param pagingRequest the pagination request object containing parameters for paging and
|
* @param pagingRequest the pagination request object containing parameters for paging and
|
||||||
* filtering zone data
|
* filtering zone data
|
||||||
* @return a list of {@code ZoneEntity} objects representing the DNS zones retrieved from the API
|
* @return a list of {@code ZoneEntity} objects representing the DNS zones retrieved from the API
|
||||||
* @throws CloudflareApiException if there is an error during the API request or response
|
* @throws CloudflareApiException if there is an error during the API request or response
|
||||||
* processing
|
* processing
|
||||||
|
* @throws IllegalArgumentException if the page size is outside the range 5 to 50
|
||||||
*/
|
*/
|
||||||
public List<ZoneEntity> zoneList(PagingRequest pagingRequest) throws CloudflareApiException {
|
public List<ZoneEntity> zoneList(PagingRequest pagingRequest) throws CloudflareApiException {
|
||||||
|
Objects.requireNonNull(pagingRequest, "pagingRequest must not be null");
|
||||||
|
int perPage = pagingRequest.perPage();
|
||||||
|
if (perPage < PagingRequest.MIN_ZONES_PER_PAGE
|
||||||
|
|| perPage > PagingRequest.MAX_ZONES_PER_PAGE) {
|
||||||
|
throw new IllegalArgumentException("Zone page size must be between "
|
||||||
|
+ PagingRequest.MIN_ZONES_PER_PAGE + " and " + PagingRequest.MAX_ZONES_PER_PAGE
|
||||||
|
+ ", but was " + perPage);
|
||||||
|
}
|
||||||
String endpoint = pagingRequest.addQueryString(CfRequest.ZONE_LIST.buildPath());
|
String endpoint = pagingRequest.addQueryString(CfRequest.ZONE_LIST.buildPath());
|
||||||
ZoneMultipleResponse response = getRequest(endpoint, ZoneMultipleResponse.class);
|
ZoneMultipleResponse response = getRequest(endpoint, ZoneMultipleResponse.class);
|
||||||
checkResponse(response);
|
checkResponse(response);
|
||||||
@@ -215,10 +279,11 @@ public class CfDnsClient extends CfBasicHttpClient {
|
|||||||
* is enabled.
|
* is enabled.
|
||||||
* @throws CloudflareApiException If an error occurs while making the API request or
|
* @throws CloudflareApiException If an error occurs while making the API request or
|
||||||
* processing the response.
|
* processing the response.
|
||||||
|
* @throws IllegalArgumentException if the name is blank or contains invalid characters
|
||||||
*/
|
*/
|
||||||
@Nullable
|
@Nullable
|
||||||
public ZoneEntity zoneGet(String name) throws CloudflareApiException {
|
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);
|
ZoneMultipleResponse response = getRequest(endpoint, ZoneMultipleResponse.class);
|
||||||
checkResponse(response, true);
|
checkResponse(response, true);
|
||||||
List<ZoneEntity> zones = response.getResult();
|
List<ZoneEntity> zones = response.getResult();
|
||||||
@@ -242,13 +307,14 @@ public class CfDnsClient extends CfBasicHttpClient {
|
|||||||
*
|
*
|
||||||
* @param zone The zone entity containing information about the target zone.
|
* @param zone The zone entity containing information about the target zone.
|
||||||
* @param pagingRequest The paging request containing parameters such as page size and number.
|
* @param pagingRequest The paging request containing parameters such as page size and number.
|
||||||
* If {@code null}, all pages are fetched.
|
* If {@code null}, all pages are fetched using an internal page size of 1,000.
|
||||||
|
* For a specific page, Cloudflare allows a page size between 1 and 5,000,000.
|
||||||
* @return A list of RecordEntity objects representing the DNS records of the specified zone.
|
* @return A list of RecordEntity objects representing the DNS records of the specified zone.
|
||||||
* @throws CloudflareApiException If an error occurs during the API request or response processing.
|
* @throws CloudflareApiException If an error occurs during the API request or response processing.
|
||||||
*/
|
*/
|
||||||
public List<RecordEntity> recordList(ZoneEntity zone, @Nullable PagingRequest pagingRequest)
|
public List<RecordEntity> recordList(ZoneEntity zone, @Nullable PagingRequest pagingRequest)
|
||||||
throws CloudflareApiException {
|
throws CloudflareApiException {
|
||||||
String path = CfRequest.RECORD_LIST.buildPath(zone.getId());
|
String path = appendQuery(CfRequest.RECORD_LIST.buildPath(zone.getId()), RECORD_ORDER);
|
||||||
if (pagingRequest == null) {
|
if (pagingRequest == null) {
|
||||||
return filterAndSetZoneRecords(zone, null,
|
return filterAndSetZoneRecords(zone, null,
|
||||||
getAllPages(path, RecordMultipleResponse.class, recordsPerPage));
|
getAllPages(path, RecordMultipleResponse.class, recordsPerPage));
|
||||||
@@ -263,20 +329,24 @@ 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, 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)
|
||||||
throws CloudflareApiException {
|
throws CloudflareApiException {
|
||||||
String fqdn = buildFqdn(zone, subdomain);
|
String fqdn = buildFqdn(zone, subdomain);
|
||||||
String endpoint = addTypeFilter(CfRequest.RECORD_LIST_NAME.buildPath(zone.getId(), fqdn), types);
|
String endpoint = appendQuery(
|
||||||
|
addTypeFilter(CfRequest.RECORD_LIST_NAME.buildPath(zone.getId(), fqdn), types), RECORD_ORDER);
|
||||||
List<RecordEntity> recs = getAllPages(endpoint, RecordMultipleResponse.class, recordsPerPage);
|
List<RecordEntity> recs = getAllPages(endpoint, RecordMultipleResponse.class, recordsPerPage);
|
||||||
return filterAndSetZoneRecords(zone, types, recs);
|
return filterAndSetZoneRecords(zone, types, recs);
|
||||||
}
|
}
|
||||||
@@ -294,7 +364,8 @@ public class CfDnsClient extends CfBasicHttpClient {
|
|||||||
*/
|
*/
|
||||||
public List<RecordEntity> recordListByType(ZoneEntity zone, @Nullable RecordType... types)
|
public List<RecordEntity> recordListByType(ZoneEntity zone, @Nullable RecordType... types)
|
||||||
throws CloudflareApiException {
|
throws CloudflareApiException {
|
||||||
String endpoint = addTypeFilter(CfRequest.RECORD_LIST.buildPath(zone.getId()), types);
|
String endpoint = appendQuery(
|
||||||
|
addTypeFilter(CfRequest.RECORD_LIST.buildPath(zone.getId()), types), RECORD_ORDER);
|
||||||
List<RecordEntity> recs = getAllPages(endpoint, RecordMultipleResponse.class, recordsPerPage);
|
List<RecordEntity> recs = getAllPages(endpoint, RecordMultipleResponse.class, recordsPerPage);
|
||||||
return filterAndSetZoneRecords(zone, types, recs);
|
return filterAndSetZoneRecords(zone, types, recs);
|
||||||
}
|
}
|
||||||
@@ -303,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
|
||||||
@@ -312,6 +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, 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 {
|
||||||
@@ -319,26 +393,6 @@ public class CfDnsClient extends CfBasicHttpClient {
|
|||||||
return recordCreate(zone, fqdn, ttl, type, content);
|
return recordCreate(zone, fqdn, ttl, type, content);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 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 subdomain The subdomain relative to the zone.
|
|
||||||
* @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.
|
|
||||||
* @param content The content of the 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
|
|
||||||
* or creating the record.
|
|
||||||
* @deprecated The name was misleading, use
|
|
||||||
* {@link #recordCreateSubdomain(ZoneEntity, String, int, RecordType, String)} instead.
|
|
||||||
*/
|
|
||||||
@Deprecated(since = "0.6.0", forRemoval = true)
|
|
||||||
public RecordEntity recordCreateSld(ZoneEntity zone, String subdomain, int ttl, RecordType type,
|
|
||||||
String content) throws CloudflareApiException {
|
|
||||||
return recordCreateSubdomain(zone, subdomain, ttl, type, content);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a DNS record in the specified DNS zone with the provided details.
|
* Creates a DNS record in the specified DNS zone with the provided details.
|
||||||
*
|
*
|
||||||
@@ -444,13 +498,17 @@ public class CfDnsClient extends CfBasicHttpClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Deletes DNS records of a specific type within a given zone if they exist. If no record of the
|
* Attempts to delete DNS records of the specified types within a given zone. If no record types
|
||||||
* specified type exists, it logs this occurrence without throwing an exception.
|
* are specified, all types for the subdomain are selected. If no matching record exists, this is
|
||||||
|
* treated as a no-op. Deletions are attempted independently; an error deleting an individual
|
||||||
|
* record is logged and processing continues. No per-record result is returned, so a normal return
|
||||||
|
* does not guarantee that every selected record was deleted.
|
||||||
*
|
*
|
||||||
* @param zone The DNS zone entity in which the record exists.
|
* @param zone The DNS zone entity in which the record exists.
|
||||||
* @param subdomain The subdomain relative to the zone for which the records are being checked.
|
* @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.
|
* @param recordTypes The DNS record types to delete; if empty or {@code null}, all types are selected.
|
||||||
* @throws CloudflareApiException If an error occurs during API communication.
|
* @throws CloudflareApiException If an error occurs while retrieving the records to delete.
|
||||||
|
* @throws IllegalArgumentException if the subdomain is blank or contains invalid characters
|
||||||
*/
|
*/
|
||||||
public void recordDeleteTypeIfExists(ZoneEntity zone, String subdomain, RecordType... recordTypes)
|
public void recordDeleteTypeIfExists(ZoneEntity zone, String subdomain, RecordType... recordTypes)
|
||||||
throws CloudflareApiException {
|
throws CloudflareApiException {
|
||||||
@@ -575,7 +633,11 @@ public class CfDnsClient extends CfBasicHttpClient {
|
|||||||
if (types == null || types.length != 1 || types[0] == null) {
|
if (types == null || types.length != 1 || types[0] == null) {
|
||||||
return endpoint;
|
return endpoint;
|
||||||
}
|
}
|
||||||
return endpoint + (endpoint.contains("?") ? "&" : "?") + "type=" + types[0].getType();
|
return appendQuery(endpoint, "type=" + types[0].getType());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String appendQuery(String endpoint, String query) {
|
||||||
|
return endpoint + (endpoint.contains("?") ? "&" : "?") + query;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void setZoneForBatchResults(@Nullable BatchEntry result, ZoneEntity zone) {
|
private void setZoneForBatchResults(@Nullable BatchEntry result, ZoneEntity zone) {
|
||||||
@@ -600,27 +662,67 @@ public class CfDnsClient extends CfBasicHttpClient {
|
|||||||
/**
|
/**
|
||||||
* Fetches all pages of a paginated endpoint and returns the combined results.
|
* Fetches all pages of a paginated endpoint and returns the combined results.
|
||||||
*
|
*
|
||||||
|
* <p>Entries are de-duplicated by their ID. If fewer entries than announced by the API were
|
||||||
|
* fetched (e.g. because of concurrent changes), the pages are fetched again, up to
|
||||||
|
* {@value #MAX_PAGING_ATTEMPTS} times.
|
||||||
|
*
|
||||||
* @param endpoint the endpoint path, may already contain a query string
|
* @param endpoint the endpoint path, may already contain a query string
|
||||||
* @param responseType the expected response type
|
* @param responseType the expected response type
|
||||||
* @param perPage the page size to request
|
* @param perPage the page size to request
|
||||||
*/
|
*/
|
||||||
private <E extends ResponseEntity, R extends AbstractMultipleResponse<E>> List<E> getAllPages(
|
private <E extends ResponseEntity, R extends AbstractMultipleResponse<E>> List<E> getAllPages(
|
||||||
String endpoint, Class<R> responseType, int perPage) throws CloudflareApiException {
|
String endpoint, Class<R> responseType, int perPage) throws CloudflareApiException {
|
||||||
List<E> all = new ArrayList<>();
|
List<E> result = List.of();
|
||||||
int page = 1;
|
for (int attempt = 1; attempt <= MAX_PAGING_ATTEMPTS; attempt++) {
|
||||||
|
PagingResult<E> paged = fetchAllPagesOnce(endpoint, responseType, perPage);
|
||||||
|
result = paged.entries();
|
||||||
|
if (paged.expectedCount() < 0 || result.size() >= paged.expectedCount()) {
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
log.debug("Fetched {} of {} entries from {} (attempt {}), fetching again.", result.size(),
|
||||||
|
paged.expectedCount(), endpoint, attempt);
|
||||||
|
}
|
||||||
|
log.warn("Paging of {} was inconsistent, the result may be incomplete.", endpoint);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private record PagingResult<E>(List<E> entries, int expectedCount) {
|
||||||
|
}
|
||||||
|
|
||||||
|
private <E extends ResponseEntity, R extends AbstractMultipleResponse<E>> PagingResult<E> fetchAllPagesOnce(
|
||||||
|
String endpoint, Class<R> responseType, int perPage) throws CloudflareApiException {
|
||||||
|
Map<String, E> byId = new LinkedHashMap<>();
|
||||||
|
List<E> withoutId = new ArrayList<>();
|
||||||
|
int expectedCount = -1;
|
||||||
|
PagingRequest pagingRequest = new PagingRequest(1, perPage);
|
||||||
while (true) {
|
while (true) {
|
||||||
String pagedEndpoint = PagingRequest.of(page, perPage).addQueryString(endpoint);
|
int page = pagingRequest.page();
|
||||||
|
String pagedEndpoint = pagingRequest.addQueryString(endpoint);
|
||||||
R resp = getRequest(pagedEndpoint, responseType);
|
R resp = getRequest(pagedEndpoint, responseType);
|
||||||
checkResponse(resp);
|
checkResponse(resp);
|
||||||
List<E> result = resp.getResult();
|
List<E> pageResult = resp.getResult();
|
||||||
if (result != null) {
|
if (pageResult != null) {
|
||||||
all.addAll(result);
|
for (E entry : pageResult) {
|
||||||
|
if (entry.getId() == null) {
|
||||||
|
withoutId.add(entry);
|
||||||
|
} else {
|
||||||
|
byId.putIfAbsent(entry.getId(), entry);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
ResultInfo info = resp.getResultInfo();
|
ResultInfo info = resp.getResultInfo();
|
||||||
if (info == null || result == null || result.isEmpty() || page >= info.totalPages()) {
|
if (info != null && page == 1) {
|
||||||
return all;
|
expectedCount = info.totalCount();
|
||||||
}
|
}
|
||||||
page++;
|
log.debug("Fetched page {} of {} from {}: {} entries, total {}", page,
|
||||||
|
info == null ? "?" : info.totalPages(), endpoint,
|
||||||
|
pageResult == null ? 0 : pageResult.size(), info == null ? "?" : info.totalCount());
|
||||||
|
if (info == null || pageResult == null || pageResult.isEmpty() || page >= info.totalPages()) {
|
||||||
|
List<E> all = new ArrayList<>(byId.values());
|
||||||
|
all.addAll(withoutId);
|
||||||
|
return new PagingResult<>(all, info == null || page == 1 ? -1 : expectedCount);
|
||||||
|
}
|
||||||
|
pagingRequest = pagingRequest.next();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
package codes.thischwa.cf;
|
package codes.thischwa.cf;
|
||||||
|
|
||||||
|
import java.net.URI;
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.Locale;
|
||||||
import org.apache.hc.core5.http.ClassicHttpRequest;
|
import org.apache.hc.core5.http.ClassicHttpRequest;
|
||||||
import org.jetbrains.annotations.NotNull;
|
|
||||||
import org.jetbrains.annotations.Nullable;
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -16,8 +18,20 @@ public class CfDnsClientBuilder {
|
|||||||
*/
|
*/
|
||||||
public static final String DEFAULT_BASEURL = "https://api.cloudflare.com/client/v4";
|
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);
|
||||||
|
|
||||||
private boolean emptyResultThrowsException;
|
private boolean emptyResultThrowsException;
|
||||||
private CfAuth auth;
|
private CfAuth auth;
|
||||||
|
private Duration connectTimeout = DEFAULT_CONNECT_TIMEOUT;
|
||||||
|
private Duration responseTimeout = DEFAULT_RESPONSE_TIMEOUT;
|
||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
private String baseUrl;
|
private String baseUrl;
|
||||||
@@ -42,14 +56,91 @@ public class CfDnsClientBuilder {
|
|||||||
* Sets the base URL to be used by the {@code CfDnsClient}.
|
* 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.
|
* 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>Only HTTPS URLs with a host are accepted. User information, query parameters and fragments
|
||||||
|
* are not permitted. Credentials are sent to the configured host, so only use trusted URLs.
|
||||||
|
*
|
||||||
|
* @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
|
* @return the current instance of {@code CfDnsClientBuilder}, enabling method chaining
|
||||||
|
* @throws IllegalArgumentException if the URL is invalid, doesn't use HTTPS, has no host or
|
||||||
|
* contains user information, a query or a fragment
|
||||||
*/
|
*/
|
||||||
public CfDnsClientBuilder withBaseUrl(String baseUrl) {
|
public CfDnsClientBuilder withBaseUrl(@Nullable String baseUrl) {
|
||||||
this.baseUrl = baseUrl;
|
this.baseUrl = baseUrl == null ? null : validateBaseUrl(baseUrl);
|
||||||
return this;
|
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 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);
|
||||||
|
}
|
||||||
|
if (uri.getRawUserInfo() != null) {
|
||||||
|
throw new IllegalArgumentException("Base URL must not contain user information: " + baseUrl);
|
||||||
|
}
|
||||||
|
String scheme = uri.getScheme() == null ? "" : uri.getScheme().toLowerCase(Locale.ROOT);
|
||||||
|
if (!"https".equals(scheme)) {
|
||||||
|
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.
|
* 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
|
* This is the recommended way to authenticate with the Cloudflare API, as it provides
|
||||||
@@ -92,10 +183,16 @@ public class CfDnsClientBuilder {
|
|||||||
* @return a new instance of {@code CfDnsClient} configured with the
|
* @return a new instance of {@code CfDnsClient} configured with the
|
||||||
* specified options such as base URL, authentication details,
|
* specified options such as base URL, authentication details,
|
||||||
* and the exception-handling policy for empty results.
|
* and the exception-handling policy for empty results.
|
||||||
|
* @throws IllegalStateException if no authentication was configured
|
||||||
*/
|
*/
|
||||||
public CfDnsClient build() {
|
public CfDnsClient build() {
|
||||||
|
if (auth == null) {
|
||||||
|
throw new IllegalStateException(
|
||||||
|
"No authentication configured, use withApiTokenAuth(...) or withEmailKeyAuth(...)");
|
||||||
|
}
|
||||||
String url = baseUrl == null ? DEFAULT_BASEURL : baseUrl;
|
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 +225,8 @@ public class CfDnsClientBuilder {
|
|||||||
* @param apiToken the Cloudflare API token
|
* @param apiToken the Cloudflare API token
|
||||||
* @throws IllegalArgumentException if the API token is null or blank
|
* @throws IllegalArgumentException if the API token is null or blank
|
||||||
*/
|
*/
|
||||||
ApiTokenAuth(@NotNull String apiToken) {
|
ApiTokenAuth(String apiToken) {
|
||||||
if (apiToken.isBlank()) {
|
if (apiToken == null || apiToken.isBlank()) {
|
||||||
throw new IllegalArgumentException("API token must not be null or blank!");
|
throw new IllegalArgumentException("API token must not be null or blank!");
|
||||||
}
|
}
|
||||||
this.apiToken = apiToken;
|
this.apiToken = apiToken;
|
||||||
@@ -157,11 +254,11 @@ public class CfDnsClientBuilder {
|
|||||||
* @param authKey the API key of the Cloudflare account
|
* @param authKey the API key of the Cloudflare account
|
||||||
* @throws IllegalArgumentException if email or key is null or blank
|
* @throws IllegalArgumentException if email or key is null or blank
|
||||||
*/
|
*/
|
||||||
EmailKeyAuth(@NotNull String authEmail, @NotNull String authKey) {
|
EmailKeyAuth(String authEmail, String authKey) {
|
||||||
if (authEmail.isBlank()) {
|
if (authEmail == null || authEmail.isBlank()) {
|
||||||
throw new IllegalArgumentException("Authentication email must not be null or blank!");
|
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!");
|
throw new IllegalArgumentException("Authentication key must not be null or blank!");
|
||||||
}
|
}
|
||||||
this.authEmail = authEmail;
|
this.authEmail = authEmail;
|
||||||
|
|||||||
@@ -1,5 +1,9 @@
|
|||||||
package codes.thischwa.cf;
|
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;
|
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
|
* name. The endpoint path supports a placeholder for the zone name, which needs to be provided to
|
||||||
* construct the complete path.
|
* 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
|
* 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
|
* specific DNS zone. The endpoint path includes a placeholder for the zone identifier, which
|
||||||
* needs to be provided to construct the complete path.
|
* 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
|
* 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
|
* 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.
|
* 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
|
* 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
|
* endpoint path includes a placeholder for the zone identifier, which needs to be provided to
|
||||||
* construct the complete path.
|
* 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
|
* 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
|
* zone. The endpoint path includes placeholders for the zone identifier and the record
|
||||||
* identifier, which need to be provided to construct the complete path.
|
* 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.
|
* 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.
|
* 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
|
* 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
|
* zone. The endpoint path includes placeholders for the zone identifier and the record
|
||||||
* identifier, which need to be provided to construct the complete path.
|
* 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;
|
private final String path;
|
||||||
|
|
||||||
CfRequest(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
|
* Constructs the complete API endpoint path by replacing the placeholders with the provided
|
||||||
* arguments.
|
* 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
|
* @param vars the arguments to replace the placeholders with, in the order of the placeholders
|
||||||
* identifiers or parameters required by the API endpoint.
|
|
||||||
* @return the fully constructed API endpoint path as a string.
|
* @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) {
|
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) {
|
if (varCount != vars.length) {
|
||||||
throw new IllegalArgumentException(
|
throw new IllegalArgumentException(
|
||||||
String.format(
|
String.format(
|
||||||
"The number of variables (%d) does not match the number of parameters (%d) in the path string: %s",
|
"The number of variables (%d) does not match the number of parameters (%d) in the path string: %s",
|
||||||
vars.length, varCount, path));
|
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();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -40,10 +40,15 @@ public interface RecordOperations {
|
|||||||
RecordEntity update(String newContent) throws CloudflareApiException;
|
RecordEntity update(String newContent) throws CloudflareApiException;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Deletes DNS records of the specified types.
|
* Deletes DNS records of the specified types for the selected subdomain. The types passed here
|
||||||
|
* determine which records are deleted, independently of any type filter used to select the
|
||||||
|
* subdomain. If no types are specified, records of all types for that subdomain are selected for
|
||||||
|
* deletion. A {@link CloudflareApiException} from an individual deletion is logged and does not
|
||||||
|
* stop later attempts. No per-record result is returned, so returning normally does not guarantee
|
||||||
|
* that all selected records were deleted.
|
||||||
*
|
*
|
||||||
* @param types the DNS record types to delete
|
* @param types the DNS record types to delete
|
||||||
* @throws CloudflareApiException if an error occurs while deleting records
|
* @throws CloudflareApiException if an error occurs while retrieving records to delete
|
||||||
*/
|
*/
|
||||||
void delete(RecordType... types) throws CloudflareApiException;
|
void delete(RecordType... types) throws CloudflareApiException;
|
||||||
}
|
}
|
||||||
@@ -21,6 +21,10 @@ 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>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
|
||||||
|
* for the selected subdomain. A {@link CloudflareApiException} from an individual deletion is
|
||||||
|
* logged and does not stop later attempts; see {@link RecordOperations#delete(RecordType...)}.
|
||||||
*
|
*
|
||||||
* @param subdomain the subdomain relative to the zone (e.g. "www"), or "@" for the zone apex
|
* @param subdomain the subdomain relative to the zone (e.g. "www"), or "@" for the zone apex
|
||||||
* @param types optional DNS record types to filter by
|
* @param types optional DNS record types to filter by
|
||||||
@@ -32,7 +36,7 @@ public interface ZoneOperations {
|
|||||||
/**
|
/**
|
||||||
* Lists all DNS records within the zone, optionally filtered by types.
|
* Lists all DNS records within the zone, optionally filtered by types.
|
||||||
*
|
*
|
||||||
* @param types optional DNS record types to filter by
|
* @param types optional DNS record types to filter by
|
||||||
* @return a list of RecordEntity objects matching the criteria
|
* @return a list of RecordEntity objects matching the criteria
|
||||||
* @throws CloudflareApiException if an error occurs while retrieving records
|
* @throws CloudflareApiException if an error occurs while retrieving records
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -1,83 +1,112 @@
|
|||||||
package codes.thischwa.cf.model;
|
package codes.thischwa.cf.model;
|
||||||
|
|
||||||
import java.util.Map;
|
import java.util.Objects;
|
||||||
import lombok.Data;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Represents a request model for paginated data.
|
* Immutable pagination parameters for Cloudflare list endpoints. Page numbers start at 1.
|
||||||
*
|
*
|
||||||
* <p>This class encapsulates the page number and the number of items per page for a paginated
|
* <p>Use {@link #forZones(int, int)} for zone requests and {@link #forRecords(int, int)} for DNS
|
||||||
* request, along with utility methods for constructing and retrieving pagination parameters.
|
* record requests. For example:
|
||||||
*
|
*
|
||||||
* <p>Key functionalities:
|
* <pre>{@code
|
||||||
*
|
* List<RecordEntity> records = client.recordList(zone, PagingRequest.forRecords(1, 100));
|
||||||
* <ul>
|
* List<ZoneEntity> zones = client.zoneList(PagingRequest.forZones(1, 50));
|
||||||
* <li>Creating a {@code PagingRequest} instance with specific pagination values using the {@code
|
* }</pre>
|
||||||
* of} method.
|
|
||||||
* <li>Creating a default {@code PagingRequest} with predefined pagination values.
|
|
||||||
* <li>Retrieving pagination parameters as a key-value map.
|
|
||||||
* <li>Generating a query string representation for the pagination parameters.
|
|
||||||
* </ul>
|
|
||||||
*/
|
*/
|
||||||
@Data
|
public record PagingRequest(int page, int perPage) {
|
||||||
public class PagingRequest {
|
|
||||||
/**
|
|
||||||
* Default page size for retrieving all records in a single request.
|
|
||||||
* Set to a very high value to effectively disable pagination when fetching all records.
|
|
||||||
*/
|
|
||||||
private static final int DEFAULT_ALL_RECORDS_PAGE_SIZE = 1000;
|
|
||||||
|
|
||||||
private int page;
|
/** Default page size, valid for zones and DNS records. */
|
||||||
private int perPage;
|
public static final int DEFAULT_PAGE_SIZE = 50;
|
||||||
|
|
||||||
PagingRequest(int page, int perPage) {
|
/** Maximum number of DNS records allowed per page by Cloudflare. */
|
||||||
this.page = page;
|
public static final int MAX_RECORDS_PER_PAGE = 5_000_000;
|
||||||
this.perPage = perPage;
|
|
||||||
|
/** Minimum number of zones allowed per page by Cloudflare. */
|
||||||
|
public static final int MIN_ZONES_PER_PAGE = 5;
|
||||||
|
|
||||||
|
/** Maximum number of zones allowed per page by Cloudflare. */
|
||||||
|
public static final int MAX_ZONES_PER_PAGE = 50;
|
||||||
|
|
||||||
|
/** Validates the page number and page size. */
|
||||||
|
public PagingRequest {
|
||||||
|
if (page < 1) {
|
||||||
|
throw new IllegalArgumentException("page must be at least 1, but was " + page);
|
||||||
|
}
|
||||||
|
if (perPage < 1 || perPage > MAX_RECORDS_PER_PAGE) {
|
||||||
|
throw new IllegalArgumentException("perPage must be between 1 and " + MAX_RECORDS_PER_PAGE
|
||||||
|
+ ", but was " + perPage);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a new {@code PagingRequest} instance with the specified page number and items per page.
|
* Creates pagination parameters for a DNS record request.
|
||||||
*
|
*
|
||||||
* @param page the page number to be requested
|
* @param page the 1-based page number
|
||||||
* @param perPage the number of items to be included per page
|
* @param perPage the number of records per page, from 1 to {@value #MAX_RECORDS_PER_PAGE}
|
||||||
* @return a new {@code PagingRequest} instance with the provided parameters
|
* @return the validated pagination request
|
||||||
|
* @throws IllegalArgumentException if either value is outside its allowed range
|
||||||
*/
|
*/
|
||||||
public static PagingRequest of(int page, int perPage) {
|
public static PagingRequest forRecords(int page, int perPage) {
|
||||||
return new PagingRequest(page, perPage);
|
return new PagingRequest(page, perPage);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a default {@code PagingRequest} instance with a page number set to 1 and a high number
|
* Creates pagination parameters for a zone request.
|
||||||
* of items per page to accommodate large dataset requests and effectively retrieve all records.
|
|
||||||
*
|
*
|
||||||
* @return a default {@code PagingRequest} instance with predefined pagination parameters
|
* @param page the 1-based page number
|
||||||
|
* @param perPage the number of zones per page, from {@value #MIN_ZONES_PER_PAGE} to
|
||||||
|
* {@value #MAX_ZONES_PER_PAGE}
|
||||||
|
* @return the validated pagination request
|
||||||
|
* @throws IllegalArgumentException if either value is outside its allowed range
|
||||||
|
*/
|
||||||
|
public static PagingRequest forZones(int page, int perPage) {
|
||||||
|
if (perPage < MIN_ZONES_PER_PAGE || perPage > MAX_ZONES_PER_PAGE) {
|
||||||
|
throw new IllegalArgumentException("Zone page size must be between " + MIN_ZONES_PER_PAGE
|
||||||
|
+ " and " + MAX_ZONES_PER_PAGE + ", but was " + perPage);
|
||||||
|
}
|
||||||
|
return new PagingRequest(page, perPage);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a request for page 1 with {@value #DEFAULT_PAGE_SIZE} items per page.
|
||||||
|
* This requests one page; it does not fetch additional pages.
|
||||||
|
*
|
||||||
|
* @return the default pagination request
|
||||||
*/
|
*/
|
||||||
public static PagingRequest defaultPaging() {
|
public static PagingRequest defaultPaging() {
|
||||||
return new PagingRequest(1, DEFAULT_ALL_RECORDS_PAGE_SIZE);
|
return new PagingRequest(1, DEFAULT_PAGE_SIZE);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieves the pagination parameters in a key-value map format.
|
* Returns a request for the next page, retaining the current page size.
|
||||||
*
|
*
|
||||||
* @return a map containing the pagination parameters, where the key "page" indicates the current
|
* @return the next page request
|
||||||
* page number and the key "perPage" indicates the number of items per page.
|
|
||||||
*/
|
*/
|
||||||
public Map<String, String> getPagingParams() {
|
public PagingRequest next() {
|
||||||
return Map.of("page", String.valueOf(page), "perPage", String.valueOf(perPage));
|
return new PagingRequest(page + 1, perPage);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Appends a query string with pagination parameters (page and perPage) to the provided endpoint.
|
* Returns a copy of this request with the specified page number.
|
||||||
*
|
*
|
||||||
* @param endpoint the base URL or API endpoint to which the query string will be appended
|
* @param page the 1-based page number
|
||||||
* @return the complete URL with the appended query string for pagination
|
* @return the updated pagination request
|
||||||
|
*/
|
||||||
|
public PagingRequest withPage(int page) {
|
||||||
|
return new PagingRequest(page, perPage);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Appends Cloudflare-compatible pagination parameters ({@code page} and {@code per_page}) to an
|
||||||
|
* endpoint.
|
||||||
|
*
|
||||||
|
* @param endpoint the base URL or API endpoint, optionally containing a query string
|
||||||
|
* @return the endpoint with pagination parameters appended
|
||||||
|
* @throws NullPointerException if {@code endpoint} is {@code null}
|
||||||
*/
|
*/
|
||||||
public String addQueryString(String endpoint) {
|
public String addQueryString(String endpoint) {
|
||||||
return endpoint + queryString(endpoint.contains("?"));
|
Objects.requireNonNull(endpoint, "endpoint must not be null");
|
||||||
}
|
return endpoint + (endpoint.contains("?") ? "&" : "?")
|
||||||
|
+ "page=" + page + "&per_page=" + perPage;
|
||||||
private String queryString(boolean add) {
|
|
||||||
String qs = "page=" + page + "&per_page=" + perPage;
|
|
||||||
return add ? "&" + qs : "?" + qs;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -11,7 +11,9 @@ import com.sun.net.httpserver.HttpServer;
|
|||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.OutputStream;
|
import java.io.OutputStream;
|
||||||
import java.net.InetSocketAddress;
|
import java.net.InetSocketAddress;
|
||||||
|
import java.net.SocketTimeoutException;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.time.Duration;
|
||||||
import java.util.concurrent.atomic.AtomicInteger;
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
import org.junit.jupiter.api.AfterEach;
|
import org.junit.jupiter.api.AfterEach;
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
@@ -33,12 +35,20 @@ class CfBasicHttpClientErrorTest {
|
|||||||
private final AtomicInteger requestCount = new AtomicInteger();
|
private final AtomicInteger requestCount = new AtomicInteger();
|
||||||
private volatile int status;
|
private volatile int status;
|
||||||
private volatile String body;
|
private volatile String body;
|
||||||
|
private volatile long delayMillis;
|
||||||
|
|
||||||
@BeforeEach
|
@BeforeEach
|
||||||
void setUp() throws IOException {
|
void setUp() throws IOException {
|
||||||
server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
|
server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
|
||||||
server.createContext("/", exchange -> {
|
server.createContext("/", exchange -> {
|
||||||
requestCount.incrementAndGet();
|
requestCount.incrementAndGet();
|
||||||
|
if (delayMillis > 0) {
|
||||||
|
try {
|
||||||
|
Thread.sleep(delayMillis);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
}
|
||||||
|
}
|
||||||
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
|
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
|
||||||
exchange.sendResponseHeaders(status, bytes.length);
|
exchange.sendResponseHeaders(status, bytes.length);
|
||||||
try (OutputStream out = exchange.getResponseBody()) {
|
try (OutputStream out = exchange.getResponseBody()) {
|
||||||
@@ -46,10 +56,8 @@ class CfBasicHttpClientErrorTest {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
server.start();
|
server.start();
|
||||||
client = new CfDnsClientBuilder()
|
client = new CfDnsClient(false, "http://localhost:" + server.getAddress().getPort(),
|
||||||
.withApiTokenAuth("test-token")
|
new CfDnsClientBuilder.ApiTokenAuth("test-token"));
|
||||||
.withBaseUrl("http://localhost:" + server.getAddress().getPort())
|
|
||||||
.build();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@AfterEach
|
@AfterEach
|
||||||
@@ -125,4 +133,22 @@ class CfBasicHttpClientErrorTest {
|
|||||||
assertEquals(CloudflareApiException.NO_STATUS_CODE, e.getStatusCode());
|
assertEquals(CloudflareApiException.NO_STATUS_CODE, e.getStatusCode());
|
||||||
assertTrue(e.getErrors().isEmpty());
|
assertTrue(e.getErrors().isEmpty());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void responseTimeoutIsApplied() throws Exception {
|
||||||
|
respond(200, ZONE_JSON);
|
||||||
|
delayMillis = 2000;
|
||||||
|
try (CfDnsClient timeoutClient = new CfDnsClient(false,
|
||||||
|
"http://localhost:" + server.getAddress().getPort(),
|
||||||
|
new CfDnsClientBuilder.ApiTokenAuth("test-token"), CfDnsClient.RECORDS_PER_PAGE,
|
||||||
|
CfDnsClientBuilder.DEFAULT_CONNECT_TIMEOUT, Duration.ofMillis(200))) {
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+165
-54
@@ -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";
|
||||||
@@ -43,6 +44,9 @@ public class CfClientTest {
|
|||||||
private static final String IP_PREFIX = "130.0.0.";
|
private static final String IP_PREFIX = "130.0.0.";
|
||||||
private static final String UPDATED_IP_PREFIX = "130.1.0.";
|
private static final String UPDATED_IP_PREFIX = "130.1.0.";
|
||||||
|
|
||||||
|
private record PagedResult(int total, Set<String> allIds, List<List<RecordEntity>> pages) {
|
||||||
|
}
|
||||||
|
|
||||||
@BeforeAll
|
@BeforeAll
|
||||||
static void checkEnv() {
|
static void checkEnv() {
|
||||||
assumeTrue(API_TOKEN != null && !API_TOKEN.isBlank(), "API_TOKEN not set; skipping client tests");
|
assumeTrue(API_TOKEN != null && !API_TOKEN.isBlank(), "API_TOKEN not set; skipping client tests");
|
||||||
@@ -109,7 +113,7 @@ public class CfClientTest {
|
|||||||
assertFalse(zones.isEmpty());
|
assertFalse(zones.isEmpty());
|
||||||
assertEquals(ZONE_STR, zones.get(0).getName());
|
assertEquals(ZONE_STR, zones.get(0).getName());
|
||||||
|
|
||||||
zones = client.zoneList(PagingRequest.of(1, 100));
|
zones = client.zoneList(PagingRequest.forZones(1, 50));
|
||||||
assertNotNull(zones);
|
assertNotNull(zones);
|
||||||
assertFalse(zones.isEmpty());
|
assertFalse(zones.isEmpty());
|
||||||
assertEquals(ZONE_STR, zones.get(0).getName());
|
assertEquals(ZONE_STR, zones.get(0).getName());
|
||||||
@@ -194,8 +198,9 @@ public class CfClientTest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// test recordList without SLD
|
// test recordList without SLD (the unfiltered list may lag behind directly after creating records)
|
||||||
List<RecordEntity> fullList = client.recordList(z);
|
List<RecordEntity> fullList = awaitRecords(() -> client.recordList(z),
|
||||||
|
recs -> recs.stream().anyMatch(re -> re.getId().equals(createdRe2.getId())));
|
||||||
assertTrue(fullList.size() >= 2);
|
assertTrue(fullList.size() >= 2);
|
||||||
assertTrue(fullList.stream().anyMatch(re -> re.getId().equals(createdRe1.getId())));
|
assertTrue(fullList.stream().anyMatch(re -> re.getId().equals(createdRe1.getId())));
|
||||||
assertTrue(fullList.stream().anyMatch(re -> re.getId().equals(createdRe2.getId())));
|
assertTrue(fullList.stream().anyMatch(re -> re.getId().equals(createdRe2.getId())));
|
||||||
@@ -203,7 +208,8 @@ public class CfClientTest {
|
|||||||
fullList.stream().allMatch(re -> re.getType().equals(RecordType.A.getType()) || re.getType().equals(RecordType.AAAA.getType())));
|
fullList.stream().allMatch(re -> re.getType().equals(RecordType.A.getType()) || re.getType().equals(RecordType.AAAA.getType())));
|
||||||
|
|
||||||
// test recordList with types without SLD
|
// test recordList with types without SLD
|
||||||
List<RecordEntity> aList = client.recordListByType(z, RecordType.A);
|
List<RecordEntity> aList = awaitRecords(() -> client.recordListByType(z, RecordType.A),
|
||||||
|
recs -> recs.stream().anyMatch(re -> re.getId().equals(createdRe1.getId())));
|
||||||
assertFalse(aList.isEmpty());
|
assertFalse(aList.isEmpty());
|
||||||
assertTrue(aList.stream().anyMatch(re -> re.getId().equals(createdRe1.getId())));
|
assertTrue(aList.stream().anyMatch(re -> re.getId().equals(createdRe1.getId())));
|
||||||
assertTrue(aList.stream().noneMatch(re -> re.getId().equals(createdRe2.getId())));
|
assertTrue(aList.stream().noneMatch(re -> re.getId().equals(createdRe2.getId())));
|
||||||
@@ -468,80 +474,121 @@ public class CfClientTest {
|
|||||||
assertEquals(2, groupedRecords.get("example.com.").size(), "The key 'example.com.' should have 2 records.");
|
assertEquals(2, groupedRecords.get("example.com.").size(), "The key 'example.com.' should have 2 records.");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testPaging() throws Exception {
|
void testPaging() throws Exception {
|
||||||
ZoneEntity zone = client.zoneGet(ZONE_STR);
|
ZoneEntity zone = client.zoneGet(ZONE_STR);
|
||||||
String pagingSld = "paging-" + System.currentTimeMillis();
|
String pagingSld = "paging-" + System.currentTimeMillis();
|
||||||
|
List<RecordEntity> createdRecords = new ArrayList<>();
|
||||||
|
Set<String> createdIds = new HashSet<>();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
int existingCount = 0;
|
List<RecordEntity> staleRecords = List.of();
|
||||||
try {
|
try {
|
||||||
List<RecordEntity> allRecords = client.recordList(zone);
|
staleRecords = client.recordList(zone).stream()
|
||||||
existingCount = allRecords.size();
|
.filter(record -> record.getName() != null && record.getName().startsWith("paging-"))
|
||||||
} catch (CloudflareApiException e) {
|
.toList();
|
||||||
// ignore
|
} catch (CloudflareNotFoundException ignored) {
|
||||||
|
// The zone is empty.
|
||||||
}
|
}
|
||||||
|
deleteQuietly(zone, staleRecords);
|
||||||
|
|
||||||
// Calculate how many records we need to create to reach at least 12 total A records
|
// Each record gets its own name, so the order by name is unambiguous.
|
||||||
// (to test paging with pageSize 5: page 1 = 5, page 2 = 5, page 3 = 2+)
|
for (int i = 1; i <= 12; i++) {
|
||||||
int targetCount = 12;
|
String name = String.format("%s-%02d.%s", pagingSld, i, ZONE_STR);
|
||||||
int recordsToCreate = Math.max(0, targetCount - existingCount);
|
RecordEntity record = RecordEntity.build(name, RecordType.A, TTL, "127.0.0." + i);
|
||||||
|
|
||||||
// Create additional A records if needed
|
|
||||||
List<RecordEntity> createdRecords = new ArrayList<>();
|
|
||||||
for (int i = 1; i <= recordsToCreate; i++) {
|
|
||||||
RecordEntity record = RecordEntity.build(pagingSld, RecordType.A, TTL, "127.0.0." + i);
|
|
||||||
RecordEntity created = client.recordCreate(zone, record);
|
RecordEntity created = client.recordCreate(zone, record);
|
||||||
createdRecords.add(created);
|
createdRecords.add(created);
|
||||||
assertNotNull(created.getId());
|
assertNotNull(created.getId());
|
||||||
|
createdIds.add(created.getId());
|
||||||
}
|
}
|
||||||
|
|
||||||
// Test paging with page size of 5
|
PagedResult pagedResult = pageThrough(zone, createdIds, 5);
|
||||||
PagingRequest page1Request = PagingRequest.of(1, 5);
|
List<String> pagedIds = pagedResult.pages().stream()
|
||||||
List<RecordEntity> page1Records = client.recordList(zone, page1Request);
|
.flatMap(List::stream)
|
||||||
assertEquals(5, page1Records.size(), "First page should contain 5 records");
|
.map(RecordEntity::getId)
|
||||||
|
.toList();
|
||||||
|
Set<String> pagedIdSet = new HashSet<>(pagedIds);
|
||||||
|
|
||||||
// 2nd page should also contain 5 records (if we have at least 12 total)
|
for (int page = 1; page <= pagedResult.pages().size(); page++) {
|
||||||
PagingRequest page2Request = PagingRequest.of(2, 5);
|
int expected = Math.max(0, Math.min(5,
|
||||||
List<RecordEntity> page2Records = client.recordList(zone, page2Request);
|
pagedResult.total() - 5 * (page - 1)));
|
||||||
assertEquals(5, page2Records.size(), "Second page should contain at least 5 records");
|
assertEquals(expected, pagedResult.pages().get(page - 1).size(),
|
||||||
|
"Page " + page + " should contain " + expected + " records");
|
||||||
|
}
|
||||||
|
assertTrue(pagedResult.pages().get(pagedResult.pages().size() - 1).isEmpty(),
|
||||||
|
"The page after the last result page should be empty");
|
||||||
|
assertEquals(pagedIds.size(), pagedIdSet.size(), "Pages should not overlap");
|
||||||
|
assertEquals(pagedResult.allIds(), pagedIdSet,
|
||||||
|
"Pages should contain every record in the zone");
|
||||||
|
assertTrue(pagedResult.allIds().containsAll(createdIds),
|
||||||
|
"The paged records should contain all records created by this test");
|
||||||
|
|
||||||
// 3rd page should contain 2 records
|
List<String> createdNamesInPageOrder = pagedResult.pages().stream()
|
||||||
PagingRequest page3Request = PagingRequest.of(3, 5);
|
.flatMap(List::stream)
|
||||||
List<RecordEntity> page3Records = client.recordList(zone, page3Request);
|
.filter(record -> createdIds.contains(record.getId()))
|
||||||
assertEquals(2, page3Records.size(), "Third page should contain 2 records");
|
.map(RecordEntity::getName)
|
||||||
|
.toList();
|
||||||
// Verify no overlap between pages
|
assertEquals(createdRecords.stream().map(RecordEntity::getName).toList(),
|
||||||
List<String> page1Ids = page1Records.stream().map(RecordEntity::getId).toList();
|
createdNamesInPageOrder, "The test records should be sorted by name");
|
||||||
List<String> page2Ids = page2Records.stream().map(RecordEntity::getId).toList();
|
|
||||||
List<String> page3Ids = page3Records.stream().map(RecordEntity::getId).toList();
|
|
||||||
Set<String> generatedRecordIds = new HashSet<>(page1Ids);
|
|
||||||
generatedRecordIds.addAll(page2Ids);
|
|
||||||
generatedRecordIds.addAll(page3Ids);
|
|
||||||
assertEquals(createdRecords.size(), generatedRecordIds.size());
|
|
||||||
|
|
||||||
// Verify our created records are in the zone
|
|
||||||
List<RecordEntity> allRecords = client.recordList(zone);
|
|
||||||
Set<String> allRecordIds = allRecords.stream().map(RecordEntity::getId).collect(Collectors.toSet());
|
|
||||||
assertEquals(createdRecords.size(), allRecordIds.size());
|
|
||||||
assertTrue(allRecordIds.containsAll(generatedRecordIds));
|
|
||||||
|
|
||||||
// Without PagingRequest all pages must be fetched, also if the page size is small
|
// Without PagingRequest all pages must be fetched, also if the page size is small
|
||||||
try (CfDnsClient smallPageClient = new CfDnsClient(true, CfDnsClientBuilder.DEFAULT_BASEURL,
|
try (CfDnsClient smallPageClient = new CfDnsClient(true, CfDnsClientBuilder.DEFAULT_BASEURL,
|
||||||
new CfDnsClientBuilder.ApiTokenAuth(API_TOKEN), 5)) {
|
new CfDnsClientBuilder.ApiTokenAuth(API_TOKEN), 5)) {
|
||||||
assertEquals(allRecordIds, smallPageClient.recordList(zone).stream()
|
List<RecordEntity> allRecords = awaitRecords(() -> smallPageClient.recordList(zone),
|
||||||
.map(RecordEntity::getId).collect(Collectors.toSet()));
|
recs -> ids(recs).containsAll(createdIds));
|
||||||
assertEquals(createdRecords.size(), smallPageClient.recordListBySubdomain(zone, pagingSld).size());
|
assertTrue(ids(allRecords).containsAll(createdIds));
|
||||||
assertEquals(createdRecords.size(), smallPageClient.recordListByType(zone, RecordType.A).size());
|
List<RecordEntity> aRecords = awaitRecords(
|
||||||
|
() -> smallPageClient.recordListByType(zone, RecordType.A),
|
||||||
|
recs -> ids(recs).containsAll(createdIds));
|
||||||
|
assertTrue(ids(aRecords).containsAll(createdIds));
|
||||||
|
assertEquals(1, smallPageClient.recordListBySubdomain(zone, pagingSld + "-01").size());
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
try {
|
deleteQuietly(zone, createdRecords);
|
||||||
client.recordDeleteTypeIfExists(zone, pagingSld, RecordType.A);
|
|
||||||
} catch (Exception e) { /* ignore */ }
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static Set<String> ids(List<RecordEntity> records) {
|
||||||
|
return records.stream().map(RecordEntity::getId).collect(Collectors.toSet());
|
||||||
|
}
|
||||||
|
|
||||||
|
private PagedResult pageThrough(ZoneEntity zone, Set<String> createdIds, int pageSize)
|
||||||
|
throws CloudflareApiException, InterruptedException {
|
||||||
|
PagedResult result = null;
|
||||||
|
for (int attempt = 1; attempt <= 3; attempt++) {
|
||||||
|
List<RecordEntity> allRecords = awaitRecords(() -> client.recordList(zone),
|
||||||
|
records -> ids(records).containsAll(createdIds));
|
||||||
|
int total = allRecords.size();
|
||||||
|
Set<String> allIds = ids(allRecords);
|
||||||
|
List<List<RecordEntity>> pages = new ArrayList<>();
|
||||||
|
List<String> pagedIds = new ArrayList<>();
|
||||||
|
int pageCount = (total + pageSize - 1) / pageSize + 1;
|
||||||
|
boolean pageSizesMatch = true;
|
||||||
|
|
||||||
|
for (int page = 1; page <= pageCount; page++) {
|
||||||
|
int currentPage = page;
|
||||||
|
int expected = Math.max(0, Math.min(pageSize, total - pageSize * (page - 1)));
|
||||||
|
List<RecordEntity> pageRecords = awaitRecords(
|
||||||
|
() -> client.recordList(zone, PagingRequest.forRecords(currentPage, pageSize)),
|
||||||
|
records -> records.size() == expected);
|
||||||
|
pages.add(pageRecords);
|
||||||
|
pagedIds.addAll(pageRecords.stream().map(RecordEntity::getId).toList());
|
||||||
|
if (pageRecords.size() != expected) {
|
||||||
|
pageSizesMatch = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
result = new PagedResult(total, allIds, pages);
|
||||||
|
if (pageSizesMatch && new HashSet<>(pagedIds).equals(allIds)) {
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
if (attempt < 3) {
|
||||||
|
Thread.sleep(1000);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testApiErrorDetails() throws Exception {
|
void testApiErrorDetails() throws Exception {
|
||||||
ZoneEntity zone = client.zoneGet(ZONE_STR);
|
ZoneEntity zone = client.zoneGet(ZONE_STR);
|
||||||
@@ -635,6 +682,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);
|
||||||
@@ -724,4 +804,35 @@ public class CfClientTest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@FunctionalInterface
|
||||||
|
private interface RecordQuery {
|
||||||
|
List<RecordEntity> get() throws CloudflareApiException;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Repeats the query until the condition is met. The unfiltered record list of Cloudflare can lag
|
||||||
|
* behind for a short time after records were created.
|
||||||
|
*/
|
||||||
|
private static List<RecordEntity> awaitRecords(RecordQuery query,
|
||||||
|
java.util.function.Predicate<List<RecordEntity>> condition)
|
||||||
|
throws CloudflareApiException, InterruptedException {
|
||||||
|
List<RecordEntity> recs = List.of();
|
||||||
|
for (int attempt = 1; attempt <= 10; attempt++) {
|
||||||
|
try {
|
||||||
|
recs = query.get();
|
||||||
|
if (condition.test(recs)) {
|
||||||
|
return recs;
|
||||||
|
}
|
||||||
|
} catch (CloudflareNotFoundException e) {
|
||||||
|
recs = List.of();
|
||||||
|
if (condition.test(recs)) {
|
||||||
|
return recs;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
log.info("Records not yet listed (attempt {}), waiting ...", attempt);
|
||||||
|
Thread.sleep(1000);
|
||||||
|
}
|
||||||
|
return recs;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -4,6 +4,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
|
|||||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
|
||||||
|
import java.lang.reflect.Method;
|
||||||
|
import java.time.Duration;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -124,18 +126,6 @@ class CfDnsClientBuilderTest {
|
|||||||
assertNotNull(client);
|
assertNotNull(client);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
|
||||||
void testBuilderWithMultipleBaseUrls() {
|
|
||||||
// Test setting base URL multiple times (last one wins)
|
|
||||||
CfDnsClient client = new CfDnsClientBuilder()
|
|
||||||
.withApiTokenAuth("test-token")
|
|
||||||
.withBaseUrl("https://old-api.example.com")
|
|
||||||
.withBaseUrl("https://new-api.example.com") // This should override
|
|
||||||
.build();
|
|
||||||
|
|
||||||
assertNotNull(client);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testEmptyResultThrowsExceptionToggle() {
|
void testEmptyResultThrowsExceptionToggle() {
|
||||||
// Test toggling the flag multiple times (last one wins)
|
// Test toggling the flag multiple times (last one wins)
|
||||||
@@ -147,4 +137,65 @@ class CfDnsClientBuilderTest {
|
|||||||
|
|
||||||
assertNotNull(client);
|
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 testBaseUrlAllowsOnlyCloudflareHttps() {
|
||||||
|
assertNotNull(new CfDnsClientBuilder().withApiTokenAuth("t")
|
||||||
|
.withBaseUrl("HTTPS://API.CLOUDFLARE.COM/client/v4/").build());
|
||||||
|
assertNotNull(new CfDnsClientBuilder().withApiTokenAuth("t").withBaseUrl(null).build());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testBaseUrlTrailingSlashIsRemoved() throws ReflectiveOperationException {
|
||||||
|
Method validateBaseUrl = CfDnsClientBuilder.class.getDeclaredMethod("validateBaseUrl", String.class);
|
||||||
|
validateBaseUrl.setAccessible(true);
|
||||||
|
|
||||||
|
assertEquals("HTTPS://API.CLOUDFLARE.COM/client/v4",
|
||||||
|
validateBaseUrl.invoke(null, "HTTPS://API.CLOUDFLARE.COM/client/v4/"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@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());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -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;
|
||||||
|
|
||||||
@@ -119,6 +120,34 @@ class CfDnsClientMockTest {
|
|||||||
assertEquals("test.com", zones.get(1).getName());
|
assertEquals("test.com", zones.get(1).getName());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testZoneList_WithPagingEnforcesApiLimits() throws Exception {
|
||||||
|
ZoneMultipleResponse mockResponse = new ZoneMultipleResponse();
|
||||||
|
mockResponse.setResult(List.of());
|
||||||
|
mockResponse.setResponseResultInfo(createSuccessResultInfo());
|
||||||
|
|
||||||
|
CfDnsClient spyClient = spy(client);
|
||||||
|
doReturn(mockResponse).when(spyClient).getRequest(anyString(), eq(ZoneMultipleResponse.class));
|
||||||
|
|
||||||
|
spyClient.zoneList(PagingRequest.forZones(1, 5));
|
||||||
|
spyClient.zoneList(PagingRequest.forZones(1, 50));
|
||||||
|
|
||||||
|
verify(spyClient).getRequest(eq("/zones?page=1&per_page=5"), eq(ZoneMultipleResponse.class));
|
||||||
|
verify(spyClient).getRequest(eq("/zones?page=1&per_page=50"), eq(ZoneMultipleResponse.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testZoneList_WithPagingRejectsOutOfRangePageSizes() throws Exception {
|
||||||
|
CfDnsClient spyClient = spy(client);
|
||||||
|
|
||||||
|
assertThrows(IllegalArgumentException.class,
|
||||||
|
() -> spyClient.zoneList(new PagingRequest(1, 4)));
|
||||||
|
assertThrows(IllegalArgumentException.class,
|
||||||
|
() -> spyClient.zoneList(new PagingRequest(1, 51)));
|
||||||
|
|
||||||
|
verify(spyClient, never()).getRequest(anyString(), eq(ZoneMultipleResponse.class));
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testZoneGet() throws Exception {
|
void testZoneGet() throws Exception {
|
||||||
// Create mock zone response
|
// Create mock zone response
|
||||||
@@ -189,7 +218,7 @@ class CfDnsClientMockTest {
|
|||||||
@Test
|
@Test
|
||||||
void testRecordList_WithPaging() throws Exception {
|
void testRecordList_WithPaging() throws Exception {
|
||||||
ZoneEntity zone = createTestZone();
|
ZoneEntity zone = createTestZone();
|
||||||
PagingRequest pagingRequest = PagingRequest.of(10, 1);
|
PagingRequest pagingRequest = PagingRequest.forRecords(10, 1);
|
||||||
|
|
||||||
RecordMultipleResponse mockResponse = new RecordMultipleResponse();
|
RecordMultipleResponse mockResponse = new RecordMultipleResponse();
|
||||||
mockResponse.setResultInfo(createResultInfo(1));
|
mockResponse.setResultInfo(createResultInfo(1));
|
||||||
@@ -456,10 +485,10 @@ class CfDnsClientMockTest {
|
|||||||
CfDnsClient spyClient = spy(client);
|
CfDnsClient spyClient = spy(client);
|
||||||
doReturn(zoneResponse(List.of(zone("z1", "a.com"), zone("z2", "b.com")),
|
doReturn(zoneResponse(List.of(zone("z1", "a.com"), zone("z2", "b.com")),
|
||||||
new ResultInfo(1, 2, 2, 2, 3)))
|
new ResultInfo(1, 2, 2, 2, 3)))
|
||||||
.when(spyClient).getRequest(eq("/zones?page=1&per_page=" + CfDnsClient.ZONES_PER_PAGE),
|
.when(spyClient).getRequest(eq("/zones?page=1&per_page=" + PagingRequest.DEFAULT_PAGE_SIZE),
|
||||||
eq(ZoneMultipleResponse.class));
|
eq(ZoneMultipleResponse.class));
|
||||||
doReturn(zoneResponse(List.of(zone("z3", "c.com")), new ResultInfo(2, 2, 2, 1, 3)))
|
doReturn(zoneResponse(List.of(zone("z3", "c.com")), new ResultInfo(2, 2, 2, 1, 3)))
|
||||||
.when(spyClient).getRequest(eq("/zones?page=2&per_page=" + CfDnsClient.ZONES_PER_PAGE),
|
.when(spyClient).getRequest(eq("/zones?page=2&per_page=" + PagingRequest.DEFAULT_PAGE_SIZE),
|
||||||
eq(ZoneMultipleResponse.class));
|
eq(ZoneMultipleResponse.class));
|
||||||
|
|
||||||
List<ZoneEntity> zones = spyClient.zoneList();
|
List<ZoneEntity> zones = spyClient.zoneList();
|
||||||
@@ -471,7 +500,7 @@ class CfDnsClientMockTest {
|
|||||||
@Test
|
@Test
|
||||||
void testRecordListByType_FetchesAllPages() throws Exception {
|
void testRecordListByType_FetchesAllPages() throws Exception {
|
||||||
ZoneEntity zone = createTestZone();
|
ZoneEntity zone = createTestZone();
|
||||||
String base = "/zones/" + TEST_ZONE_ID + "/dns_records?type=A&page=%d&per_page=" + CfDnsClient.RECORDS_PER_PAGE;
|
String base = "/zones/" + TEST_ZONE_ID + "/dns_records?type=A&order=name&direction=asc&page=%d&per_page=" + CfDnsClient.RECORDS_PER_PAGE;
|
||||||
CfDnsClient spyClient = spy(client);
|
CfDnsClient spyClient = spy(client);
|
||||||
doReturn(recordResponse(List.of(RecordEntity.build("a.example.com", RecordType.A, 60, "1.1.1.1")),
|
doReturn(recordResponse(List.of(RecordEntity.build("a.example.com", RecordType.A, 60, "1.1.1.1")),
|
||||||
new ResultInfo(1, 1, 2, 1, 2)))
|
new ResultInfo(1, 1, 2, 1, 2)))
|
||||||
@@ -489,7 +518,7 @@ class CfDnsClientMockTest {
|
|||||||
@Test
|
@Test
|
||||||
void testRecordListBySld_FetchesAllPages() throws Exception {
|
void testRecordListBySld_FetchesAllPages() throws Exception {
|
||||||
ZoneEntity zone = createTestZone();
|
ZoneEntity zone = createTestZone();
|
||||||
String base = "/zones/" + TEST_ZONE_ID + "/dns_records?name=test.example.com&page=%d&per_page="
|
String base = "/zones/" + TEST_ZONE_ID + "/dns_records?name=test.example.com&order=name&direction=asc&page=%d&per_page="
|
||||||
+ CfDnsClient.RECORDS_PER_PAGE;
|
+ CfDnsClient.RECORDS_PER_PAGE;
|
||||||
CfDnsClient spyClient = spy(client);
|
CfDnsClient spyClient = spy(client);
|
||||||
doReturn(recordResponse(List.of(RecordEntity.build("test.example.com", RecordType.A, 60, "1.1.1.1")),
|
doReturn(recordResponse(List.of(RecordEntity.build("test.example.com", RecordType.A, 60, "1.1.1.1")),
|
||||||
@@ -529,7 +558,7 @@ class CfDnsClientMockTest {
|
|||||||
spyClient.recordListBySubdomain(zone, CfDnsClient.APEX);
|
spyClient.recordListBySubdomain(zone, CfDnsClient.APEX);
|
||||||
|
|
||||||
verify(spyClient).getRequest(
|
verify(spyClient).getRequest(
|
||||||
eq("/zones/" + TEST_ZONE_ID + "/dns_records?name=example.com&page=1&per_page="
|
eq("/zones/" + TEST_ZONE_ID + "/dns_records?name=example.com&order=name&direction=asc&page=1&per_page="
|
||||||
+ CfDnsClient.RECORDS_PER_PAGE),
|
+ CfDnsClient.RECORDS_PER_PAGE),
|
||||||
eq(RecordMultipleResponse.class));
|
eq(RecordMultipleResponse.class));
|
||||||
}
|
}
|
||||||
@@ -589,6 +618,22 @@ class CfDnsClientMockTest {
|
|||||||
.when(spyClient).getRequest(anyString(), eq(RecordMultipleResponse.class));
|
.when(spyClient).getRequest(anyString(), eq(RecordMultipleResponse.class));
|
||||||
|
|
||||||
assertEquals(1, spyClient.recordList(createTestZone(), null).size());
|
assertEquals(1, spyClient.recordList(createTestZone(), null).size());
|
||||||
|
verify(spyClient).getRequest(eq("/zones/" + TEST_ZONE_ID
|
||||||
|
+ "/dns_records?order=name&direction=asc&page=1&per_page=" + CfDnsClient.RECORDS_PER_PAGE),
|
||||||
|
eq(RecordMultipleResponse.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testRecordList_ExplicitPagingRequestIsPreserved() throws Exception {
|
||||||
|
CfDnsClient spyClient = spy(client);
|
||||||
|
doReturn(recordResponse(List.of(), new ResultInfo(0)))
|
||||||
|
.when(spyClient).getRequest(anyString(), eq(RecordMultipleResponse.class));
|
||||||
|
|
||||||
|
spyClient.recordList(createTestZone(), PagingRequest.forRecords(2, 42));
|
||||||
|
|
||||||
|
verify(spyClient).getRequest(eq("/zones/" + TEST_ZONE_ID
|
||||||
|
+ "/dns_records?order=name&direction=asc&page=2&per_page=42"),
|
||||||
|
eq(RecordMultipleResponse.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -600,10 +645,10 @@ class CfDnsClientMockTest {
|
|||||||
spyClient.recordListByType(createTestZone(), RecordType.MX);
|
spyClient.recordListByType(createTestZone(), RecordType.MX);
|
||||||
spyClient.recordListBySubdomain(createTestZone(), "www", RecordType.TXT);
|
spyClient.recordListBySubdomain(createTestZone(), "www", RecordType.TXT);
|
||||||
|
|
||||||
verify(spyClient).getRequest(eq("/zones/" + TEST_ZONE_ID + "/dns_records?type=MX&page=1&per_page="
|
verify(spyClient).getRequest(eq("/zones/" + TEST_ZONE_ID + "/dns_records?type=MX&order=name&direction=asc&page=1&per_page="
|
||||||
+ CfDnsClient.RECORDS_PER_PAGE), eq(RecordMultipleResponse.class));
|
+ CfDnsClient.RECORDS_PER_PAGE), eq(RecordMultipleResponse.class));
|
||||||
verify(spyClient).getRequest(eq("/zones/" + TEST_ZONE_ID
|
verify(spyClient).getRequest(eq("/zones/" + TEST_ZONE_ID
|
||||||
+ "/dns_records?name=www.example.com&type=TXT&page=1&per_page="
|
+ "/dns_records?name=www.example.com&type=TXT&order=name&direction=asc&page=1&per_page="
|
||||||
+ CfDnsClient.RECORDS_PER_PAGE), eq(RecordMultipleResponse.class));
|
+ CfDnsClient.RECORDS_PER_PAGE), eq(RecordMultipleResponse.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -624,7 +669,7 @@ class CfDnsClientMockTest {
|
|||||||
List<RecordEntity> records = spyClient.recordListByType(createTestZone(), RecordType.A, RecordType.AAAA);
|
List<RecordEntity> records = spyClient.recordListByType(createTestZone(), RecordType.A, RecordType.AAAA);
|
||||||
|
|
||||||
assertEquals(List.of("A", "AAAA"), records.stream().map(RecordEntity::getType).toList());
|
assertEquals(List.of("A", "AAAA"), records.stream().map(RecordEntity::getType).toList());
|
||||||
verify(spyClient).getRequest(eq("/zones/" + TEST_ZONE_ID + "/dns_records?page=1&per_page="
|
verify(spyClient).getRequest(eq("/zones/" + TEST_ZONE_ID + "/dns_records?order=name&direction=asc&page=1&per_page="
|
||||||
+ CfDnsClient.RECORDS_PER_PAGE), eq(RecordMultipleResponse.class));
|
+ CfDnsClient.RECORDS_PER_PAGE), eq(RecordMultipleResponse.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -731,4 +776,137 @@ class CfDnsClientMockTest {
|
|||||||
assertEquals("srv1", sent.getPatches().get(0).getId());
|
assertEquals("srv1", sent.getPatches().get(0).getId());
|
||||||
assertEquals(10, sent.getPatches().get(0).getPriority());
|
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));
|
||||||
|
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(" "));
|
||||||
|
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&order=name&direction=asc&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&order=name&direction=asc&page=1&per_page=" + CfDnsClient.RECORDS_PER_PAGE),
|
||||||
|
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
|
||||||
|
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());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static RecordEntity rec(String id, String name) {
|
||||||
|
RecordEntity rec = RecordEntity.build(name, RecordType.A, 60, "1.1.1.1");
|
||||||
|
rec.setId(id);
|
||||||
|
return rec;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String recordsPage(int page) {
|
||||||
|
return "/zones/" + TEST_ZONE_ID + "/dns_records?order=name&direction=asc&page=" + page
|
||||||
|
+ "&per_page=" + CfDnsClient.RECORDS_PER_PAGE;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testRecordList_InconsistentPagesAreFetchedAgain() throws Exception {
|
||||||
|
CfDnsClient spyClient = spy(client);
|
||||||
|
// 1st attempt: page 2 repeats a record of page 1 (unstable order), so record c is missing
|
||||||
|
doReturn(recordResponse(List.of(rec("a", "a.example.com"), rec("b", "b.example.com")),
|
||||||
|
new ResultInfo(1, 2, 2, 2, 3)))
|
||||||
|
.when(spyClient).getRequest(eq(recordsPage(1)), eq(RecordMultipleResponse.class));
|
||||||
|
doReturn(recordResponse(List.of(rec("b", "b.example.com")), new ResultInfo(2, 2, 2, 1, 3)),
|
||||||
|
recordResponse(List.of(rec("c", "c.example.com")), new ResultInfo(2, 2, 2, 1, 3)))
|
||||||
|
.when(spyClient).getRequest(eq(recordsPage(2)), eq(RecordMultipleResponse.class));
|
||||||
|
|
||||||
|
List<RecordEntity> records = spyClient.recordList(createTestZone());
|
||||||
|
|
||||||
|
assertEquals(List.of("a", "b", "c"), records.stream().map(RecordEntity::getId).toList());
|
||||||
|
verify(spyClient, times(2)).getRequest(eq(recordsPage(1)), eq(RecordMultipleResponse.class));
|
||||||
|
verify(spyClient, times(2)).getRequest(eq(recordsPage(2)), eq(RecordMultipleResponse.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testRecordList_PersistentlyInconsistentPagesReturnDeduplicatedResult() throws Exception {
|
||||||
|
CfDnsClient spyClient = spy(client);
|
||||||
|
doReturn(recordResponse(List.of(rec("a", "a.example.com"), rec("b", "b.example.com")),
|
||||||
|
new ResultInfo(1, 2, 2, 2, 3)))
|
||||||
|
.when(spyClient).getRequest(eq(recordsPage(1)), eq(RecordMultipleResponse.class));
|
||||||
|
doReturn(recordResponse(List.of(rec("b", "b.example.com")), new ResultInfo(2, 2, 2, 1, 3)))
|
||||||
|
.when(spyClient).getRequest(eq(recordsPage(2)), eq(RecordMultipleResponse.class));
|
||||||
|
|
||||||
|
List<RecordEntity> records = spyClient.recordList(createTestZone());
|
||||||
|
|
||||||
|
// no duplicates, after 3 attempts the incomplete result is returned
|
||||||
|
assertEquals(List.of("a", "b"), records.stream().map(RecordEntity::getId).toList());
|
||||||
|
verify(spyClient, times(3)).getRequest(eq(recordsPage(1)), eq(RecordMultipleResponse.class));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -55,4 +55,32 @@ public class CfRequestTest {
|
|||||||
IllegalArgumentException.class,
|
IllegalArgumentException.class,
|
||||||
() -> CfRequest.RECORD_UPDATE.buildPath("zone123"));
|
() -> 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"));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,43 +1,80 @@
|
|||||||
package codes.thischwa.cf.model;
|
package codes.thischwa.cf.model;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.*;
|
class PagingRequestTest {
|
||||||
|
|
||||||
public class PagingRequestTest {
|
@Test
|
||||||
|
void testBuildPath() {
|
||||||
|
String result = PagingRequest.defaultPaging().addQueryString("/zones");
|
||||||
|
assertEquals("/zones?page=1&per_page=50", result);
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testBuildPath() {
|
void testBuildPathWithExistingQuery() {
|
||||||
String result = PagingRequest.defaultPaging().addQueryString("/zones");
|
String result = PagingRequest.forRecords(10, 100).addQueryString("/zones?foo=bar");
|
||||||
assertEquals("/zones?page=1&per_page=1000", result);
|
assertEquals("/zones?foo=bar&page=10&per_page=100", result);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testBuildPathAdditional() {
|
void testPagingRequestBoundaries() {
|
||||||
String result = new PagingRequest( 10, 100).addQueryString("/zones?foo=bar");
|
assertDoesNotThrow(() -> PagingRequest.forRecords(1, 1));
|
||||||
assertEquals("/zones?foo=bar&page=10&per_page=100", result);
|
assertDoesNotThrow(() -> PagingRequest.forRecords(1, PagingRequest.MAX_RECORDS_PER_PAGE));
|
||||||
}
|
assertThrows(IllegalArgumentException.class, () -> PagingRequest.forRecords(0, 1));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> PagingRequest.forRecords(1, 0));
|
||||||
|
assertThrows(IllegalArgumentException.class,
|
||||||
|
() -> PagingRequest.forRecords(1, PagingRequest.MAX_RECORDS_PER_PAGE + 1));
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testGetPagingParams() {
|
void testZonePageSizeBoundaries() {
|
||||||
PagingRequest request = PagingRequest.of(2, 50);
|
assertDoesNotThrow(() -> PagingRequest.forZones(1, PagingRequest.MIN_ZONES_PER_PAGE));
|
||||||
java.util.Map<String, String> params = request.getPagingParams();
|
assertDoesNotThrow(() -> PagingRequest.forZones(1, PagingRequest.MAX_ZONES_PER_PAGE));
|
||||||
assertEquals("2", params.get("page"));
|
assertThrows(IllegalArgumentException.class,
|
||||||
assertEquals("50", params.get("perPage"));
|
() -> PagingRequest.forZones(1, PagingRequest.MIN_ZONES_PER_PAGE - 1));
|
||||||
}
|
assertThrows(IllegalArgumentException.class,
|
||||||
|
() -> PagingRequest.forZones(1, PagingRequest.MAX_ZONES_PER_PAGE + 1));
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testLombokMethods() {
|
void testNextAndWithPageReturnNewRequests() {
|
||||||
PagingRequest req1 = PagingRequest.of(1, 10);
|
PagingRequest request = PagingRequest.forRecords(2, 50);
|
||||||
PagingRequest req2 = PagingRequest.of(1, 10);
|
|
||||||
assertEquals(req1, req2);
|
|
||||||
assertEquals(req1.hashCode(), req2.hashCode());
|
|
||||||
assertTrue(req1.toString().contains("page=1"));
|
|
||||||
|
|
||||||
req1.setPage(5);
|
|
||||||
assertEquals(5, req1.getPage());
|
|
||||||
req1.setPerPage(20);
|
|
||||||
assertEquals(20, req1.getPerPage());
|
|
||||||
}
|
|
||||||
|
|
||||||
|
assertEquals(PagingRequest.forRecords(3, 50), request.next());
|
||||||
|
assertEquals(PagingRequest.forRecords(5, 50), request.withPage(5));
|
||||||
|
assertEquals(PagingRequest.forRecords(2, 50), request);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testRecordMethods() {
|
||||||
|
PagingRequest first = PagingRequest.forRecords(1, 10);
|
||||||
|
PagingRequest second = PagingRequest.forRecords(1, 10);
|
||||||
|
|
||||||
|
assertEquals(first, second);
|
||||||
|
assertEquals(first.hashCode(), second.hashCode());
|
||||||
|
assertTrue(first.toString().contains("page=1"));
|
||||||
|
assertEquals(1, first.page());
|
||||||
|
assertEquals(10, first.perPage());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testValidationMessagesContainInvalidValues() {
|
||||||
|
IllegalArgumentException pageException = assertThrows(IllegalArgumentException.class,
|
||||||
|
() -> PagingRequest.forRecords(0, 10));
|
||||||
|
assertTrue(pageException.getMessage().contains("0"));
|
||||||
|
|
||||||
|
IllegalArgumentException perPageException = assertThrows(IllegalArgumentException.class,
|
||||||
|
() -> PagingRequest.forRecords(1, 0));
|
||||||
|
assertTrue(perPageException.getMessage().contains("0"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testAddQueryStringRejectsNullEndpoint() {
|
||||||
|
assertThrows(NullPointerException.class, () -> PagingRequest.defaultPaging().addQueryString(null));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user