Compare commits
43
Commits
36fe1cf22d
...
develop
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
70258786fb | ||
|
|
af04a484a1 | ||
|
|
4b1a32b1bf | ||
|
|
4c65cab3f6 | ||
|
|
63713e30bd | ||
|
|
ec32490cbf | ||
|
|
fac92ed615 | ||
|
|
5ed95453f1 | ||
|
|
b563b16a26 | ||
|
|
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 | ||
|
|
4b560141a1 | ||
|
|
31229ff627 | ||
|
|
d2acc3ce74 | ||
|
|
9aba45ab0e |
No files matched your search
@@ -4,6 +4,9 @@ inputs:
|
||||
token:
|
||||
description: Gitea token with write access to the repository.
|
||||
required: true
|
||||
build-outcome:
|
||||
description: Outcome of the build and test step.
|
||||
required: true
|
||||
|
||||
runs:
|
||||
using: composite
|
||||
@@ -17,6 +20,7 @@ runs:
|
||||
run: |
|
||||
mkdir -p junit-short
|
||||
shopt -s globstar nullglob
|
||||
rm -f junit-short/*.xml
|
||||
for f in **/target/*-reports/TEST-*.xml; do
|
||||
base="$(basename "$f")"
|
||||
short="${base#TEST-}"
|
||||
@@ -25,10 +29,12 @@ runs:
|
||||
|
||||
- name: Generate Markdown Test Report
|
||||
shell: bash
|
||||
env:
|
||||
BUILD_OUTCOME: ${{ inputs.build-outcome }}
|
||||
run: |
|
||||
mkdir -p reports
|
||||
python3 - <<'EOF'
|
||||
import glob, xml.etree.ElementTree as ET
|
||||
import glob, os, xml.etree.ElementTree as ET
|
||||
from datetime import datetime, timezone
|
||||
|
||||
generated_at = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")
|
||||
@@ -57,7 +63,17 @@ runs:
|
||||
test_rows.append(f"| {status} | {name} | {tests} | {passed} | {failures + errors} | {skipped} |")
|
||||
|
||||
total_passed = total_tests - total_failures - total_errors - total_skipped
|
||||
overall = "✅ All tests passed" if (total_failures + total_errors) == 0 else "❌ Some tests failed"
|
||||
build_outcome = os.environ.get("BUILD_OUTCOME", "unknown")
|
||||
if total_failures + total_errors:
|
||||
overall = "❌ Some tests failed"
|
||||
elif not files:
|
||||
overall = "⚠️ No JUnit reports found"
|
||||
elif total_passed == 0:
|
||||
overall = "⚠️ No tests passed"
|
||||
elif build_outcome != "success":
|
||||
overall = "❌ Build did not succeed"
|
||||
else:
|
||||
overall = "✅ All tests passed"
|
||||
|
||||
# --- JaCoCo ---
|
||||
def counter(el, type_):
|
||||
@@ -87,6 +103,7 @@ runs:
|
||||
"# Test Report\n\n"
|
||||
f"_Generated on {generated_at}_\n\n"
|
||||
f"**{overall}**\n\n"
|
||||
f"Build outcome: **{build_outcome}**\n\n"
|
||||
"## Test Results\n\n"
|
||||
"| | Tests | Passed | Failed | Skipped |\n"
|
||||
"|---|---|---|---|---|\n"
|
||||
@@ -111,6 +128,8 @@ runs:
|
||||
EOF
|
||||
|
||||
- name: Commit Test-Report to Repo
|
||||
# pull requests have no branch to push to (ref_name is e.g. "1/merge")
|
||||
if: ${{ github.event_name == 'push' }}
|
||||
shell: bash
|
||||
env:
|
||||
GIT_USER: gitea-actions-bot
|
||||
@@ -125,4 +144,12 @@ runs:
|
||||
git add reports/
|
||||
git diff --cached --quiet && echo "No changes" && exit 0
|
||||
git commit -m "ci: update test report [skip ci]"
|
||||
git push origin ${{ github.ref_name }}
|
||||
# rebase onto commits pushed in the meantime instead of overwriting them;
|
||||
# on conflicts in reports/ the freshly generated report wins
|
||||
for attempt in 1 2 3; do
|
||||
git pull --rebase --autostash -X theirs origin ${{ github.ref_name }}
|
||||
git push origin ${{ github.ref_name }} && exit 0
|
||||
echo "Push rejected (attempt $attempt), retrying..."
|
||||
sleep 5
|
||||
done
|
||||
exit 1
|
||||
@@ -0,0 +1,57 @@
|
||||
import os
|
||||
import pathlib
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
ACTION = pathlib.Path(__file__).resolve().parents[1] / "actions/publish-report/action.yml"
|
||||
|
||||
|
||||
def generate_report(directory, outcome, xml=None):
|
||||
action = ACTION.read_text()
|
||||
script = action.split(" python3 - <<'EOF'\n", 1)[1].split(" EOF", 1)[0]
|
||||
script = "\n".join(line[8:] for line in script.splitlines())
|
||||
root = pathlib.Path(directory)
|
||||
(root / "reports").mkdir()
|
||||
(root / "junit-short").mkdir()
|
||||
if xml is not None:
|
||||
(root / "junit-short/test.xml").write_text(xml)
|
||||
env = dict(os.environ, BUILD_OUTCOME=outcome)
|
||||
subprocess.run(["python3", "-c", script], cwd=root, env=env, check=True, capture_output=True)
|
||||
return (root / "reports/test.md").read_text()
|
||||
|
||||
|
||||
class PublishReportTest(unittest.TestCase):
|
||||
def test_missing_reports_are_not_successful(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
report = generate_report(directory, "failure")
|
||||
self.assertNotIn("All tests passed", report)
|
||||
self.assertIn("No JUnit", report)
|
||||
self.assertIn("failure", report)
|
||||
|
||||
def test_failed_build_with_passing_tests_is_not_successful(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
report = generate_report(directory, "failure", '<testsuite name="example" tests="1" failures="0" errors="0" skipped="0"/>')
|
||||
self.assertNotIn("All tests passed", report)
|
||||
self.assertIn("failure", report)
|
||||
|
||||
def test_passing_build_and_tests(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
report = generate_report(directory, "success", '<testsuite name="example" tests="1" failures="0" errors="0" skipped="0"/>')
|
||||
self.assertIn("All tests passed", report)
|
||||
|
||||
def test_all_skipped_is_not_successful(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
report = generate_report(directory, "success", '<testsuite name="example" tests="1" failures="0" errors="0" skipped="1"/>')
|
||||
self.assertNotIn("All tests passed", report)
|
||||
|
||||
def test_failed_tests(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
report = generate_report(directory, "failure", '<testsuite name="example" tests="1" failures="1" errors="0" skipped="0"/>')
|
||||
self.assertNotIn("All tests passed", report)
|
||||
self.assertIn("Some tests failed", report)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -4,9 +4,10 @@ on:
|
||||
push:
|
||||
branches:
|
||||
- develop
|
||||
- feature*
|
||||
- 'feature/**'
|
||||
pull_request:
|
||||
types: [ opened, synchronize, reopened ]
|
||||
workflow_dispatch:
|
||||
|
||||
defaults:
|
||||
run:
|
||||
@@ -25,10 +26,15 @@ jobs:
|
||||
uses: ./.gitea/actions/setup-java-maven
|
||||
|
||||
- name: Build and test
|
||||
run: mvn -B verify
|
||||
id: build
|
||||
env:
|
||||
# required by the live tests (CfClientTest, CfClientPenTest), they are skipped if not set
|
||||
API_TOKEN: ${{ secrets.API_TOKEN }}
|
||||
run: mvn -B clean verify
|
||||
|
||||
- name: Publish Test Report
|
||||
uses: ./.gitea/actions/publish-report
|
||||
if: ${{ always() }}
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
build-outcome: ${{ steps.build.outcome }}
|
||||
@@ -12,3 +12,4 @@
|
||||
cf.yml
|
||||
/docs/apidocs/javadoc.sh
|
||||
/.claude/settings.local.json
|
||||
/.junie/
|
||||
@@ -2,6 +2,10 @@
|
||||
|
||||
[](https://git.mein-gateway.de/thischwa/CloudflareDNS-java/actions?workflow=build-and-analyse.yml)
|
||||
|
||||
[](https://git.mein-gateway.de/thischwa/-/packages/maven/codes.thischwa:cloudflaredns/)
|
||||
|
||||
[Test report](reports/test.md)
|
||||
|
||||
## Preface
|
||||
|
||||
This project provides a java client for minimalistic access to the Cloudflare API version 4, which is mainly used for
|
||||
@@ -20,6 +24,8 @@ This guide comes without any warranty. Use at your own risk. The author is not r
|
||||
|
||||
## Get It
|
||||
|
||||
Java 17 or higher is required.
|
||||
|
||||
The project has its own maven repository. Follow the instructions on the latest [package](https://git.mein-gateway.de/thischwa/-/packages/maven/codes.thischwa:cloudflaredns) to add the repository to your project.
|
||||
|
||||
## Changelog
|
||||
@@ -31,7 +37,7 @@ See [changelog](changelog.md)
|
||||
The methods can be categorized as follows:
|
||||
|
||||
- `Zone`: list, info
|
||||
- `Record`: list, info, create, update, delete
|
||||
- `Record`: list, info, create, update, delete, batch
|
||||
|
||||
The API provides two styles for working with DNS records:
|
||||
|
||||
@@ -58,6 +64,28 @@ CfDnsClient cfDnsClient = new CfDnsClientBuilder()
|
||||
.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.
|
||||
`CfDnsClient` implements `AutoCloseable`, call `close()` (or use try-with-resources) to release the connections:
|
||||
|
||||
```java
|
||||
try (CfDnsClient cfDnsClient = new CfDnsClientBuilder().withApiTokenAuth("your-api-token").build()) {
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
### `zoneList`
|
||||
|
||||
Retrieve all zones within the Cloudflare account.
|
||||
@@ -69,6 +97,18 @@ List<ZoneEntity> zones = cfDnsClient.zoneList();
|
||||
zones.forEach(zone -> System.out.println("Zone: " + zone.getName()));
|
||||
```
|
||||
|
||||
Without a `PagingRequest`, `zoneList()` fetches zones in pages of 50, requesting further pages as needed.
|
||||
Use a `PagingRequest` to retrieve a specific page:
|
||||
|
||||
```java
|
||||
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`
|
||||
@@ -90,65 +130,110 @@ System.out.println("Zone ID: " + zone.getId());
|
||||
|
||||
Retrieve records for a given zone. There are two variants:
|
||||
|
||||
#### List by SLD
|
||||
Retrieve all records for a specific second-level domain (SLD) under a given zone.
|
||||
#### List by subdomain (`recordListBySubdomain`)
|
||||
Retrieve all records for a specific subdomain under a given zone, optionally filtered by record types.
|
||||
|
||||
- **Parameters**:
|
||||
- `ZoneEntity zone` - The zone object.
|
||||
- `String sld` - Second-level domain (e.g., "www" in "www.example.com").
|
||||
- `String subdomain` - The subdomain relative to the zone (e.g., "www" in "www.example.com"
|
||||
or "my.sub" in "my.sub.example.com"). Use `CfDnsClient.APEX` (`"@"`) for the zone apex.
|
||||
- `RecordType... types` - Optional record types to filter by. If not specified, returns all record types.
|
||||
- **Returns**: A list of `RecordEntity` objects.
|
||||
|
||||
```java
|
||||
List<RecordEntity> records = cfDnsClient.recordList(zone, "sld");
|
||||
records.forEach(record ->
|
||||
System.out.println("Record Type: "+record.getType()
|
||||
+", Value: "+record.getContent())
|
||||
);
|
||||
// Get all records for a specific subdomain
|
||||
List<RecordEntity> wwwRecords = cfDnsClient.recordListBySubdomain(zone, "www");
|
||||
|
||||
// Get only A records for a specific subdomain
|
||||
List<RecordEntity> wwwARecords = cfDnsClient.recordListBySubdomain(zone, "www", RecordType.A);
|
||||
|
||||
// Get the records of the zone apex (e.g. "example.com")
|
||||
List<RecordEntity> apexRecords = cfDnsClient.recordListBySubdomain(zone, CfDnsClient.APEX);
|
||||
```
|
||||
|
||||
#### List by Zone (optional filtering)
|
||||
Retrieve DNS record details for a zone or a specific SLD, optionally filtered by record types.
|
||||
|
||||
- **Parameters**:
|
||||
- `ZoneEntity zone` - The zone object.
|
||||
- `String sld` - (Optional) The second-level domain.
|
||||
- `RecordType... types` - Optional record types to filter by (e.g., A, CNAME). If not specified, returns all record types.
|
||||
- **Returns**: A list of `RecordEntity` objects matching the criteria.
|
||||
#### List by type (`recordListByType`)
|
||||
Retrieve all records of a zone, optionally filtered by record types.
|
||||
|
||||
```java
|
||||
// Get all records for a specific SLD
|
||||
List<RecordEntity> allSldRecords = cfDnsClient.recordList(zone, "www");
|
||||
// Get only A and AAAA records of a zone
|
||||
List<RecordEntity> ipZoneRecords = cfDnsClient.recordListByType(zone, RecordType.A, RecordType.AAAA);
|
||||
```
|
||||
|
||||
// Get only A records for a specific SLD
|
||||
List<RecordEntity> aSldRecords = cfDnsClient.recordList(zone, "www", RecordType.A);
|
||||
If exactly one record type is given, the filtering is done by Cloudflare, otherwise by the client.
|
||||
|
||||
#### List all records of a zone (`recordList`)
|
||||
|
||||
```java
|
||||
// Get all records of a zone
|
||||
List<RecordEntity> allZoneRecords = cfDnsClient.recordList(zone);
|
||||
|
||||
// Get only A and AAAA records of a zone
|
||||
List<RecordEntity> ipZoneRecords = cfDnsClient.recordList(zone, RecordType.A, RecordType.AAAA);
|
||||
// Get the records of a zone page by page (page 2, 100 records per page)
|
||||
List<RecordEntity> pagedRecords = cfDnsClient.recordList(zone, PagingRequest.forRecords(2, 100));
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
`RecordEntity#getSubdomain()` returns the record name relative to its zone, e.g. `my.sub` for
|
||||
`my.sub.example.com` and `"@"` for the zone apex. The timestamps `getCreatedOn()` and `getModifiedOn()`
|
||||
are of type `java.time.Instant` (UTC).
|
||||
|
||||
#### Group by FQDN
|
||||
|
||||
The static helper `CfDnsClient.groupRecordsByFqdn` groups a list of records by their fully qualified domain name:
|
||||
|
||||
```java
|
||||
Map<String, List<RecordEntity>> byFqdn = CfDnsClient.groupRecordsByFqdn(cfDnsClient.recordList(zone));
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `recordCreate`
|
||||
### `recordCreateSubdomain` / `recordCreate`
|
||||
|
||||
Create a new DNS record in a specific zone.
|
||||
|
||||
- **Parameters**:
|
||||
- `ZoneEntity zone` - DNS zone object.
|
||||
- `String sld` - The sub-tld of the new record.
|
||||
- `int ttl` - The time-to-live in seconds of the new rcord.
|
||||
- `ZoneEntity zone` - The DNS zone object.
|
||||
- `String subdomain` - The subdomain of the new record relative to the zone (e.g., "api" in "api.example.com").
|
||||
- `int ttl` - The time-to-live in seconds of the new record.
|
||||
- `RecordType type` - The record type (e.g., A, AAAA, CNAME).
|
||||
- `String content` - The content of the record (e.g., the IP address of an A record).
|
||||
- **Returns**: The created `RecordEntity`.
|
||||
|
||||
```java
|
||||
RecordEntity created = client.recordCreateSld(zone, "api", 60, RecordType.A, "192.168.1.1");
|
||||
RecordEntity created = cfDnsClient.recordCreateSubdomain(zone, "api", 60, RecordType.A, "192.168.1.1");
|
||||
System.out.println("Created Record ID: " + created.getId());
|
||||
```
|
||||
|
||||
Alternatively, the record can be created with its fully qualified name or from a `RecordEntity`:
|
||||
|
||||
```java
|
||||
cfDnsClient.recordCreate(zone, "api.example.com", 60, RecordType.A, "192.168.1.1");
|
||||
cfDnsClient.recordCreate(zone, RecordEntity.build("api.example.com", RecordType.A, 60, "192.168.1.1"));
|
||||
```
|
||||
|
||||
Records which need more than a content, like MX, SRV or CAA records, can be created from a `RecordEntity`.
|
||||
Besides `priority` and `data`, the attributes `proxied`, `comment` and `tags` are supported:
|
||||
|
||||
```java
|
||||
// MX record with priority
|
||||
RecordEntity mx = RecordEntity.build("example.com", RecordType.MX, 3600, "mail.example.com");
|
||||
mx.setPriority(10);
|
||||
cfDnsClient.recordCreate(zone, mx);
|
||||
|
||||
// SRV record with structured data (keys as in the Cloudflare API), the priority is part of the data
|
||||
RecordEntity srv = RecordEntity.build("_sip._tcp.example.com", RecordType.SRV, 3600, null);
|
||||
srv.setData(Map.of("priority", 10, "weight", 5, "port", 5060, "target", "sip.example.com"));
|
||||
cfDnsClient.recordCreate(zone, srv);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `recordUpdate`
|
||||
|
||||
Update an existing DNS record.
|
||||
Update an existing DNS record (partial update: attributes which are `null` remain unchanged).
|
||||
Read-only attributes like timestamps are ignored, the given `RecordEntity` isn't modified.
|
||||
|
||||
- **Parameters**:
|
||||
- `ZoneEntity zone` - The zone that contains the record.
|
||||
@@ -175,22 +260,30 @@ boolean isDeleted = cfDnsClient.recordDelete(zone, record);
|
||||
System.out.println(isDeleted ? "Deletion successful." : "Deletion failed.");
|
||||
```
|
||||
|
||||
If only the ID is known, the record can be deleted by its ID:
|
||||
|
||||
```java
|
||||
cfDnsClient.recordDelete(zone, record.getId());
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `recordDeleteTypeIfExists`
|
||||
|
||||
Delete a DNS record of a specific type if it exists.
|
||||
Delete the DNS records of the given types if they exist.
|
||||
|
||||
- **Parameters**:
|
||||
- `ZoneEntity zone` - Target zone.
|
||||
- `String sld` - Second-level domain.
|
||||
- `RecordType type` - Record type.
|
||||
- `String subdomain` - The subdomain relative to the zone.
|
||||
- `RecordType... types` - One or more record types.
|
||||
|
||||
```java
|
||||
cfDnsClient.recordDeleteTypeIfExists(zone, "api", RecordType.A);
|
||||
cfDnsClient.recordDeleteTypeIfExists(zone, "api", RecordType.A, RecordType.AAAA);
|
||||
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
|
||||
|
||||
Process multiple DNS record operations (POST, PUT, PATCH, DELETE) in a single batch request.
|
||||
@@ -226,8 +319,8 @@ Partially update existing records. **Record IDs are required** - fetch them firs
|
||||
```java
|
||||
// Step 1: Fetch existing records to get their IDs
|
||||
List<RecordEntity> recordsToUpdate = new ArrayList<>();
|
||||
recordsToUpdate.add(cfDnsClient.recordList(zone, "api",RecordType.A).get(0));
|
||||
recordsToUpdate.add(cfDnsClient.recordList(zone, "cdn",RecordType.A).get(0));
|
||||
recordsToUpdate.add(cfDnsClient.recordListBySubdomain(zone, "api",RecordType.A).get(0));
|
||||
recordsToUpdate.add(cfDnsClient.recordListBySubdomain(zone, "cdn",RecordType.A).get(0));
|
||||
|
||||
// Step 2: Modify only the fields you want to update
|
||||
recordsToUpdate.forEach(record ->record.setContent("192.168.2.10"));
|
||||
@@ -244,8 +337,8 @@ Fully replace existing records. **Record IDs are required** - fetch them first:
|
||||
```java
|
||||
// Step 1: Fetch existing records to get their IDs
|
||||
List<RecordEntity> recordsToReplace = new ArrayList<>();
|
||||
recordsToReplace.add(cfDnsClient.recordList(zone, "mail",RecordType.A).get(0));
|
||||
recordsToReplace.add(cfDnsClient.recordList(zone, "cdn",RecordType.A).get(0));
|
||||
recordsToReplace.add(cfDnsClient.recordListBySubdomain(zone, "mail",RecordType.A).get(0));
|
||||
recordsToReplace.add(cfDnsClient.recordListBySubdomain(zone, "cdn",RecordType.A).get(0));
|
||||
|
||||
// Step 2: Modify all fields as needed (full replacement)
|
||||
recordsToReplace.get(0).setContent("192.168.3.10");
|
||||
@@ -265,8 +358,8 @@ Delete existing records. **Record IDs are required** - fetch them first:
|
||||
```java
|
||||
// Step 1: Fetch existing records to get their IDs
|
||||
List<RecordEntity> recordsToDelete = new ArrayList<>();
|
||||
recordsToDelete.add(cfDnsClient.recordList(zone, "cdn",RecordType.A).get(0));
|
||||
recordsToDelete.add(cfDnsClient.recordList(zone, "mail",RecordType.A).get(0));
|
||||
recordsToDelete.add(cfDnsClient.recordListBySubdomain(zone, "cdn",RecordType.A).get(0));
|
||||
recordsToDelete.add(cfDnsClient.recordListBySubdomain(zone, "mail",RecordType.A).get(0));
|
||||
|
||||
// Step 2: Send batch delete request
|
||||
BatchEntry result = cfDnsClient.recordBatch(zone, null, null, null, recordsToDelete);
|
||||
@@ -285,12 +378,12 @@ List<RecordEntity> newRecords = Arrays.asList(
|
||||
|
||||
// Fetch existing records for update/delete (IDs required)
|
||||
List<RecordEntity> recordsToUpdate = Arrays.asList(
|
||||
cfDnsClient.recordList(zone, "existing-api", RecordType.A).get(0)
|
||||
cfDnsClient.recordListBySubdomain(zone, "existing-api", RecordType.A).get(0)
|
||||
);
|
||||
recordsToUpdate.get(0).setContent("192.168.1.200");
|
||||
|
||||
List<RecordEntity> recordsToDelete = Arrays.asList(
|
||||
cfDnsClient.recordList(zone, "old-api", RecordType.A).get(0)
|
||||
cfDnsClient.recordListBySubdomain(zone, "old-api", RecordType.A).get(0)
|
||||
);
|
||||
|
||||
// Execute all operations in a single batch request
|
||||
@@ -318,31 +411,33 @@ that reduces verbosity and improves code readability.
|
||||
### Basic Usage
|
||||
|
||||
```java
|
||||
// Create a DNS getRecord
|
||||
// Create a DNS record
|
||||
client.zone("example.com")
|
||||
.record("api")
|
||||
.getRecord("api")
|
||||
.create(RecordType.A, "192.168.1.1",60);
|
||||
|
||||
// Get DNS records of a subdomain
|
||||
List<RecordEntity> records = client.zone("example.com")
|
||||
.record("www", RecordType.A)
|
||||
.getRecord("www", RecordType.A)
|
||||
.get();
|
||||
|
||||
// Get all DNS records of a zone
|
||||
List<RecordEntity> zoneRecords = client.zone("example.com")
|
||||
.list(RecordType.A, RecordType.AAAA);
|
||||
|
||||
// Update a DNS getRecord
|
||||
// Update a DNS record
|
||||
RecordEntity updated = client.zone("example.com")
|
||||
.record("api", RecordType.A)
|
||||
.getRecord("api", RecordType.A)
|
||||
.update("192.168.1.2");
|
||||
|
||||
// Delete DNS records
|
||||
client.zone("example.com")
|
||||
.record("old-service")
|
||||
.getRecord("old-service")
|
||||
.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
|
||||
|
||||
- **More Readable**: The chain of method calls reads like natural language
|
||||
@@ -357,25 +452,25 @@ CfDnsClient client = new CfDnsClientBuilder()
|
||||
.withApiTokenAuth("your-api-token")
|
||||
.build();
|
||||
|
||||
// Create a new getRecord
|
||||
// Create a new record
|
||||
client.zone("example.com")
|
||||
.record("api")
|
||||
.getRecord("api")
|
||||
.create(RecordType.A, "192.168.100.1",60);
|
||||
|
||||
// Retrieve and verify
|
||||
List<RecordEntity> records = client.zone("example.com")
|
||||
.record("api", RecordType.A)
|
||||
.getRecord("api", RecordType.A)
|
||||
.get();
|
||||
System.out.println("IP: "+records.get(0).getContent());
|
||||
|
||||
// Update the getRecord
|
||||
// Update the record
|
||||
client.zone("example.com")
|
||||
.record("api",RecordType.A)
|
||||
.getRecord("api",RecordType.A)
|
||||
.update("192.168.100.2");
|
||||
|
||||
// Clean up
|
||||
client.zone("example.com")
|
||||
.record("api")
|
||||
.getRecord("api")
|
||||
.delete(RecordType.A);
|
||||
```
|
||||
|
||||
@@ -385,7 +480,10 @@ client.zone("example.com")
|
||||
|
||||
The `CfDnsClient` provides internal error-handling mechanisms through exceptions. For example:
|
||||
- `CloudflareApiException` is thrown for errors during API communication or invalid responses.
|
||||
- `CloudflareNotFoundException` is thrown when the requested resource (single or multiple) is not found, if enabled via the `emptyResultThrowsException` flag during initialization. **Default is `false`**, meaning empty results will be returned without throwing an exception.
|
||||
`getStatusCode()` returns the HTTP status code (or `CloudflareApiException.NO_STATUS_CODE` if there was no response)
|
||||
and `getErrors()` the error codes and messages reported by Cloudflare.
|
||||
- `CloudflareNotFoundException` is thrown if Cloudflare responds with HTTP status 404 (e.g. deleting a non-existing record).
|
||||
- `CloudflareNotFoundException` is also thrown when the requested resource (single or multiple) is not found, if enabled via the `emptyResultThrowsException` flag during initialization. **Default is `false`**, meaning empty results will be returned without throwing an exception.
|
||||
|
||||
To enable exception throwing for empty results:
|
||||
|
||||
@@ -400,13 +498,14 @@ CfDnsClient client = new CfDnsClientBuilder()
|
||||
|
||||
```java
|
||||
try {
|
||||
List<RecordEntity> records = cfDnsClient.recordList(zone, "www", RecordType.A);
|
||||
List<RecordEntity> records = cfDnsClient.recordListBySubdomain(zone, "www", RecordType.A);
|
||||
System.out.println("Record IP: "+records.get(0).getContent());
|
||||
} catch (CloudflareApiException e) {
|
||||
if (e instanceof CloudflareNotFoundException) {
|
||||
log.warn("Sld not found: www");
|
||||
log.warn("Subdomain not found: www");
|
||||
} else {
|
||||
log.error("Error while getting sld info of www", e);
|
||||
log.error("Error while getting records of subdomain www (HTTP status {}, errors {})",
|
||||
e.getStatusCode(), e.getErrors(), e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
+37
-1
@@ -1,6 +1,42 @@
|
||||
# Changelog
|
||||
|
||||
- 0.5.0-SNAPSHOT:
|
||||
- 1.0.0:
|
||||
- **Breaking Changes**:
|
||||
- `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, RecordType... types)` → `recordListByType(zone, types...)`
|
||||
- `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
|
||||
- Cloudflare responses with HTTP status 404 throw a `CloudflareNotFoundException` (independent of `emptyResultThrowsException`)
|
||||
- unexpected runtime exceptions aren't wrapped into a `CloudflareApiException("Unexpected error!")` anymore
|
||||
- batch DELETE sends only the record IDs, batch PATCH sends all writable attributes which aren't `null` (before: only the content)
|
||||
- security: query values (zone names, subdomains) are URL-encoded and IDs are validated, which prevents query parameter injection and path traversal
|
||||
- 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
|
||||
- `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`
|
||||
- `recordCreate` and `recordUpdate` don't modify the given `RecordEntity` anymore and send only writable attributes
|
||||
- fluent `update(content)` sends only the new content (partial update)
|
||||
- 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 maven plugins: maven-compiler-plugin 3.16.0, maven-surefire-plugin 3.6.0, maven-jar-plugin 3.5.1
|
||||
- fixed "getRecord" wording in 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()`
|
||||
- `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: `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: `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
|
||||
- 0.5.0:
|
||||
- moved the project to git.mein-gateway.de
|
||||
- replaced sonarqube with own actions
|
||||
- migrate to jackson 3.x
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
<groupId>codes.thischwa</groupId>
|
||||
<artifactId>cloudflaredns</artifactId>
|
||||
<version>0.5.0</version>
|
||||
<version>1.1.0-SNAPSHOT</version>
|
||||
<name>CloudflareDNS-java</name>
|
||||
<inceptionYear>2025</inceptionYear>
|
||||
<packaging>jar</packaging>
|
||||
@@ -36,21 +36,22 @@
|
||||
<linkXRef>false</linkXRef>
|
||||
|
||||
<!-- 3rd party dependencies -->
|
||||
<jackson.version>3.2.1</jackson.version>
|
||||
<httpclient5.version>5.6.2</httpclient5.version>
|
||||
<lombok.version>1.18.46</lombok.version>
|
||||
<jackson.version>3.2.4</jackson.version>
|
||||
<httpclient5.version>5.6.4</httpclient5.version>
|
||||
<lombok.version>1.18.48</lombok.version>
|
||||
<slf4j.version>2.0.18</slf4j.version>
|
||||
<logback-classic.version>1.5.38</logback-classic.version>
|
||||
<logback-classic.version>1.6.6</logback-classic.version>
|
||||
<junit5.version>5.14.2</junit5.version>
|
||||
<mockito-junit5.version>5.23.0</mockito-junit5.version>
|
||||
<mockito-junit5.version>5.24.0</mockito-junit5.version>
|
||||
<lombok-maven-plugin.version>1.18.20.0</lombok-maven-plugin.version>
|
||||
<jetbrains-annotations.version>26.1.0</jetbrains-annotations.version>
|
||||
</properties>
|
||||
|
||||
<scm>
|
||||
<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>
|
||||
<url>https://git.mein-gateway.de/thischwa/CloudflareDNS-java</url>
|
||||
<tag>v0.5.0</tag>
|
||||
<tag>HEAD</tag>
|
||||
</scm>
|
||||
|
||||
<distributionManagement>
|
||||
@@ -102,7 +103,7 @@
|
||||
<dependency>
|
||||
<groupId>org.jetbrains</groupId>
|
||||
<artifactId>annotations</artifactId>
|
||||
<version>26.1.0</version>
|
||||
<version>${jetbrains-annotations.version}</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
|
||||
@@ -131,7 +132,7 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.14.1</version>
|
||||
<version>3.16.0</version>
|
||||
<configuration>
|
||||
<source>${java.version}</source>
|
||||
<target>${java.version}</target>
|
||||
@@ -220,7 +221,7 @@
|
||||
<!-- to export test summary -->
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>3.5.6</version>
|
||||
<version>3.6.0</version>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
@@ -254,7 +255,7 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<version>3.5.0</version>
|
||||
<version>3.5.1</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>attach-delomboked-sources</id>
|
||||
|
||||
+17
-14
@@ -1,31 +1,34 @@
|
||||
# Test Report
|
||||
|
||||
_Generated on 2026-09-07 06:51:01 UTC_
|
||||
_Generated on 2026-11-21 12:07:43 UTC_
|
||||
|
||||
**✅ All tests passed**
|
||||
|
||||
Build outcome: **success**
|
||||
|
||||
## Test Results
|
||||
|
||||
| | Tests | Passed | Failed | Skipped |
|
||||
|---|---|---|---|---|
|
||||
| **Total** | 90 | 90 | 0 | 0 |
|
||||
| **Total** | 165 | 165 | 0 | 0 |
|
||||
|
||||
### Details
|
||||
|
||||
| Status | Suite | Tests | Passed | Failed | Skipped |
|
||||
|---|---|---|---|---|---|
|
||||
| ✅ | codes.thischwa.cf.CfBasicHttpClientErrorTest | 6 | 6 | 0 | 0 |
|
||||
| ✅ | codes.thischwa.cf.CfBasicHttpClientTest | 9 | 9 | 0 | 0 |
|
||||
| ✅ | codes.thischwa.cf.CfClientPenTest | 0 | 0 | 0 | 0 |
|
||||
| ✅ | codes.thischwa.cf.CfClientTest | 0 | 0 | 0 | 0 |
|
||||
| ✅ | codes.thischwa.cf.CfDnsClientBuilderTest | 16 | 16 | 0 | 0 |
|
||||
| ✅ | codes.thischwa.cf.CfDnsClientMockTest | 16 | 16 | 0 | 0 |
|
||||
| ✅ | codes.thischwa.cf.CfRequestTest | 8 | 8 | 0 | 0 |
|
||||
| ✅ | codes.thischwa.cf.ObjectMapperTest | 2 | 2 | 0 | 0 |
|
||||
| ✅ | codes.thischwa.cf.ResponseValidatorTest | 8 | 8 | 0 | 0 |
|
||||
| ✅ | codes.thischwa.cf.CfClientIntegrationTest | 19 | 19 | 0 | 0 |
|
||||
| ✅ | codes.thischwa.cf.CfClientPenTest | 4 | 4 | 0 | 0 |
|
||||
| ✅ | codes.thischwa.cf.CfDnsClientBuilderTest | 21 | 21 | 0 | 0 |
|
||||
| ✅ | codes.thischwa.cf.CfDnsClientMockTest | 42 | 42 | 0 | 0 |
|
||||
| ✅ | codes.thischwa.cf.CfRequestTest | 10 | 10 | 0 | 0 |
|
||||
| ✅ | codes.thischwa.cf.ObjectMapperTest | 4 | 4 | 0 | 0 |
|
||||
| ✅ | codes.thischwa.cf.ResponseValidatorTest | 11 | 11 | 0 | 0 |
|
||||
| ✅ | codes.thischwa.cf.fluent.FluentApiTest | 15 | 15 | 0 | 0 |
|
||||
| ✅ | codes.thischwa.cf.model.BatchEntryTest | 2 | 2 | 0 | 0 |
|
||||
| ✅ | codes.thischwa.cf.model.PagingRequestTest | 4 | 4 | 0 | 0 |
|
||||
| ✅ | codes.thischwa.cf.model.RecordEntityTest | 6 | 6 | 0 | 0 |
|
||||
| ✅ | codes.thischwa.cf.model.PagingRequestTest | 8 | 8 | 0 | 0 |
|
||||
| ✅ | codes.thischwa.cf.model.RecordEntityTest | 10 | 10 | 0 | 0 |
|
||||
| ✅ | codes.thischwa.cf.model.RecordTypeTest | 3 | 3 | 0 | 0 |
|
||||
| ✅ | codes.thischwa.cf.model.ZoneEntityTest | 1 | 1 | 0 | 0 |
|
||||
|
||||
@@ -33,6 +36,6 @@ _Generated on 2026-09-07 06:51:01 UTC_
|
||||
|
||||
| Package | Line Coverage | Branch Coverage |
|
||||
|---|---|---|
|
||||
| codes.thischwa.cf.fluent | 100% (25/25) | 100% (4/4) |
|
||||
| codes.thischwa.cf.model | 100% (93/93) | 90% (9/10) |
|
||||
| codes.thischwa.cf | 89% (249/279) | 71% (51/72) |
|
||||
| codes.thischwa.cf.fluent | 100% (23/23) | 100% (4/4) |
|
||||
| codes.thischwa.cf.model | 100% (102/102) | 96% (23/24) |
|
||||
| codes.thischwa.cf | 97% (441/454) | 88% (189/214) |
|
||||
@@ -1,22 +1,32 @@
|
||||
package codes.thischwa.cf;
|
||||
|
||||
import codes.thischwa.cf.model.AbstractResponse;
|
||||
import codes.thischwa.cf.model.ResponseResultInfo;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpDelete;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpGet;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpPatch;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpPost;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpPut;
|
||||
import org.apache.hc.client5.http.config.ConnectionConfig;
|
||||
import org.apache.hc.client5.http.config.RequestConfig;
|
||||
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
|
||||
import org.apache.hc.client5.http.impl.classic.HttpClients;
|
||||
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
|
||||
import org.apache.hc.core5.http.ClassicHttpRequest;
|
||||
import org.apache.hc.core5.http.ClassicHttpResponse;
|
||||
import org.apache.hc.core5.http.ContentType;
|
||||
import org.apache.hc.core5.http.HttpHeaders;
|
||||
import org.apache.hc.core5.http.HttpStatus;
|
||||
import org.apache.hc.core5.http.io.entity.EntityUtils;
|
||||
import org.apache.hc.core5.http.io.entity.StringEntity;
|
||||
import org.apache.hc.core5.http.message.BasicClassicHttpRequest;
|
||||
import org.apache.hc.core5.util.Timeout;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import tools.jackson.core.JacksonException;
|
||||
import tools.jackson.databind.ObjectMapper;
|
||||
@@ -25,13 +35,17 @@ import tools.jackson.databind.ObjectMapper;
|
||||
* Abstract base class for creating HTTP clients to interact with the Cloudflare API. Provides
|
||||
* methods for handling GET and POST requests and includes utilities for constructing HTTP clients,
|
||||
* managing authentication, and handling JSON serialization.
|
||||
*
|
||||
* <p>One underlying HTTP client (with connection pooling) is shared for all requests. It is
|
||||
* released by {@link #close()}.
|
||||
*/
|
||||
@Slf4j
|
||||
abstract class CfBasicHttpClient {
|
||||
abstract class CfBasicHttpClient implements AutoCloseable {
|
||||
|
||||
private final String baseUrl;
|
||||
private final CfDnsClientBuilder.CfAuth auth;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final CloseableHttpClient httpClient;
|
||||
|
||||
private record ResultWrapper(int statusCode, String responseBody) {
|
||||
}
|
||||
@@ -43,65 +57,112 @@ abstract class CfBasicHttpClient {
|
||||
* @param auth the authentication mechanism to use
|
||||
*/
|
||||
CfBasicHttpClient(@NotNull String baseUrl, @NotNull CfDnsClientBuilder.CfAuth auth) {
|
||||
this(baseUrl, auth, CfDnsClientBuilder.DEFAULT_CONNECT_TIMEOUT,
|
||||
CfDnsClientBuilder.DEFAULT_RESPONSE_TIMEOUT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new Cloudflare HTTP client with the specified base URL, authentication and timeouts.
|
||||
*
|
||||
* @param baseUrl the base URL for the Cloudflare API
|
||||
* @param auth the authentication mechanism to use
|
||||
* @param connectTimeout the timeout for establishing a connection
|
||||
* @param responseTimeout the timeout for waiting for the response data
|
||||
*/
|
||||
CfBasicHttpClient(@NotNull String baseUrl, @NotNull CfDnsClientBuilder.CfAuth auth,
|
||||
@NotNull Duration connectTimeout, @NotNull Duration responseTimeout) {
|
||||
this.baseUrl = baseUrl;
|
||||
this.auth = auth;
|
||||
this.objectMapper = JsonConf.initObjectMapper();
|
||||
this.httpClient = createHttpClient(connectTimeout, responseTimeout);
|
||||
}
|
||||
|
||||
private CloseableHttpClient createHttpClient() {
|
||||
return HttpClients.custom().addRequestInterceptorFirst((request, context, execChain) -> {
|
||||
request.addHeader(HttpHeaders.ACCEPT_CHARSET, "UTF-8");
|
||||
request.addHeader(HttpHeaders.ACCEPT_ENCODING, "gzip");
|
||||
request.addHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.getMimeType());
|
||||
request.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType());
|
||||
if (request instanceof ClassicHttpRequest classicRequest) {
|
||||
auth.applyAuth(classicRequest);
|
||||
}
|
||||
}).build();
|
||||
/**
|
||||
* Releases the underlying HTTP client and its connections. The client must not be used anymore
|
||||
* afterwards.
|
||||
*
|
||||
* @throws IOException if an I/O error occurs while closing the HTTP client
|
||||
*/
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
httpClient.close();
|
||||
}
|
||||
|
||||
private CloseableHttpClient createHttpClient(Duration connectTimeout, Duration responseTimeout) {
|
||||
Timeout connect = Timeout.ofMilliseconds(connectTimeout.toMillis());
|
||||
Timeout response = Timeout.ofMilliseconds(responseTimeout.toMillis());
|
||||
ConnectionConfig connectionConfig = ConnectionConfig.custom()
|
||||
.setConnectTimeout(connect)
|
||||
.setSocketTimeout(response)
|
||||
.build();
|
||||
RequestConfig requestConfig = RequestConfig.custom()
|
||||
.setConnectionRequestTimeout(connect)
|
||||
.setResponseTimeout(response)
|
||||
.build();
|
||||
return HttpClients.custom()
|
||||
.setConnectionManager(PoolingHttpClientConnectionManagerBuilder.create()
|
||||
.setDefaultConnectionConfig(connectionConfig)
|
||||
.build())
|
||||
.setDefaultRequestConfig(requestConfig)
|
||||
.addRequestInterceptorFirst((request, context, execChain) -> {
|
||||
request.addHeader(HttpHeaders.ACCEPT_CHARSET, "UTF-8");
|
||||
request.addHeader(HttpHeaders.ACCEPT_ENCODING, "gzip");
|
||||
request.addHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.getMimeType());
|
||||
request.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType());
|
||||
if (request instanceof ClassicHttpRequest classicRequest) {
|
||||
auth.applyAuth(classicRequest);
|
||||
}
|
||||
})
|
||||
.build();
|
||||
}
|
||||
|
||||
private <T extends AbstractResponse> T executeRequest(ClassicHttpRequest request,
|
||||
Class<T> responseType)
|
||||
throws CloudflareApiException {
|
||||
String logUri = null;
|
||||
try (CloseableHttpClient client = createHttpClient()) {
|
||||
ResultWrapper result = client.execute(request,
|
||||
(ClassicHttpResponse response) -> new ResultWrapper(response.getCode(),
|
||||
EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8)));
|
||||
|
||||
|
||||
T respObj = objectMapper.readValue(result.responseBody, responseType);
|
||||
if (!respObj.getResponseResultInfo().isSuccess()) {
|
||||
log.error("API error.");
|
||||
StringBuilder errorMessage = new StringBuilder("API error");
|
||||
if (!respObj.getResponseResultInfo().getErrors().isEmpty()) {
|
||||
errorMessage.append(": ");
|
||||
respObj.getResponseResultInfo().getErrors().forEach(e -> {
|
||||
log.error(" - {}", e.toString());
|
||||
errorMessage.append(e).append("; ");
|
||||
});
|
||||
// Remove trailing "; "
|
||||
if (errorMessage.toString().endsWith("; ")) {
|
||||
errorMessage.setLength(errorMessage.length() - 2);
|
||||
}
|
||||
}
|
||||
throw new CloudflareApiException(errorMessage.toString());
|
||||
}
|
||||
logUri = request.getRequestUri();
|
||||
if (result.statusCode >= 200 && result.statusCode < 300) {
|
||||
return respObj;
|
||||
} else {
|
||||
log.error("{} request failed for URL {}: Status {}", request.getMethod(), request.getUri(),
|
||||
result.statusCode);
|
||||
throw new CloudflareApiException(
|
||||
request.getMethod() + " request failed with status code: " + result.statusCode);
|
||||
}
|
||||
} catch (JacksonException e) {
|
||||
log.error("JSON parsing error for request to {}", logUri, e);
|
||||
throw new CloudflareApiException("Error processing JSON response", e);
|
||||
} catch (Exception e) {
|
||||
throw new CloudflareApiException("Unexpected error!", e);
|
||||
String requestInfo = request.getMethod() + " " + request.getRequestUri();
|
||||
ResultWrapper result;
|
||||
try {
|
||||
result = httpClient.execute(request, (ClassicHttpResponse response) -> new ResultWrapper(
|
||||
response.getCode(),
|
||||
response.getEntity() == null ? ""
|
||||
: EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8)));
|
||||
} catch (IOException e) {
|
||||
throw new CloudflareApiException("Request failed: " + requestInfo, e);
|
||||
}
|
||||
|
||||
boolean httpSuccess = result.statusCode >= 200 && result.statusCode < 300;
|
||||
T respObj;
|
||||
try {
|
||||
respObj = objectMapper.readValue(result.responseBody, responseType);
|
||||
} catch (JacksonException e) {
|
||||
if (!httpSuccess) {
|
||||
// e.g. an HTML error page of a proxy
|
||||
throw buildException(requestInfo + " failed with status code " + result.statusCode,
|
||||
result.statusCode, null);
|
||||
}
|
||||
throw new CloudflareApiException("Error processing JSON response of " + requestInfo, e);
|
||||
}
|
||||
|
||||
ResponseResultInfo resultInfo = respObj.getResponseResultInfo();
|
||||
boolean apiSuccess = resultInfo != null && resultInfo.isSuccess();
|
||||
if (!httpSuccess || !apiSuccess) {
|
||||
List<ResponseResultInfo.Error> errors = resultInfo == null ? null : resultInfo.getErrors();
|
||||
String message = "API error";
|
||||
if (errors != null && !errors.isEmpty()) {
|
||||
message += ": " + errors.stream().map(Object::toString).collect(Collectors.joining("; "));
|
||||
}
|
||||
log.debug("{} failed with status code {}: {}", requestInfo, result.statusCode, message);
|
||||
throw buildException(message, result.statusCode, errors);
|
||||
}
|
||||
return respObj;
|
||||
}
|
||||
|
||||
private static CloudflareApiException buildException(String message, int statusCode,
|
||||
List<ResponseResultInfo.Error> errors) {
|
||||
if (statusCode == HttpStatus.SC_NOT_FOUND) {
|
||||
return new CloudflareNotFoundException(message, statusCode, errors);
|
||||
}
|
||||
return new CloudflareApiException(message, statusCode, errors);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -2,6 +2,7 @@ package codes.thischwa.cf;
|
||||
|
||||
import codes.thischwa.cf.fluent.ZoneOperations;
|
||||
import codes.thischwa.cf.fluent.ZoneOperationsImpl;
|
||||
import codes.thischwa.cf.model.AbstractMultipleResponse;
|
||||
import codes.thischwa.cf.model.AbstractResponse;
|
||||
import codes.thischwa.cf.model.BatchEntry;
|
||||
import codes.thischwa.cf.model.BatchResponse;
|
||||
@@ -10,15 +11,21 @@ import codes.thischwa.cf.model.RecordEntity;
|
||||
import codes.thischwa.cf.model.RecordMultipleResponse;
|
||||
import codes.thischwa.cf.model.RecordSingleResponse;
|
||||
import codes.thischwa.cf.model.RecordType;
|
||||
import codes.thischwa.cf.model.ResponseEntity;
|
||||
import codes.thischwa.cf.model.ResultInfo;
|
||||
import codes.thischwa.cf.model.ZoneEntity;
|
||||
import codes.thischwa.cf.model.ZoneMultipleResponse;
|
||||
import java.net.IDN;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
@@ -28,26 +35,30 @@ import org.jetbrains.annotations.Nullable;
|
||||
* records and zones within the Cloudflare system, including creating, updating, retrieving, and
|
||||
* deleting DNS records.
|
||||
*
|
||||
* <p>The client is thread-safe and should be reused. It holds a pool of HTTP connections, which is
|
||||
* released by {@link #close()}.
|
||||
*
|
||||
* <p>Example with API token authentication (recommended):
|
||||
* <pre><code>
|
||||
* // Create a new CfDnsClient instance with API token
|
||||
* CfDnsClient cfDnsClient = new CfDnsClientBuilder()
|
||||
* try (CfDnsClient cfDnsClient = new CfDnsClientBuilder()
|
||||
* .withApiTokenAuth("your-api-token")
|
||||
* .build();
|
||||
* .build()) {
|
||||
*
|
||||
* // Retrieve a zone
|
||||
* ZoneEntity zone = cfDnsClient.zoneGet("example.com");
|
||||
* System.out.println("Zone ID: " + zone.getId());
|
||||
* // Retrieve a zone
|
||||
* ZoneEntity zone = cfDnsClient.zoneGet("example.com");
|
||||
* System.out.println("Zone ID: " + zone.getId());
|
||||
*
|
||||
* // Retrieve records of a subdomain
|
||||
* List<RecordEntity> records = cfDnsClient.recordList(zone, "sld");
|
||||
* records.forEach(record ->
|
||||
* System.out.println("Record Type: " + record.getType() + ", Value: " + record.getContent())
|
||||
* );
|
||||
* // Retrieve records of a subdomain
|
||||
* List<RecordEntity> records = cfDnsClient.recordListBySubdomain(zone, "www");
|
||||
* records.forEach(record ->
|
||||
* System.out.println("Record Type: " + record.getType() + ", Value: " + record.getContent())
|
||||
* );
|
||||
*
|
||||
* // Create a record for the subdomain "api"
|
||||
* RecordEntity created = cfDnsClient.recordCreateSld(zone, "api", 60, RecordType.A, "192.168.1.10");
|
||||
* System.out.println("Created Record ID: " + created.getId());
|
||||
* // Create a record for the subdomain "api"
|
||||
* RecordEntity created = cfDnsClient.recordCreateSubdomain(zone, "api", 60, RecordType.A, "192.168.1.10");
|
||||
* System.out.println("Created Record ID: " + created.getId());
|
||||
* }
|
||||
* </code></pre>
|
||||
*
|
||||
* <p>Example with email/key authentication (legacy):
|
||||
@@ -66,21 +77,44 @@ import org.jetbrains.annotations.Nullable;
|
||||
* .build();
|
||||
* </code></pre>
|
||||
*
|
||||
* <p>Example with custom base URL:
|
||||
* <p>Example specifying the Cloudflare API base URL:
|
||||
* <pre><code>
|
||||
* CfDnsClient cfDnsClient = new CfDnsClientBuilder()
|
||||
* .withApiTokenAuth("your-api-token")
|
||||
* .withBaseUrl("https://custom-api.example.com")
|
||||
* .withBaseUrl(CfDnsClientBuilder.DEFAULT_BASEURL)
|
||||
* .build();
|
||||
* </code></pre>
|
||||
*/
|
||||
@Slf4j
|
||||
public class CfDnsClient extends CfBasicHttpClient {
|
||||
|
||||
/**
|
||||
* Page size used when fetching all DNS records.
|
||||
*/
|
||||
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).
|
||||
*/
|
||||
public static final String APEX = "@";
|
||||
|
||||
private final ResponseValidator responseValidator;
|
||||
|
||||
private final boolean emptyResultThrowsException;
|
||||
|
||||
private final int recordsPerPage;
|
||||
|
||||
/**
|
||||
* Constructs a new instance of {@code CfDnsClient}.
|
||||
*
|
||||
@@ -91,13 +125,69 @@ public class CfDnsClient extends CfBasicHttpClient {
|
||||
* @param auth The authentication mechanism to use (ApiTokenAuth or EmailKeyAuth)
|
||||
*/
|
||||
CfDnsClient(boolean emptyResultThrowsException, String baseUrl, CfDnsClientBuilder.CfAuth auth) {
|
||||
super(baseUrl, auth);
|
||||
this.responseValidator = new ResponseValidator(emptyResultThrowsException);
|
||||
this.emptyResultThrowsException = emptyResultThrowsException;
|
||||
this(emptyResultThrowsException, baseUrl, auth, RECORDS_PER_PAGE);
|
||||
}
|
||||
|
||||
private static String buildFqdn(ZoneEntity zone, String sld) {
|
||||
return sld + "." + zone.getName();
|
||||
/**
|
||||
* Constructs a new instance of {@code CfDnsClient} with a custom page size for fetching all DNS
|
||||
* records. Intended for tests, which need to fetch multiple pages with only a few records.
|
||||
*/
|
||||
CfDnsClient(boolean emptyResultThrowsException, String baseUrl, CfDnsClientBuilder.CfAuth auth,
|
||||
int recordsPerPage) {
|
||||
this(emptyResultThrowsException, baseUrl, auth, recordsPerPage,
|
||||
CfDnsClientBuilder.DEFAULT_CONNECT_TIMEOUT, CfDnsClientBuilder.DEFAULT_RESPONSE_TIMEOUT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a new instance of {@code CfDnsClient} with all settings.
|
||||
*/
|
||||
CfDnsClient(boolean emptyResultThrowsException, String baseUrl, CfDnsClientBuilder.CfAuth auth,
|
||||
int recordsPerPage, Duration connectTimeout, Duration responseTimeout) {
|
||||
super(baseUrl, auth, connectTimeout, responseTimeout);
|
||||
this.responseValidator = new ResponseValidator(emptyResultThrowsException);
|
||||
this.emptyResultThrowsException = emptyResultThrowsException;
|
||||
this.recordsPerPage = recordsPerPage;
|
||||
}
|
||||
|
||||
/**
|
||||
* Characters which can't be part of a DNS name, but are typical for injection attempts. Further
|
||||
* validation is done by Cloudflare; the values are URL-encoded anyway. A slash isn't rejected,
|
||||
* because it's valid in classless reverse delegation names (RFC 2317).
|
||||
*/
|
||||
private static final Pattern INVALID_NAME_CHARS = Pattern.compile("[\\s\\p{Cntrl}\\\\?#&;|<>\"'`]");
|
||||
|
||||
/**
|
||||
* Validates a zone name or subdomain before it's used in a request.
|
||||
*
|
||||
* @throws IllegalArgumentException if the name is {@code null}, blank or contains invalid
|
||||
* characters
|
||||
*/
|
||||
private static String validateName(String name, String kind) {
|
||||
if (name == null || name.isBlank()) {
|
||||
throw new IllegalArgumentException(kind + " must not be null or blank");
|
||||
}
|
||||
if (INVALID_NAME_CHARS.matcher(name).find()) {
|
||||
throw new IllegalArgumentException("Invalid characters in " + kind + ": " + name);
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
private static String buildFqdn(ZoneEntity zone, String subdomain) {
|
||||
validateName(subdomain, "subdomain");
|
||||
if (APEX.equals(subdomain)) {
|
||||
return zone.getName();
|
||||
}
|
||||
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();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -129,33 +219,50 @@ public class CfDnsClient extends CfBasicHttpClient {
|
||||
*
|
||||
* @param zoneName the name of the DNS zone (e.g., "example.com")
|
||||
* @return a ZoneOperations instance for chaining operations
|
||||
* @throws CloudflareApiException if the zone cannot be found or accessed
|
||||
* @throws CloudflareNotFoundException if the zone doesn't exist
|
||||
* @throws CloudflareApiException if the zone cannot be accessed
|
||||
* @throws IllegalArgumentException if the name is blank or contains invalid characters
|
||||
*/
|
||||
public ZoneOperations zone(String zoneName) throws CloudflareApiException {
|
||||
ZoneEntity zoneEntity = zoneGet(zoneName);
|
||||
if (zoneEntity == null) {
|
||||
throw new CloudflareNotFoundException("Zone not found: " + zoneName);
|
||||
}
|
||||
return new ZoneOperationsImpl(this, zoneEntity);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves a list of all zones from the Cloudflare API.
|
||||
* Retrieves a list of all zones from the Cloudflare API. If there are more zones than fit on one
|
||||
* page, all pages are fetched.
|
||||
*
|
||||
* @return A list of ZoneEntity objects representing the zones retrieved from the Cloudflare API.
|
||||
* @throws CloudflareApiException If an error occurs during the API request or response handling.
|
||||
*/
|
||||
public List<ZoneEntity> zoneList() throws CloudflareApiException {
|
||||
return zoneList(PagingRequest.defaultPaging());
|
||||
return getAllPages(CfRequest.ZONE_LIST.buildPath(), ZoneMultipleResponse.class,
|
||||
PagingRequest.DEFAULT_PAGE_SIZE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves a list of all 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
|
||||
* filtering zone data
|
||||
* @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
|
||||
* processing
|
||||
* @throws IllegalArgumentException if the page size is outside the range 5 to 50
|
||||
*/
|
||||
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());
|
||||
ZoneMultipleResponse response = getRequest(endpoint, ZoneMultipleResponse.class);
|
||||
checkResponse(response);
|
||||
@@ -166,124 +273,135 @@ public class CfDnsClient extends CfBasicHttpClient {
|
||||
* Retrieves detailed information about a specific zone by its name.
|
||||
*
|
||||
* @param name The name of the zone to retrieve information for.
|
||||
* @return A {@link ZoneEntity} object that contains details of the specified zone.
|
||||
* @throws CloudflareApiException If an error occurs while making the API request or processing
|
||||
* the response.
|
||||
* @return A {@link ZoneEntity} object that contains details of the specified zone, or
|
||||
* {@code null} if the zone doesn't exist and 'emptyResultThrowsException' is disabled.
|
||||
* @throws CloudflareNotFoundException If the zone doesn't exist and 'emptyResultThrowsException'
|
||||
* is enabled.
|
||||
* @throws CloudflareApiException If an error occurs while making the API request or
|
||||
* processing the response.
|
||||
* @throws IllegalArgumentException if the name is blank or contains invalid characters
|
||||
*/
|
||||
@Nullable
|
||||
public ZoneEntity zoneGet(String name) throws CloudflareApiException {
|
||||
String endpoint = CfRequest.ZONE_INFO.buildPath(name);
|
||||
String endpoint = CfRequest.ZONE_INFO.buildPath(validateName(name, "zone name"));
|
||||
ZoneMultipleResponse response = getRequest(endpoint, ZoneMultipleResponse.class);
|
||||
checkResponse(response, true);
|
||||
return response.getResult().get(0);
|
||||
List<ZoneEntity> zones = response.getResult();
|
||||
return (zones == null || zones.isEmpty()) ? null : zones.get(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves a list of DNS records for a specified zone, with optional paging support.
|
||||
* Retrieves all DNS records for a specified zone. If there are more records than fit on one
|
||||
* page, all pages are fetched.
|
||||
*
|
||||
* @param zone The zone entity containing information about the target zone.
|
||||
* @param zone The zone entity containing information about the target 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.
|
||||
*/
|
||||
public List<RecordEntity> recordList(ZoneEntity zone) throws CloudflareApiException {
|
||||
return recordList(zone, (PagingRequest) null);
|
||||
return recordList(zone, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves a list of DNS records for a specified zone, with optional paging support.
|
||||
* Retrieves DNS records for a specified zone, with optional paging support.
|
||||
*
|
||||
* @param zone The zone entity containing information about the target zone.
|
||||
* @param pagingRequest The paging request containing parameters such as page size and number.
|
||||
* 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.
|
||||
* @throws CloudflareApiException If an error occurs during the API request or response processing.
|
||||
*/
|
||||
public List<RecordEntity> recordList(ZoneEntity zone, @Nullable PagingRequest pagingRequest) throws CloudflareApiException {
|
||||
PagingRequest pr = pagingRequest == null ? PagingRequest.defaultPaging() : pagingRequest;
|
||||
String endpoint = pr.addQueryString(CfRequest.RECORD_LIST.buildPath(zone.getId()));
|
||||
RecordMultipleResponse resp = getRequest(endpoint, RecordMultipleResponse.class);
|
||||
public List<RecordEntity> recordList(ZoneEntity zone, @Nullable PagingRequest pagingRequest)
|
||||
throws CloudflareApiException {
|
||||
String path = appendQuery(CfRequest.RECORD_LIST.buildPath(zone.getId()), RECORD_ORDER);
|
||||
if (pagingRequest == null) {
|
||||
return filterAndSetZoneRecords(zone, null,
|
||||
getAllPages(path, RecordMultipleResponse.class, recordsPerPage));
|
||||
}
|
||||
RecordMultipleResponse resp = getRequest(pagingRequest.addQueryString(path), RecordMultipleResponse.class);
|
||||
checkResponse(resp);
|
||||
return resp.getResult();
|
||||
return filterAndSetZoneRecords(zone, null, resp.getResult());
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves DNS records for the specified second-level domain (SLD) within a zone.
|
||||
* Retrieves DNS records for the specified subdomain within a zone.
|
||||
* Optionally, filters by one or more DNS record types.
|
||||
*
|
||||
* @param zone the zone entity representing the DNS zone to query
|
||||
* @param sld the second-level domain (SLD) to filter the records
|
||||
* @return a list of RecordEntity objects that match the specified SLD within the zone
|
||||
* @throws CloudflareNotFoundException if the specified SLD is not found in the zone
|
||||
* @throws CloudflareApiException if an error occurs while interacting with the Cloudflare API
|
||||
*/
|
||||
public List<RecordEntity> recordList(ZoneEntity zone, String sld) throws CloudflareApiException {
|
||||
return recordList(zone, sld, (RecordType[]) null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves DNS records for the specified second-level domain (SLD) within a zone.
|
||||
* Optionally, filters by one or more DNS getRecord types.
|
||||
*
|
||||
* @param zone The zone entity containing information about the domain zone.
|
||||
* @param sld The second-level domain (SLD) for which to retrieve DNS records.
|
||||
* @param types Optional parameter specifying one or more DNS getRecord types to filter the results.
|
||||
* @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");
|
||||
* 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
|
||||
* all types are returned.
|
||||
* @return A list of {@code RecordEntity} objects representing the DNS records for the specified domain.
|
||||
* @throws CloudflareNotFoundException if the specified SLD is not found in the zone
|
||||
* @throws CloudflareNotFoundException if no records were found and 'emptyResultThrowsException'
|
||||
* is enabled
|
||||
* @throws CloudflareApiException if an error occurs while interacting with the Cloudflare API
|
||||
* @throws IllegalArgumentException if the subdomain is blank, contains invalid characters or
|
||||
* cannot be converted to Punycode
|
||||
*/
|
||||
public List<RecordEntity> recordList(ZoneEntity zone, String sld, @Nullable RecordType... types)
|
||||
public List<RecordEntity> recordListBySubdomain(ZoneEntity zone, String subdomain,
|
||||
@Nullable RecordType... types)
|
||||
throws CloudflareApiException {
|
||||
String fqdn = buildFqdn(zone, sld);
|
||||
String endpoint = CfRequest.RECORD_LIST_NAME.buildPath(zone.getId(), fqdn);
|
||||
RecordMultipleResponse resp = getRequest(endpoint, RecordMultipleResponse.class);
|
||||
checkResponse(resp, false);
|
||||
List<RecordEntity> recs = resp.getResult();
|
||||
String fqdn = buildFqdn(zone, subdomain);
|
||||
String endpoint = appendQuery(
|
||||
addTypeFilter(CfRequest.RECORD_LIST_NAME.buildPath(zone.getId(), fqdn), types), RECORD_ORDER);
|
||||
List<RecordEntity> recs = getAllPages(endpoint, RecordMultipleResponse.class, recordsPerPage);
|
||||
return filterAndSetZoneRecords(zone, types, recs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves a list of all DNS records for a given zone.
|
||||
* Optionally, filters by one or more DNS getRecord types.
|
||||
* Retrieves all DNS records of the given types for a zone.
|
||||
*
|
||||
* @param zone The zone entity containing information about the domain zone.
|
||||
* @param types Optional parameter specifying one or more DNS getRecord types to filter the results.
|
||||
* @param types Optional DNS record types to filter the results. If none are given, records of all
|
||||
* types are returned.
|
||||
* @return A list of {@code RecordEntity} objects representing the DNS records for the specified zone.
|
||||
* @throws CloudflareApiException if an error occurs while interacting with the Cloudflare API
|
||||
* @throws CloudflareNotFoundException if no records were found and 'emptyResultThrowsException'
|
||||
* is enabled
|
||||
* @throws CloudflareApiException if an error occurs while interacting with the Cloudflare API
|
||||
*/
|
||||
public List<RecordEntity> recordList(ZoneEntity zone, RecordType... types)
|
||||
public List<RecordEntity> recordListByType(ZoneEntity zone, @Nullable RecordType... types)
|
||||
throws CloudflareApiException {
|
||||
String endpoint = CfRequest.RECORD_LIST.buildPath(zone.getId());
|
||||
RecordMultipleResponse resp = getRequest(endpoint, RecordMultipleResponse.class);
|
||||
checkResponse(resp, false);
|
||||
List<RecordEntity> recs = resp.getResult();
|
||||
String endpoint = appendQuery(
|
||||
addTypeFilter(CfRequest.RECORD_LIST.buildPath(zone.getId()), types), RECORD_ORDER);
|
||||
List<RecordEntity> recs = getAllPages(endpoint, RecordMultipleResponse.class, recordsPerPage);
|
||||
return filterAndSetZoneRecords(zone, types, recs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new DNS getRecord for a given second-level domain (SLD) 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 getRecord is to be created.
|
||||
* @param sld The second-level domain (SLD) for which the DNS getRecord is being created.
|
||||
* @param ttl The time-to-live (TTL) value for the DNS getRecord in seconds.
|
||||
* @param type The RecordType specifying the type of the DNS getRecord (e.g., A, AAAA, CNAME).
|
||||
* @param content The content of the DNS getRecord (e.g., IP address for A/AAAA records, target
|
||||
* domain for CNAME).
|
||||
* @return The created RecordEntity object containing details of the newly created DNS getRecord.
|
||||
* @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");
|
||||
* 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 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
|
||||
* domain for CNAME).
|
||||
* @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 getRecord.
|
||||
* or creating the record.
|
||||
* @throws IllegalArgumentException if the subdomain is blank, contains invalid characters or
|
||||
* cannot be converted to Punycode
|
||||
*/
|
||||
public RecordEntity recordCreateSld(ZoneEntity zone, String sld, int ttl, RecordType type,
|
||||
String content) throws CloudflareApiException {
|
||||
String fqdn = buildFqdn(zone, sld);
|
||||
public RecordEntity recordCreateSubdomain(ZoneEntity zone, String subdomain, int ttl, RecordType type,
|
||||
String content) throws CloudflareApiException {
|
||||
String fqdn = buildFqdn(zone, subdomain);
|
||||
return recordCreate(zone, fqdn, ttl, type, content);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a DNS getRecord in the specified DNS zone with the provided details.
|
||||
* Creates a DNS record in the specified DNS zone with the provided details.
|
||||
*
|
||||
* @param zone the DNS zone in which the getRecord will be created
|
||||
* @param name the name of the DNS getRecord (e.g., www.example.com)
|
||||
* @param ttl the time-to-live (TTL) value for the DNS getRecord
|
||||
* @param type the type of the DNS getRecord (e.g., A, AAAA, CNAME)
|
||||
* @param content the content or value of the DNS getRecord
|
||||
* @return the created DNS getRecord as a {@link RecordEntity} object
|
||||
* @param zone the DNS zone in which the record will be created
|
||||
* @param name the name of the DNS record (e.g., www.example.com)
|
||||
* @param ttl the time-to-live (TTL) value for the DNS record
|
||||
* @param type the type of the DNS record (e.g., A, AAAA, CNAME)
|
||||
* @param content the content or value of the DNS record
|
||||
* @return the created DNS record as a {@link RecordEntity} object
|
||||
* @throws CloudflareApiException if an error occurs while interacting with the Cloudflare API
|
||||
*/
|
||||
public RecordEntity recordCreate(ZoneEntity zone, String name, int ttl, RecordType type,
|
||||
@@ -293,51 +411,54 @@ public class CfDnsClient extends CfBasicHttpClient {
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new DNS getRecord in the specified zone using the Cloudflare API.
|
||||
* Creates a new DNS record in the specified zone using the Cloudflare API.
|
||||
*
|
||||
* @param zone The zone entity where the getRecord will be created. Contains details such as zone
|
||||
* @param zone The zone entity where the record will be created. Contains details such as zone
|
||||
* ID.
|
||||
* @param rec The getRecord entity representing the DNS getRecord to be created, including its
|
||||
* attributes.
|
||||
* @return The created getRecord entity as returned by the Cloudflare API.
|
||||
* @param rec The record entity representing the DNS record to be created, including its
|
||||
* attributes. Read-only attributes (e.g. ID, timestamps) are ignored, the given
|
||||
* object isn't modified.
|
||||
* @return The created record entity as returned by the Cloudflare API.
|
||||
* @throws CloudflareApiException If an error occurs while interacting with the Cloudflare API.
|
||||
*/
|
||||
public RecordEntity recordCreate(ZoneEntity zone, RecordEntity rec)
|
||||
throws CloudflareApiException {
|
||||
String endpoint = CfRequest.RECORD_CREATE.buildPath(zone.getId());
|
||||
RecordSingleResponse resp = postRequest(endpoint, rec, RecordSingleResponse.class);
|
||||
RecordEntity payload = writableCopy(rec, false);
|
||||
RecordSingleResponse resp = postRequest(endpoint, payload, RecordSingleResponse.class);
|
||||
checkResponse(resp);
|
||||
log.info("Record {} of type {} successful created.", rec.getSld(), rec.getType());
|
||||
log.info("Record {} of type {} successful created.", rec.getSubdomain(), rec.getType());
|
||||
RecordEntity retRec = resp.getResult();
|
||||
retRec.setZoneId(zone.getId());
|
||||
assignZone(retRec, zone);
|
||||
return retRec;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a DNS getRecord of the specified type within a given zone on the Cloudflare API.
|
||||
* Deletes a DNS record of the specified type within a given zone on the Cloudflare API.
|
||||
*
|
||||
* @param zone The zone entity that specifies the zone in which the getRecord exists.
|
||||
* @param rec The getRecord entity that represents the DNS getRecord to be deleted.
|
||||
* @return {@code true} if the DNS getRecord was successfully deleted; {@code false} otherwise.
|
||||
* @param zone The zone entity that specifies the zone in which the record exists.
|
||||
* @param rec The record entity that represents the DNS record to be deleted.
|
||||
* @return {@code true} if the DNS record was successfully deleted; {@code false} otherwise.
|
||||
* @throws CloudflareApiException if there is an issue during the API communication, or the
|
||||
* request fails for any reason.
|
||||
*/
|
||||
public boolean recordDelete(ZoneEntity zone, RecordEntity rec) throws CloudflareApiException {
|
||||
boolean changed = recordDelete(zone, rec.getId());
|
||||
if (changed) {
|
||||
log.debug("Record {} of the type [{}] successful deleted.", rec.getSld(), rec.getType());
|
||||
log.debug("Record {} of the type [{}] successful deleted.", rec.getSubdomain(), rec.getType());
|
||||
} else {
|
||||
log.warn("Record {} of the type [{}] was not deleted.", rec.getSld(), rec.getType());
|
||||
log.warn("Record {} of the type [{}] was not deleted.", rec.getSubdomain(), rec.getType());
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a DNS getRecord of the specified type within a given zone on the Cloudflare API.
|
||||
* Deletes a DNS record of the specified type within a given zone on the Cloudflare API.
|
||||
*
|
||||
* @param zone The zone entity that specifies the zone in which the getRecord exists.
|
||||
* @param id The getRecord entity that represents the DNS getRecord to be deleted.
|
||||
* @return {@code true} if the DNS getRecord was successfully deleted; {@code false} otherwise.
|
||||
* @param zone The zone entity that specifies the zone in which the record exists.
|
||||
* @param id The ID of the DNS record to be deleted.
|
||||
* @return {@code true} if the API confirms the deletion of the record with the given ID;
|
||||
* {@code false} otherwise.
|
||||
* @throws CloudflareApiException if there is an issue during the API communication or the request
|
||||
* fails for any reason.
|
||||
*/
|
||||
@@ -345,48 +466,58 @@ public class CfDnsClient extends CfBasicHttpClient {
|
||||
String endpoint = CfRequest.RECORD_DELETE.buildPath(zone.getId(), id);
|
||||
RecordSingleResponse resp = deleteRequest(endpoint, RecordSingleResponse.class);
|
||||
checkResponse(resp);
|
||||
log.debug("Record id#{} successful deleted.", id);
|
||||
return resp.getResult().getId().equals(id);
|
||||
RecordEntity deleted = resp.getResult();
|
||||
boolean confirmed = deleted != null && id.equals(deleted.getId());
|
||||
if (confirmed) {
|
||||
log.debug("Record id#{} successfully deleted.", id);
|
||||
}
|
||||
return confirmed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates an existing DNS getRecord in a specified Cloudflare zone.
|
||||
* Updates an existing DNS record in a specified Cloudflare zone (partial update, attributes
|
||||
* which are {@code null} remain unchanged).
|
||||
*
|
||||
* @param zone the zone entity containing the ID of the target zone
|
||||
* @param rec the getRecord entity containing the ID of the DNS getRecord to be updated and its updated
|
||||
* data
|
||||
* @return the updated getRecord entity as returned by the Cloudflare API
|
||||
* @param rec the record entity containing the ID of the DNS record to be updated and its updated
|
||||
* data. Read-only attributes (e.g. timestamps) are ignored, the given object isn't
|
||||
* modified.
|
||||
* @return the updated record entity as returned by the Cloudflare API
|
||||
* @throws CloudflareApiException if an error occurs while interacting with the Cloudflare API
|
||||
*/
|
||||
public RecordEntity recordUpdate(ZoneEntity zone, RecordEntity rec)
|
||||
throws CloudflareApiException {
|
||||
// reset all dates, it causes an API issue
|
||||
rec.setModifiedOn(null);
|
||||
rec.setCreatedOn(null);
|
||||
String endpoint = CfRequest.RECORD_UPDATE.buildPath(zone.getId(), rec.getId());
|
||||
RecordSingleResponse resp = patchRequest(endpoint, rec, RecordSingleResponse.class);
|
||||
RecordEntity payload = writableCopy(rec, false);
|
||||
RecordSingleResponse resp = patchRequest(endpoint, payload, RecordSingleResponse.class);
|
||||
checkResponse(resp);
|
||||
log.info("Record {} of type {} successful updated.", rec.getSld(), rec.getType());
|
||||
return resp.getResult();
|
||||
log.info("Record {} of type {} successful updated.", rec.getSubdomain(), rec.getType());
|
||||
RecordEntity retRec = resp.getResult();
|
||||
assignZone(retRec, zone);
|
||||
return retRec;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes DNS records of a specific type within a given zone if they exist. If no getRecord of the
|
||||
* specified type exists, it logs this occurrence without throwing an exception.
|
||||
* Attempts to delete DNS records of the specified types within a given zone. If no record types
|
||||
* 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 getRecord exists.
|
||||
* @param sld The second-level domain for which the getRecord is being checked.
|
||||
* @param recordTypes The types of DNS records that should be deleted if they exist.
|
||||
* @throws CloudflareApiException If an error occurs during API communication.
|
||||
* @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 recordTypes The DNS record types to delete; if empty or {@code null}, all types are selected.
|
||||
* @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 sld, RecordType... recordTypes)
|
||||
public void recordDeleteTypeIfExists(ZoneEntity zone, String subdomain, RecordType... recordTypes)
|
||||
throws CloudflareApiException {
|
||||
String fqdn = buildFqdn(zone, sld);
|
||||
String fqdn = buildFqdn(zone, subdomain);
|
||||
List<RecordEntity> recs;
|
||||
try {
|
||||
recs = recordList(zone, sld, recordTypes);
|
||||
recs = recordListBySubdomain(zone, subdomain, recordTypes);
|
||||
} catch (CloudflareNotFoundException e) {
|
||||
log.trace("No getRecord of type {} found for domain {}.", recordTypes, fqdn);
|
||||
log.trace("No record of type {} found for domain {}.", recordTypes, fqdn);
|
||||
return;
|
||||
}
|
||||
for (RecordEntity rec : recs) {
|
||||
@@ -394,13 +525,13 @@ public class CfDnsClient extends CfBasicHttpClient {
|
||||
recordDelete(zone, rec);
|
||||
log.info("Record {} of type {} successful deleted.", fqdn, recordTypes);
|
||||
} catch (CloudflareApiException e) {
|
||||
log.error("Failed to delete getRecord {} of type {} for zone {}: {}", fqdn, recordTypes, zone.getName(), e.getMessage());
|
||||
log.error("Failed to delete record {} of type {} for zone {}: {}", fqdn, recordTypes, zone.getName(), e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes a batch of DNS getRecord operations (POST, PUT, PATCH, DELETE) for a specified zone.
|
||||
* Processes a batch of DNS record operations (POST, PUT, PATCH, DELETE) for a specified zone.
|
||||
* This method builds and cleans the input records, sends the batch request to the Cloudflare API,
|
||||
* and returns a result containing processed batch entries.
|
||||
*
|
||||
@@ -408,7 +539,8 @@ public class CfDnsClient extends CfBasicHttpClient {
|
||||
* @param postRecords A list of DNS records to be created (POST). This parameter is nullable.
|
||||
* @param putRecords A list of DNS records to be fully replaced (PUT). This parameter is nullable.
|
||||
* @param patchRecords A list of DNS records to be partially updated (PATCH). This parameter is nullable.
|
||||
* @param deleteRecords A list of DNS records to be deleted (DELETE). This parameter is nullable.
|
||||
* @param deleteRecords A list of DNS records to be deleted (DELETE), only the IDs are used. This
|
||||
* parameter is nullable.
|
||||
* @return The resulting {@link BatchEntry} containing the processed records after the batch operation.
|
||||
* @throws CloudflareApiException If an error occurs while communicating with the Cloudflare API.
|
||||
*/
|
||||
@@ -416,18 +548,18 @@ public class CfDnsClient extends CfBasicHttpClient {
|
||||
@Nullable List<RecordEntity> patchRecords, @Nullable List<RecordEntity> deleteRecords)
|
||||
throws CloudflareApiException {
|
||||
BatchEntry batchEntry = new BatchEntry();
|
||||
// build 'clean' getRecord entries
|
||||
// build 'clean' record entries, the given records aren't modified
|
||||
if (postRecords != null) {
|
||||
batchEntry.setPosts(cleanRecordsForPostOrPut(postRecords));
|
||||
batchEntry.setPosts(postRecords.stream().map(rec -> writableCopy(rec, false)).toList());
|
||||
}
|
||||
if (putRecords != null) {
|
||||
batchEntry.setPuts(cleanRecordsForPostOrPut(putRecords));
|
||||
batchEntry.setPuts(putRecords.stream().map(rec -> writableCopy(rec, true)).toList());
|
||||
}
|
||||
if (patchRecords != null) {
|
||||
batchEntry.setPatches(cleanRecordsForPatch(patchRecords));
|
||||
batchEntry.setPatches(patchRecords.stream().map(rec -> writableCopy(rec, true)).toList());
|
||||
}
|
||||
if (deleteRecords != null) {
|
||||
batchEntry.setDeletes(cleanRecordsForDelete(deleteRecords));
|
||||
batchEntry.setDeletes(deleteRecords.stream().map(CfDnsClient::idOnly).toList());
|
||||
}
|
||||
|
||||
String endpoint = CfRequest.RECORD_BATCH.buildPath(zone.getId());
|
||||
@@ -436,21 +568,27 @@ public class CfDnsClient extends CfBasicHttpClient {
|
||||
|
||||
// set zone id
|
||||
BatchEntry result = resp.getResult();
|
||||
setZoneIdForBatchResults(result, zone.getId());
|
||||
setZoneForBatchResults(result, zone);
|
||||
return result;
|
||||
}
|
||||
|
||||
private List<RecordEntity> filterAndSetZoneRecords(ZoneEntity zone, @Nullable RecordType[] types, List<RecordEntity> recs)
|
||||
private List<RecordEntity> filterAndSetZoneRecords(ZoneEntity zone, @Nullable RecordType[] types,
|
||||
@Nullable List<RecordEntity> recs)
|
||||
throws CloudflareNotFoundException {
|
||||
if (recs == null) {
|
||||
recs = List.of();
|
||||
}
|
||||
List<RecordEntity> filtered;
|
||||
if (types != null && types.length > 0) {
|
||||
Set<RecordType> allowedTypes = new HashSet<>(Arrays.asList(types));
|
||||
Set<String> allowedTypes = Arrays.stream(types).filter(Objects::nonNull)
|
||||
.map(RecordType::getType).collect(Collectors.toSet());
|
||||
filtered = recs.stream()
|
||||
.filter(rec -> allowedTypes.contains(RecordType.valueOf(rec.getType()))).toList();
|
||||
.filter(rec -> allowedTypes.contains(rec.getType()))
|
||||
.collect(Collectors.toCollection(ArrayList::new));
|
||||
} else {
|
||||
filtered = new ArrayList<>(recs);
|
||||
}
|
||||
filtered.forEach(rec -> rec.setZoneId(zone.getId()));
|
||||
filtered.forEach(rec -> assignZone(rec, zone));
|
||||
|
||||
// special exception for an empty result, normally it's done in the RecordValidator
|
||||
if (filtered.isEmpty() && emptyResultThrowsException) {
|
||||
@@ -460,35 +598,131 @@ public class CfDnsClient extends CfBasicHttpClient {
|
||||
}
|
||||
|
||||
|
||||
private List<RecordEntity> cleanRecordsForPostOrPut(List<RecordEntity> records) {
|
||||
List<RecordEntity> cleaned = new ArrayList<>();
|
||||
records.forEach(
|
||||
rec -> cleaned.add(RecordEntity.build(rec.getId(), rec.getSld(), rec.getType(), rec.getTtl(), rec.getContent())));
|
||||
return cleaned;
|
||||
}
|
||||
|
||||
private List<RecordEntity> cleanRecordsForPatch(List<RecordEntity> records) {
|
||||
List<RecordEntity> cleaned = new ArrayList<>();
|
||||
records.forEach(rec -> cleaned.add(RecordEntity.build(rec.getId(), rec.getContent())));
|
||||
return cleaned;
|
||||
}
|
||||
|
||||
private List<RecordEntity> cleanRecordsForDelete(List<RecordEntity> records) {
|
||||
List<RecordEntity> cleaned = new ArrayList<>();
|
||||
records.forEach(
|
||||
rec -> cleaned.add(RecordEntity.build(rec.getId(), rec.getSld(), rec.getType(), null, rec.getContent())));
|
||||
return cleaned;
|
||||
}
|
||||
|
||||
private void setZoneIdForBatchResults(BatchEntry result, String zoneId) {
|
||||
if (result.getPosts() != null) {
|
||||
result.getPosts().forEach(rec -> rec.setZoneId(zoneId));
|
||||
/**
|
||||
* Creates a copy of the record containing only the attributes which can be written to the API.
|
||||
* Read-only attributes like timestamps, zone info, 'proxiable' or 'locked' are omitted.
|
||||
*/
|
||||
private static RecordEntity writableCopy(RecordEntity rec, boolean withId) {
|
||||
RecordEntity copy = new RecordEntity();
|
||||
if (withId) {
|
||||
copy.setId(rec.getId());
|
||||
}
|
||||
if (result.getPuts() != null) {
|
||||
result.getPuts().forEach(rec -> rec.setZoneId(zoneId));
|
||||
copy.setName(rec.getName());
|
||||
copy.setType(rec.getType());
|
||||
copy.setContent(rec.getContent());
|
||||
copy.setTtl(rec.getTtl());
|
||||
copy.setProxied(rec.getProxied());
|
||||
copy.setPriority(rec.getPriority());
|
||||
copy.setComment(rec.getComment());
|
||||
copy.setTags(rec.getTags() == null ? null : new ArrayList<>(rec.getTags()));
|
||||
copy.setData(rec.getData() == null ? null : new LinkedHashMap<>(rec.getData()));
|
||||
return copy;
|
||||
}
|
||||
|
||||
private static RecordEntity idOnly(RecordEntity rec) {
|
||||
RecordEntity copy = new RecordEntity();
|
||||
copy.setId(rec.getId());
|
||||
return copy;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the server-side type filter to the endpoint. The API supports only one type, so the
|
||||
* filter is only added if exactly one type is given. Multiple types are filtered client-side.
|
||||
*/
|
||||
private static String addTypeFilter(String endpoint, @Nullable RecordType[] types) {
|
||||
if (types == null || types.length != 1 || types[0] == null) {
|
||||
return endpoint;
|
||||
}
|
||||
if (result.getPatches() != null) {
|
||||
result.getPatches().forEach(rec -> rec.setZoneId(zoneId));
|
||||
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) {
|
||||
if (result == null) {
|
||||
return;
|
||||
}
|
||||
for (List<RecordEntity> recs : Arrays.asList(result.getPosts(), result.getPuts(),
|
||||
result.getPatches(), result.getDeletes())) {
|
||||
if (recs != null) {
|
||||
recs.forEach(rec -> assignZone(rec, zone));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void assignZone(@Nullable RecordEntity rec, ZoneEntity zone) {
|
||||
if (rec != null) {
|
||||
rec.setZoneId(zone.getId());
|
||||
rec.setZoneName(zone.getName());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 responseType the expected response type
|
||||
* @param perPage the page size to request
|
||||
*/
|
||||
private <E extends ResponseEntity, R extends AbstractMultipleResponse<E>> List<E> getAllPages(
|
||||
String endpoint, Class<R> responseType, int perPage) throws CloudflareApiException {
|
||||
List<E> result = List.of();
|
||||
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) {
|
||||
int page = pagingRequest.page();
|
||||
String pagedEndpoint = pagingRequest.addQueryString(endpoint);
|
||||
R resp = getRequest(pagedEndpoint, responseType);
|
||||
checkResponse(resp);
|
||||
List<E> pageResult = resp.getResult();
|
||||
if (pageResult != null) {
|
||||
for (E entry : pageResult) {
|
||||
if (entry.getId() == null) {
|
||||
withoutId.add(entry);
|
||||
} else {
|
||||
byId.putIfAbsent(entry.getId(), entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
ResultInfo info = resp.getResultInfo();
|
||||
if (info != null && page == 1) {
|
||||
expectedCount = info.totalCount();
|
||||
}
|
||||
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;
|
||||
|
||||
import java.net.URI;
|
||||
import java.time.Duration;
|
||||
import java.util.Locale;
|
||||
import org.apache.hc.core5.http.ClassicHttpRequest;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
/**
|
||||
@@ -16,8 +18,20 @@ public class CfDnsClientBuilder {
|
||||
*/
|
||||
public static final String DEFAULT_BASEURL = "https://api.cloudflare.com/client/v4";
|
||||
|
||||
/**
|
||||
* The default timeout for establishing a connection.
|
||||
*/
|
||||
public static final Duration DEFAULT_CONNECT_TIMEOUT = Duration.ofSeconds(10);
|
||||
|
||||
/**
|
||||
* The default timeout for waiting for the response data.
|
||||
*/
|
||||
public static final Duration DEFAULT_RESPONSE_TIMEOUT = Duration.ofSeconds(30);
|
||||
|
||||
private boolean emptyResultThrowsException;
|
||||
private CfAuth auth;
|
||||
private Duration connectTimeout = DEFAULT_CONNECT_TIMEOUT;
|
||||
private Duration responseTimeout = DEFAULT_RESPONSE_TIMEOUT;
|
||||
|
||||
@Nullable
|
||||
private String baseUrl;
|
||||
@@ -42,14 +56,91 @@ public class CfDnsClientBuilder {
|
||||
* Sets the base URL to be used by the {@code CfDnsClient}.
|
||||
* This method allows configuring the base URL for API requests, overriding any default value.
|
||||
*
|
||||
* @param baseUrl the base URL to be used for API requests
|
||||
* <p>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
|
||||
* @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) {
|
||||
this.baseUrl = baseUrl;
|
||||
public CfDnsClientBuilder withBaseUrl(@Nullable String baseUrl) {
|
||||
this.baseUrl = baseUrl == null ? null : validateBaseUrl(baseUrl);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the timeout for establishing a connection. Default is {@link #DEFAULT_CONNECT_TIMEOUT}.
|
||||
*
|
||||
* @param connectTimeout the connect timeout, must be positive
|
||||
* @return the current instance of {@code CfDnsClientBuilder}, enabling method chaining
|
||||
* @throws IllegalArgumentException if the timeout is {@code null}, zero or negative
|
||||
*/
|
||||
public CfDnsClientBuilder withConnectTimeout(Duration connectTimeout) {
|
||||
this.connectTimeout = validateTimeout(connectTimeout, "Connect timeout");
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the timeout for waiting for the response data. Default is
|
||||
* {@link #DEFAULT_RESPONSE_TIMEOUT}.
|
||||
*
|
||||
* @param responseTimeout the response timeout, must be positive
|
||||
* @return the current instance of {@code CfDnsClientBuilder}, enabling method chaining
|
||||
* @throws IllegalArgumentException if the timeout is {@code null}, zero or negative
|
||||
*/
|
||||
public CfDnsClientBuilder withResponseTimeout(Duration responseTimeout) {
|
||||
this.responseTimeout = validateTimeout(responseTimeout, "Response timeout");
|
||||
return this;
|
||||
}
|
||||
|
||||
private static Duration validateTimeout(Duration timeout, String name) {
|
||||
if (timeout == null || timeout.isZero() || timeout.isNegative()) {
|
||||
throw new IllegalArgumentException(name + " must be positive: " + timeout);
|
||||
}
|
||||
long millis;
|
||||
try {
|
||||
millis = timeout.toMillis();
|
||||
} catch (ArithmeticException e) {
|
||||
throw new IllegalArgumentException(name + " is too large: " + timeout, e);
|
||||
}
|
||||
// the HTTP client works with milliseconds, 0 ms would disable the timeout
|
||||
if (millis < 1) {
|
||||
throw new IllegalArgumentException(name + " must be at least 1 ms: " + timeout);
|
||||
}
|
||||
return timeout;
|
||||
}
|
||||
|
||||
private static String validateBaseUrl(String baseUrl) {
|
||||
URI uri;
|
||||
try {
|
||||
uri = URI.create(baseUrl.strip());
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new IllegalArgumentException("Invalid base URL: " + baseUrl, e);
|
||||
}
|
||||
String 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.
|
||||
* 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
|
||||
* specified options such as base URL, authentication details,
|
||||
* and the exception-handling policy for empty results.
|
||||
* @throws IllegalStateException if no authentication was configured
|
||||
*/
|
||||
public CfDnsClient build() {
|
||||
if (auth == null) {
|
||||
throw new IllegalStateException(
|
||||
"No authentication configured, use withApiTokenAuth(...) or withEmailKeyAuth(...)");
|
||||
}
|
||||
String url = baseUrl == null ? DEFAULT_BASEURL : baseUrl;
|
||||
return new CfDnsClient(emptyResultThrowsException, url, auth);
|
||||
return new CfDnsClient(emptyResultThrowsException, url, auth, CfDnsClient.RECORDS_PER_PAGE,
|
||||
connectTimeout, responseTimeout);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -128,8 +225,8 @@ public class CfDnsClientBuilder {
|
||||
* @param apiToken the Cloudflare API token
|
||||
* @throws IllegalArgumentException if the API token is null or blank
|
||||
*/
|
||||
ApiTokenAuth(@NotNull String apiToken) {
|
||||
if (apiToken.isBlank()) {
|
||||
ApiTokenAuth(String apiToken) {
|
||||
if (apiToken == null || apiToken.isBlank()) {
|
||||
throw new IllegalArgumentException("API token must not be null or blank!");
|
||||
}
|
||||
this.apiToken = apiToken;
|
||||
@@ -157,11 +254,11 @@ public class CfDnsClientBuilder {
|
||||
* @param authKey the API key of the Cloudflare account
|
||||
* @throws IllegalArgumentException if email or key is null or blank
|
||||
*/
|
||||
EmailKeyAuth(@NotNull String authEmail, @NotNull String authKey) {
|
||||
if (authEmail.isBlank()) {
|
||||
EmailKeyAuth(String authEmail, String authKey) {
|
||||
if (authEmail == null || authEmail.isBlank()) {
|
||||
throw new IllegalArgumentException("Authentication email must not be null or blank!");
|
||||
}
|
||||
if (authKey.isBlank()) {
|
||||
if (authKey == null || authKey.isBlank()) {
|
||||
throw new IllegalArgumentException("Authentication key must not be null or blank!");
|
||||
}
|
||||
this.authEmail = authEmail;
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
package codes.thischwa.cf;
|
||||
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import lombok.Getter;
|
||||
|
||||
/**
|
||||
@@ -18,46 +22,54 @@ public enum CfRequest {
|
||||
* name. The endpoint path supports a placeholder for the zone name, which needs to be provided to
|
||||
* construct the complete path.
|
||||
*/
|
||||
ZONE_INFO("/zones?name=%s"),
|
||||
ZONE_INFO("/zones?name={value}"),
|
||||
|
||||
/**
|
||||
* Represents the API endpoint path for retrieving information about DNS records within a
|
||||
* specific DNS zone. The endpoint path includes a placeholder for the zone identifier, which
|
||||
* needs to be provided to construct the complete path.
|
||||
*/
|
||||
RECORD_LIST("/zones/%s/dns_records"),
|
||||
RECORD_LIST("/zones/{id}/dns_records"),
|
||||
/**
|
||||
* Represents the API endpoint path for retrieving information about a DNS getRecord 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
|
||||
* and the getRecord 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 getRecord 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
|
||||
* 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 getRecord within a specific DNS
|
||||
* zone. The endpoint path includes placeholders for the zone identifier and the getRecord
|
||||
* Represents the API endpoint path for updating an existing DNS record within a specific DNS
|
||||
* zone. The endpoint path includes placeholders for the zone identifier and the record
|
||||
* identifier, which need to be provided to construct the complete path.
|
||||
*/
|
||||
RECORD_UPDATE("/zones/%s/dns_records/%s"),
|
||||
RECORD_UPDATE("/zones/{id}/dns_records/{id}"),
|
||||
/**
|
||||
* Represents the API endpoint path for performing batch operations on DNS records within a specific zone.
|
||||
* The placeholder "%s" in the path is intended to be replaced by a zone identifier.
|
||||
* The placeholder in the path is intended to be replaced by a zone identifier.
|
||||
* This constant is used to construct the URL for interacting with the batch DNS records API.
|
||||
*/
|
||||
RECORD_BATCH("/zones/%s/dns_records/batch"),
|
||||
RECORD_BATCH("/zones/{id}/dns_records/batch"),
|
||||
/**
|
||||
* Represents the API endpoint path for deleting an existing DNS getRecord within a specific DNS
|
||||
* zone. The endpoint path includes placeholders for the zone identifier and the getRecord
|
||||
* Represents the API endpoint path for deleting an existing DNS record within a specific DNS
|
||||
* zone. The endpoint path includes placeholders for the zone identifier and the record
|
||||
* identifier, which need to be provided to construct the complete path.
|
||||
*/
|
||||
RECORD_DELETE("/zones/%s/dns_records/%s");
|
||||
RECORD_DELETE("/zones/{id}/dns_records/{id}");
|
||||
|
||||
private static final String ID_PLACEHOLDER = "{id}";
|
||||
private static final Pattern PLACEHOLDER = Pattern.compile("\\{(id|value)}");
|
||||
|
||||
/**
|
||||
* Allowed characters of Cloudflare identifiers (zone and record IDs). Prevents e.g. path
|
||||
* traversal with IDs like "../..".
|
||||
*/
|
||||
private static final Pattern ID_PATTERN = Pattern.compile("[A-Za-z0-9]{1,64}");
|
||||
|
||||
private static final char VAR_IDENTIFICATION = '%';
|
||||
private final String path;
|
||||
|
||||
CfRequest(String path) {
|
||||
@@ -65,21 +77,45 @@ public enum CfRequest {
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs the complete API endpoint path by formatting the base path with the provided
|
||||
* arguments.
|
||||
* Constructs the complete API endpoint path by replacing the placeholders with the provided
|
||||
* arguments. Identifiers ({@code {id}}) are validated, query values ({@code {value}}) are
|
||||
* URL-encoded.
|
||||
*
|
||||
* @param vars the arguments to format the path string with; these are typically specific
|
||||
* identifiers or parameters required by the API endpoint.
|
||||
* @param vars the arguments to replace the placeholders with, in the order of the placeholders
|
||||
* @return the fully constructed API endpoint path as a string.
|
||||
* @throws IllegalArgumentException if the number of arguments doesn't match the placeholders, an
|
||||
* argument is {@code null} or an identifier is invalid
|
||||
*/
|
||||
String buildPath(Object... vars) {
|
||||
long varCount = path.chars().filter(c -> c == VAR_IDENTIFICATION).count();
|
||||
Matcher matcher = PLACEHOLDER.matcher(path);
|
||||
long varCount = matcher.results().count();
|
||||
if (varCount != vars.length) {
|
||||
throw new IllegalArgumentException(
|
||||
String.format(
|
||||
"The number of variables (%d) does not match the number of parameters (%d) in the path string: %s",
|
||||
vars.length, varCount, path));
|
||||
}
|
||||
return String.format(path, vars);
|
||||
matcher.reset();
|
||||
StringBuilder sb = new StringBuilder();
|
||||
int i = 0;
|
||||
while (matcher.find()) {
|
||||
Object arg = vars[i++];
|
||||
if (arg == null) {
|
||||
throw new IllegalArgumentException("Path variable must not be null: " + path);
|
||||
}
|
||||
String value = arg.toString();
|
||||
String replacement;
|
||||
if (ID_PLACEHOLDER.equals(matcher.group())) {
|
||||
if (!ID_PATTERN.matcher(value).matches()) {
|
||||
throw new IllegalArgumentException("Invalid identifier: " + value);
|
||||
}
|
||||
replacement = value;
|
||||
} else {
|
||||
replacement = URLEncoder.encode(value, StandardCharsets.UTF_8);
|
||||
}
|
||||
matcher.appendReplacement(sb, Matcher.quoteReplacement(replacement));
|
||||
}
|
||||
matcher.appendTail(sb);
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,34 @@
|
||||
package codes.thischwa.cf;
|
||||
|
||||
import codes.thischwa.cf.model.ResponseResultInfo;
|
||||
import java.io.Serial;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Represents a custom exception for errors encountered while interacting with the Cloudflare API.
|
||||
*
|
||||
* <p>If the error was caused by an API response, {@link #getStatusCode()} returns the HTTP status
|
||||
* code and {@link #getErrors()} the errors reported by Cloudflare.
|
||||
*/
|
||||
public class CloudflareApiException extends Exception {
|
||||
|
||||
/**
|
||||
* Value of {@link #getStatusCode()} if the exception was not caused by an HTTP response.
|
||||
*/
|
||||
public static final int NO_STATUS_CODE = -1;
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
private static final long serialVersionUID = 2L;
|
||||
|
||||
/**
|
||||
* The HTTP status code of the response, or {@link #NO_STATUS_CODE}.
|
||||
*/
|
||||
private final int statusCode;
|
||||
|
||||
/**
|
||||
* The errors reported by Cloudflare. Transient, because the error class isn't serializable.
|
||||
*/
|
||||
private final transient List<ResponseResultInfo.Error> errors;
|
||||
|
||||
/**
|
||||
* Constructs a new CloudflareApiException with the specified detail message.
|
||||
@@ -16,7 +36,7 @@ public class CloudflareApiException extends Exception {
|
||||
* @param message the detail message, which provides more information about the exception.
|
||||
*/
|
||||
public CloudflareApiException(String message) {
|
||||
super(message);
|
||||
this(message, NO_STATUS_CODE, null);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -29,5 +49,40 @@ public class CloudflareApiException extends Exception {
|
||||
*/
|
||||
public CloudflareApiException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
this.statusCode = NO_STATUS_CODE;
|
||||
this.errors = List.of();
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a new CloudflareApiException caused by an API response.
|
||||
*
|
||||
* @param message the detail message
|
||||
* @param statusCode the HTTP status code of the response, or {@link #NO_STATUS_CODE}
|
||||
* @param errors the errors reported by Cloudflare, may be {@code null}
|
||||
*/
|
||||
public CloudflareApiException(String message, int statusCode,
|
||||
List<ResponseResultInfo.Error> errors) {
|
||||
super(message);
|
||||
this.statusCode = statusCode;
|
||||
this.errors = errors == null ? List.of() : List.copyOf(errors);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the HTTP status code of the response that caused this exception.
|
||||
*
|
||||
* @return the HTTP status code, or {@link #NO_STATUS_CODE} if the exception wasn't caused by an
|
||||
* HTTP response
|
||||
*/
|
||||
public int getStatusCode() {
|
||||
return statusCode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the errors reported by Cloudflare.
|
||||
*
|
||||
* @return an unmodifiable list of errors, never {@code null}
|
||||
*/
|
||||
public List<ResponseResultInfo.Error> getErrors() {
|
||||
return errors == null ? List.of() : errors;
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,21 @@
|
||||
package codes.thischwa.cf;
|
||||
|
||||
import codes.thischwa.cf.model.ResponseResultInfo;
|
||||
import java.io.Serial;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* This exception is thrown to indicate that a requested resource was not found during interaction
|
||||
* with the Cloudflare API.
|
||||
*
|
||||
* <p>It extends {@link CloudflareApiException} to provide specific errors related to situations
|
||||
* where Cloudflare responds with a "not found" operation.
|
||||
* <p>It is thrown if Cloudflare responds with HTTP status 404, or if a result is empty and
|
||||
* 'emptyResultThrowsException' is enabled.
|
||||
*/
|
||||
public class CloudflareNotFoundException extends CloudflareApiException {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* Constructs a new CloudflareNotFoundException with the specified detail message.
|
||||
*
|
||||
@@ -18,4 +25,16 @@ public class CloudflareNotFoundException extends CloudflareApiException {
|
||||
public CloudflareNotFoundException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a new CloudflareNotFoundException caused by an API response.
|
||||
*
|
||||
* @param message the detail message
|
||||
* @param statusCode the HTTP status code of the response
|
||||
* @param errors the errors reported by Cloudflare, may be {@code null}
|
||||
*/
|
||||
public CloudflareNotFoundException(String message, int statusCode,
|
||||
List<ResponseResultInfo.Error> errors) {
|
||||
super(message, statusCode, errors);
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
package codes.thischwa.cf;
|
||||
|
||||
import codes.thischwa.cf.model.AbstractMultipleResponse;
|
||||
import codes.thischwa.cf.model.AbstractResponse;
|
||||
import codes.thischwa.cf.model.AbstractSingleResponse;
|
||||
import codes.thischwa.cf.model.RecordMultipleResponse;
|
||||
import codes.thischwa.cf.model.ResponseResultInfo;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@@ -16,7 +16,7 @@ import java.util.stream.Collectors;
|
||||
* metadata. If the response indicates failure, an exception is thrown with descriptive error
|
||||
* messages.
|
||||
* <li>It validates the number of results in the API response payload to detect unexpected counts.
|
||||
* For {@link RecordMultipleResponse}, it checks if results are empty or if more than one result
|
||||
* For {@link AbstractMultipleResponse}, it checks if results are empty or if more than one result
|
||||
* was returned when a single result was expected. For {@link AbstractSingleResponse}, it checks
|
||||
* if the result is null. Depending on the parameter 'emptyResultThrowsException', an exception
|
||||
* will be triggered or an empty/null result will be returned.
|
||||
@@ -45,16 +45,16 @@ class ResponseValidator {
|
||||
|
||||
private void validateResultCount(AbstractResponse resp, boolean singleResultExpected)
|
||||
throws CloudflareApiException {
|
||||
if (resp instanceof RecordMultipleResponse respMulti) {
|
||||
if (resp instanceof AbstractMultipleResponse<?> respMulti) {
|
||||
validateMultipleResponse(respMulti, singleResultExpected);
|
||||
} else if (resp instanceof AbstractSingleResponse<?> respSingle) {
|
||||
validateSingleResponse(respSingle);
|
||||
}
|
||||
}
|
||||
|
||||
private void validateMultipleResponse(RecordMultipleResponse response, boolean singleResultExpected)
|
||||
private void validateMultipleResponse(AbstractMultipleResponse<?> response, boolean singleResultExpected)
|
||||
throws CloudflareApiException {
|
||||
int totalCount = response.getResultInfo().totalCount();
|
||||
int totalCount = getTotalCount(response);
|
||||
if (singleResultExpected && totalCount > 1) {
|
||||
throw new CloudflareApiException("Unexpected result count: " + totalCount);
|
||||
}
|
||||
@@ -63,6 +63,17 @@ class ResponseValidator {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines the total count of the results. Falls back to the size of the result list if the
|
||||
* response contains no result info.
|
||||
*/
|
||||
private static int getTotalCount(AbstractMultipleResponse<?> response) {
|
||||
if (response.getResultInfo() != null) {
|
||||
return response.getResultInfo().totalCount();
|
||||
}
|
||||
return response.getResult() == null ? 0 : response.getResult().size();
|
||||
}
|
||||
|
||||
private void validateSingleResponse(AbstractSingleResponse<?> response)
|
||||
throws CloudflareNotFoundException {
|
||||
if (emptyResultThrowsException && response.getResult() == null) {
|
||||
|
||||
@@ -6,7 +6,7 @@ import codes.thischwa.cf.model.RecordType;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Fluent interface for getRecord-level operations.
|
||||
* Fluent interface for record-level operations.
|
||||
* Provides a chainable API for CRUD operations on DNS records.
|
||||
*/
|
||||
public interface RecordOperations {
|
||||
@@ -20,30 +20,35 @@ public interface RecordOperations {
|
||||
List<RecordEntity> get() throws CloudflareApiException;
|
||||
|
||||
/**
|
||||
* Creates a new DNS getRecord with the specified parameters.
|
||||
* Creates a new DNS record with the specified parameters.
|
||||
*
|
||||
* @param type the DNS getRecord type (e.g., A, AAAA, CNAME)
|
||||
* @param content the content of the DNS getRecord (e.g., IP address)
|
||||
* @param type the DNS record type (e.g., A, AAAA, CNAME)
|
||||
* @param content the content of the DNS record (e.g., IP address)
|
||||
* @param ttl the time-to-live value in seconds
|
||||
* @return the created RecordEntity
|
||||
* @throws CloudflareApiException if an error occurs while creating the getRecord
|
||||
* @throws CloudflareApiException if an error occurs while creating the record
|
||||
*/
|
||||
RecordEntity create(RecordType type, String content, int ttl) throws CloudflareApiException;
|
||||
|
||||
/**
|
||||
* Updates an existing DNS getRecord with new content.
|
||||
* Updates an existing DNS record with new content.
|
||||
*
|
||||
* @param newContent the new content for the DNS getRecord
|
||||
* @param newContent the new content for the DNS record
|
||||
* @return the updated RecordEntity
|
||||
* @throws CloudflareApiException if an error occurs while updating the getRecord
|
||||
* @throws CloudflareApiException if an error occurs while updating the record
|
||||
*/
|
||||
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 getRecord types to delete
|
||||
* @throws CloudflareApiException if an error occurs while deleting records
|
||||
* @param types the DNS record types to delete
|
||||
* @throws CloudflareApiException if an error occurs while retrieving records to delete
|
||||
*/
|
||||
void delete(RecordType... types) throws CloudflareApiException;
|
||||
}
|
||||
@@ -9,56 +9,55 @@ import java.util.List;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* Implementation of RecordOperations for fluent API access to getRecord-level operations.
|
||||
* Implementation of RecordOperations for fluent API access to record-level operations.
|
||||
*/
|
||||
public class RecordOperationsImpl implements RecordOperations {
|
||||
|
||||
private final CfDnsClient client;
|
||||
private final ZoneEntity zone;
|
||||
private final String sld;
|
||||
private final String subdomain;
|
||||
private final RecordType[] types;
|
||||
|
||||
/**
|
||||
* Constructs a RecordOperationsImpl instance.
|
||||
*
|
||||
* @param client the CfDnsClient instance to use for operations
|
||||
* @param zone the ZoneEntity representing the DNS zone
|
||||
* @param sld the subdomain (second-level domain) name
|
||||
* @param types optional array of RecordType to filter by
|
||||
* @param client the CfDnsClient instance to use for operations
|
||||
* @param zone the ZoneEntity representing the DNS zone
|
||||
* @param subdomain the subdomain relative to the zone, or "@" for the zone apex
|
||||
* @param types optional array of RecordType to filter by
|
||||
*/
|
||||
public RecordOperationsImpl(CfDnsClient client, ZoneEntity zone, String sld, @Nullable RecordType[] types) {
|
||||
public RecordOperationsImpl(CfDnsClient client, ZoneEntity zone, String subdomain, @Nullable RecordType[] types) {
|
||||
this.client = client;
|
||||
this.zone = zone;
|
||||
this.sld = sld;
|
||||
this.subdomain = subdomain;
|
||||
this.types = types;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<RecordEntity> get() throws CloudflareApiException {
|
||||
return client.recordList(zone, sld, types);
|
||||
return client.recordListBySubdomain(zone, subdomain, types);
|
||||
}
|
||||
|
||||
@Override
|
||||
public RecordEntity create(RecordType type, String content, int ttl) throws CloudflareApiException {
|
||||
return client.recordCreateSld(zone, sld, ttl, type, content);
|
||||
return client.recordCreateSubdomain(zone, subdomain, ttl, type, content);
|
||||
}
|
||||
|
||||
@Override
|
||||
public RecordEntity update(String newContent) throws CloudflareApiException {
|
||||
List<RecordEntity> recs = get();
|
||||
if (recs.isEmpty()) {
|
||||
throw new CloudflareApiException("No recs found to update for subdomain: " + sld);
|
||||
throw new CloudflareApiException("No recs found to update for subdomain: " + subdomain);
|
||||
}
|
||||
if (recs.size() > 1) {
|
||||
throw new CloudflareApiException("Multiple recs found. Please use recordUpdate() directly for precise control.");
|
||||
}
|
||||
RecordEntity rec = recs.get(0);
|
||||
rec.setContent(newContent);
|
||||
return client.recordUpdate(zone, rec);
|
||||
// partial update: only the content is changed
|
||||
return client.recordUpdate(zone, RecordEntity.build(recs.get(0).getId(), newContent));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(RecordType... types) throws CloudflareApiException {
|
||||
client.recordDeleteTypeIfExists(zone, sld, types);
|
||||
client.recordDeleteTypeIfExists(zone, subdomain, types);
|
||||
}
|
||||
}
|
||||
@@ -13,21 +13,25 @@ public interface ZoneOperations {
|
||||
/**
|
||||
* Selects a record (subdomain) within the zone for further operations.
|
||||
*
|
||||
* @param sld the second-level domain (subdomain) name
|
||||
* @param subdomain the subdomain relative to the zone (e.g. "www"), or "@" for the zone apex
|
||||
* @return a RecordOperations instance for chaining record-specific operations
|
||||
* @throws CloudflareApiException if the zone cannot be found or accessed
|
||||
*/
|
||||
RecordOperations getRecord(String sld) throws CloudflareApiException;
|
||||
RecordOperations getRecord(String subdomain) throws CloudflareApiException;
|
||||
|
||||
/**
|
||||
* 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 sld the second-level domain (subdomain) name
|
||||
* @param types optional DNS record types to filter by
|
||||
* @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
|
||||
* @return a RecordOperations instance for chaining record-specific operations
|
||||
* @throws CloudflareApiException if the zone cannot be found or accessed
|
||||
*/
|
||||
RecordOperations getRecord(String sld, @Nullable RecordType... types) throws CloudflareApiException;
|
||||
RecordOperations getRecord(String subdomain, @Nullable RecordType... types) throws CloudflareApiException;
|
||||
|
||||
/**
|
||||
* Lists all DNS records within the zone, optionally filtered by types.
|
||||
|
||||
@@ -28,17 +28,17 @@ public class ZoneOperationsImpl implements ZoneOperations {
|
||||
}
|
||||
|
||||
@Override
|
||||
public RecordOperations getRecord(String sld) throws CloudflareApiException {
|
||||
return new RecordOperationsImpl(client, zone, sld, null);
|
||||
public RecordOperations getRecord(String subdomain) throws CloudflareApiException {
|
||||
return new RecordOperationsImpl(client, zone, subdomain, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public RecordOperations getRecord(String sld, @Nullable RecordType... types) throws CloudflareApiException {
|
||||
return new RecordOperationsImpl(client, zone, sld, types);
|
||||
public RecordOperations getRecord(String subdomain, @Nullable RecordType... types) throws CloudflareApiException {
|
||||
return new RecordOperationsImpl(client, zone, subdomain, types);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<RecordEntity> list(@Nullable RecordType... types) throws CloudflareApiException {
|
||||
return client.recordList(zone, types);
|
||||
return client.recordListByType(zone, types);
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@
|
||||
*
|
||||
* <p>Example usage:
|
||||
* <pre><code>
|
||||
* // Create a DNS getRecord
|
||||
* // Create a DNS record
|
||||
* client.zone("example.com")
|
||||
* .getRecord("api")
|
||||
* .create(RecordType.A, "192.168.1.1", 60);
|
||||
@@ -16,7 +16,7 @@
|
||||
* .getRecord("www", RecordType.A)
|
||||
* .get();
|
||||
*
|
||||
* // Update a DNS getRecord
|
||||
* // Update a DNS record
|
||||
* client.zone("example.com")
|
||||
* .getRecord("api", RecordType.A)
|
||||
* .update("192.168.1.2");
|
||||
|
||||
@@ -5,11 +5,11 @@ import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
/**
|
||||
* Represents a batch entry containing different types of operations on getRecord entities.
|
||||
* Represents a batch entry containing different types of operations on record entities.
|
||||
*
|
||||
* <p>A BatchEntry groups together collections of operations (patches, posts, puts, and deletes)
|
||||
* intended to be performed as part of a single batch process. Each operation corresponds to a specific
|
||||
* type of action on DNS getRecord entities.
|
||||
* type of action on DNS record entities.
|
||||
*
|
||||
* <ul>
|
||||
* <li><b>patches</b>: A list of {@link RecordEntity} objects representing partial updates to existing records.
|
||||
|
||||
@@ -5,7 +5,7 @@ package codes.thischwa.cf.model;
|
||||
*
|
||||
* <p>This class is used for API responses where the primary result is a batch entry,
|
||||
* which includes collections of operations such as patches, posts, puts, and deletes
|
||||
* performed on DNS getRecord entities.
|
||||
* performed on DNS record entities.
|
||||
*
|
||||
* <p>Extends {@code AbstractSingleResponse} with {@code BatchEntry} as the generic type,
|
||||
* ensuring that the response result is a batch of operations.
|
||||
|
||||
@@ -1,83 +1,118 @@
|
||||
package codes.thischwa.cf.model;
|
||||
|
||||
import java.util.Map;
|
||||
import lombok.Data;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* 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
|
||||
* request, along with utility methods for constructing and retrieving pagination parameters.
|
||||
* <p>Use {@link #forZones(int, int)} for zone requests and {@link #forRecords(int, int)} for DNS
|
||||
* record requests. For example:
|
||||
*
|
||||
* <p>Key functionalities:
|
||||
*
|
||||
* <ul>
|
||||
* <li>Creating a {@code PagingRequest} instance with specific pagination values using the {@code
|
||||
* 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>
|
||||
* <pre>{@code
|
||||
* List<RecordEntity> records = client.recordList(zone, PagingRequest.forRecords(1, 100));
|
||||
* List<ZoneEntity> zones = client.zoneList(PagingRequest.forZones(1, 50));
|
||||
* }</pre>
|
||||
*/
|
||||
@Data
|
||||
public class PagingRequest {
|
||||
public record PagingRequest(int page, int perPage) {
|
||||
|
||||
/** Default page size, valid for zones and DNS records. */
|
||||
public static final int DEFAULT_PAGE_SIZE = 50;
|
||||
|
||||
/** Maximum number of DNS records allowed per page by Cloudflare. */
|
||||
public static final int MAX_RECORDS_PER_PAGE = 5_000_000;
|
||||
|
||||
/** 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;
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* Validates the page number and page size.
|
||||
*
|
||||
* @param page the 1-based page number
|
||||
* @param perPage the number of items per page, from 1 to {@value #MAX_RECORDS_PER_PAGE}
|
||||
* @throws IllegalArgumentException if either value is outside its allowed range
|
||||
*/
|
||||
private static final int DEFAULT_ALL_RECORDS_PAGE_SIZE = 1000;
|
||||
|
||||
private int page;
|
||||
private int perPage;
|
||||
|
||||
PagingRequest(int page, int perPage) {
|
||||
this.page = page;
|
||||
this.perPage = perPage;
|
||||
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 perPage the number of items to be included per page
|
||||
* @return a new {@code PagingRequest} instance with the provided parameters
|
||||
* @param page the 1-based page number
|
||||
* @param perPage the number of records per page, from 1 to {@value #MAX_RECORDS_PER_PAGE}
|
||||
* @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);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a default {@code PagingRequest} instance with a page number set to 1 and a high number
|
||||
* of items per page to accommodate large dataset requests and effectively retrieve all records.
|
||||
* Creates pagination parameters for a zone request.
|
||||
*
|
||||
* @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() {
|
||||
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
|
||||
* page number and the key "perPage" indicates the number of items per page.
|
||||
* @return the next page request
|
||||
*/
|
||||
public Map<String, String> getPagingParams() {
|
||||
return Map.of("page", String.valueOf(page), "perPage", String.valueOf(perPage));
|
||||
public PagingRequest next() {
|
||||
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
|
||||
* @return the complete URL with the appended query string for pagination
|
||||
* @param page the 1-based page number
|
||||
* @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) {
|
||||
return endpoint + queryString(endpoint.contains("?"));
|
||||
}
|
||||
|
||||
private String queryString(boolean add) {
|
||||
String qs = "page=" + page + "&per_page=" + perPage;
|
||||
return add ? "&" + qs : "?" + qs;
|
||||
Objects.requireNonNull(endpoint, "endpoint must not be null");
|
||||
return endpoint + (endpoint.contains("?") ? "&" : "?")
|
||||
+ "page=" + page + "&per_page=" + perPage;
|
||||
}
|
||||
}
|
||||
@@ -1,51 +1,83 @@
|
||||
package codes.thischwa.cf.model;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* Represents a DNS getRecord entity within a specific zone.
|
||||
* Represents a DNS record entity within a specific zone.
|
||||
*
|
||||
* <p>Attributes defined in this class include:
|
||||
*
|
||||
* <ul>
|
||||
* <li>DNS getRecord type such as "A" or "CNAME".
|
||||
* <li>Name of the DNS getRecord.
|
||||
* <li>Content of the DNS getRecord, such as an IP address.
|
||||
* <li>Flags indicating whether the getRecord is proxiable or proxied.
|
||||
* <li>TTL (Time-To-Live) for the DNS getRecord.
|
||||
* <li>A locked status to indicate the immutability of the getRecord.
|
||||
* <li>DNS record type such as "A" or "CNAME".
|
||||
* <li>Name of the DNS record.
|
||||
* <li>Content of the DNS record, such as an IP address.
|
||||
* <li>Flags indicating whether the record is proxiable or proxied.
|
||||
* <li>TTL (Time-To-Live) for the DNS record.
|
||||
* <li>Priority, required for MX and URI records (for SRV records it's part of the data).
|
||||
* <li>Structured data, required for e.g. SRV, CAA, LOC or TLSA records instead of content.
|
||||
* <li>An optional comment and tags.
|
||||
* <li>A locked status to indicate the immutability of the record.
|
||||
* <li>Zone-specific metadata including zone ID and name.
|
||||
* <li>Timestamps for creation and modification.
|
||||
* <li>Timestamps for creation and modification (UTC).
|
||||
* </ul>
|
||||
*
|
||||
* <p>Provides a static factory method {@code build} for creating a DNS getRecord with specific
|
||||
* <p>Provides a static factory method {@code build} for creating a DNS record with specific
|
||||
* attributes.
|
||||
*/
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@Data
|
||||
public class RecordEntity extends AbstractEntity {
|
||||
private static final String APEX = "@";
|
||||
|
||||
private String type;
|
||||
private String name;
|
||||
private String content;
|
||||
private Boolean proxiable;
|
||||
private Boolean proxied;
|
||||
private Integer ttl;
|
||||
/**
|
||||
* Priority of the record, required for MX and URI records. For SRV records the priority is
|
||||
* part of {@link #data}.
|
||||
*/
|
||||
@Nullable
|
||||
private Integer priority;
|
||||
/**
|
||||
* Comment of the record, only used by Cloudflare.
|
||||
*/
|
||||
@Nullable
|
||||
private String comment;
|
||||
/**
|
||||
* Custom tags of the record in the form "name:value", only used by Cloudflare.
|
||||
*/
|
||||
@Nullable
|
||||
private List<String> tags;
|
||||
/**
|
||||
* Structured content of the record, e.g. for SRV records the keys "priority", "weight", "port"
|
||||
* and "target".
|
||||
* The keys are the same as in the Cloudflare API.
|
||||
*/
|
||||
@Nullable
|
||||
private Map<String, Object> data;
|
||||
private Boolean locked;
|
||||
@Nullable
|
||||
private String zoneId;
|
||||
@Nullable
|
||||
private String zoneName;
|
||||
@Nullable
|
||||
private LocalDateTime modifiedOn;
|
||||
private Instant modifiedOn;
|
||||
@Nullable
|
||||
private LocalDateTime createdOn;
|
||||
private Instant createdOn;
|
||||
|
||||
/**
|
||||
* Initializes a new instance of the RecordEntity class and invokes the parent constructor from
|
||||
* the AbstractEntity class. The RecordEntity class represents a DNS getRecord entity within a
|
||||
* the AbstractEntity class. The RecordEntity class represents a DNS record entity within a
|
||||
* specific zone, encapsulating attributes such as type, name, content, TTL, and other related
|
||||
* metadata.
|
||||
*/
|
||||
@@ -56,10 +88,10 @@ public class RecordEntity extends AbstractEntity {
|
||||
/**
|
||||
* Builds and returns a {@link RecordEntity} instance with the specified attributes.
|
||||
*
|
||||
* @param name the name of the DNS getRecord
|
||||
* @param type the {@link RecordType} of the DNS getRecord
|
||||
* @param ttl the time-to-live (TTL) value for the DNS getRecord
|
||||
* @param content the content of the DNS getRecord, typically an IP address
|
||||
* @param name the name of the DNS record
|
||||
* @param type the {@link RecordType} of the DNS record
|
||||
* @param ttl the time-to-live (TTL) value for the DNS record
|
||||
* @param content the content of the DNS record, typically an IP address
|
||||
* @return a {@link RecordEntity} populated with the provided attributes
|
||||
*/
|
||||
public static RecordEntity build(String name, RecordType type, Integer ttl, String content) {
|
||||
@@ -74,8 +106,8 @@ public class RecordEntity extends AbstractEntity {
|
||||
/**
|
||||
* Builds and returns a {@link RecordEntity} instance with the specified ID and content.
|
||||
*
|
||||
* @param id the unique identifier for the DNS getRecord
|
||||
* @param content the content of the DNS getRecord, typically an IP address or other getRecord data
|
||||
* @param id the unique identifier for the DNS record
|
||||
* @param content the content of the DNS record, typically an IP address or other record data
|
||||
* @return a {@link RecordEntity} populated with the provided ID and content
|
||||
*/
|
||||
public static RecordEntity build(String id, String content) {
|
||||
@@ -88,11 +120,11 @@ public class RecordEntity extends AbstractEntity {
|
||||
/**
|
||||
* Builds and returns a {@link RecordEntity} instance with the specified attributes.
|
||||
*
|
||||
* @param id the unique identifier for the DNS getRecord
|
||||
* @param name the name of the DNS getRecord
|
||||
* @param type the type of the DNS getRecord, represented as a string (e.g., "A", "CNAME")
|
||||
* @param ttl the time-to-live (TTL) value for the DNS getRecord
|
||||
* @param content the content of the DNS getRecord, typically an IP address or other getRecord data
|
||||
* @param id the unique identifier for the DNS record
|
||||
* @param name the name of the DNS record
|
||||
* @param type the type of the DNS record, represented as a string (e.g., "A", "CNAME")
|
||||
* @param ttl the time-to-live (TTL) value for the DNS record
|
||||
* @param content the content of the DNS record, typically an IP address or other record data
|
||||
* @return a {@link RecordEntity} populated with the provided attributes
|
||||
* @throws IllegalArgumentException if the type string is not a valid RecordType
|
||||
*/
|
||||
@@ -101,7 +133,7 @@ public class RecordEntity extends AbstractEntity {
|
||||
try {
|
||||
recordType = RecordType.valueOf(type);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new IllegalArgumentException("Invalid getRecord type: " + type + ". Must be one of: "
|
||||
throw new IllegalArgumentException("Invalid record type: " + type + ". Must be one of: "
|
||||
+ java.util.Arrays.toString(RecordType.values()), e);
|
||||
}
|
||||
RecordEntity rec = new RecordEntity();
|
||||
@@ -114,22 +146,31 @@ public class RecordEntity extends AbstractEntity {
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the short name (subdomain) of the DNS getRecord.
|
||||
* If the name contains a dot ('.'), only the substring before the first dot is returned.
|
||||
* This is useful for getting the subdomain part of a fully qualified domain name.
|
||||
* Retrieves the subdomain of the DNS record, i.e. the record name relative to its zone.
|
||||
*
|
||||
* @return the short name of the DNS getRecord (substring before the first dot),
|
||||
* or the full name if no dot is present
|
||||
* <p>If the zone name is known, the zone name is stripped from the record name, e.g.
|
||||
* {@code my.sub.example.com} results in {@code my.sub}. A record at the zone apex results in
|
||||
* {@code "@"}. If the zone name is unknown, only the substring before the first dot is returned.
|
||||
*
|
||||
* @return the short name of the DNS record, {@code "@"} for the zone apex, or the full name if
|
||||
* no dot is present
|
||||
*/
|
||||
public String getSld() {
|
||||
@JsonIgnore
|
||||
@Nullable
|
||||
public String getSubdomain() {
|
||||
if (name == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (zoneName != null && name.endsWith(zoneName)) {
|
||||
int zoneNameLength = zoneName.length();
|
||||
int dotSeparatorLength = 1;
|
||||
return name.substring(0, name.length() - zoneNameLength - dotSeparatorLength);
|
||||
if (zoneName != null && !zoneName.isEmpty()) {
|
||||
String lowerName = name.toLowerCase(Locale.ROOT);
|
||||
String lowerZone = zoneName.toLowerCase(Locale.ROOT);
|
||||
if (lowerName.equals(lowerZone)) {
|
||||
return APEX;
|
||||
}
|
||||
if (lowerName.endsWith("." + lowerZone)) {
|
||||
return name.substring(0, name.length() - zoneName.length() - 1);
|
||||
}
|
||||
}
|
||||
|
||||
int firstDotPosition = name.indexOf('.');
|
||||
@@ -139,4 +180,17 @@ public class RecordEntity extends AbstractEntity {
|
||||
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the subdomain of the DNS record.
|
||||
*
|
||||
* @return the subdomain of the DNS record
|
||||
* @deprecated The name was misleading, use {@link #getSubdomain()} instead.
|
||||
*/
|
||||
@Deprecated(since = "0.6.0", forRemoval = true)
|
||||
@JsonIgnore
|
||||
@Nullable
|
||||
public String getSld() {
|
||||
return getSubdomain();
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@ public class RecordMultipleResponse extends AbstractMultipleResponse<RecordEntit
|
||||
/**
|
||||
* Constructs an instance of RecordMultipleResponse.
|
||||
*
|
||||
* <p>This class represents a response containing multiple DNS getRecord entities from the
|
||||
* <p>This class represents a response containing multiple DNS record entities from the
|
||||
* Cloudflare API. It inherits functionality from AbstractMultipleResponse to handle multiple
|
||||
* records of type RecordEntity.
|
||||
*/
|
||||
|
||||
@@ -11,7 +11,7 @@ public class RecordSingleResponse extends AbstractSingleResponse<RecordEntity> {
|
||||
*
|
||||
* <p>This constructor initializes the RecordSingleResponse object by invoking the superclass
|
||||
* constructor. The RecordSingleResponse represents a specific API response structure that
|
||||
* encapsulates a single DNS getRecord entity, providing mechanisms to interact with such data in the
|
||||
* encapsulates a single DNS record entity, providing mechanisms to interact with such data in the
|
||||
* context of the Cloudflare API.
|
||||
*/
|
||||
public RecordSingleResponse() {
|
||||
|
||||
@@ -3,86 +3,86 @@ package codes.thischwa.cf.model;
|
||||
import lombok.Getter;
|
||||
|
||||
/**
|
||||
* Enum representing various DNS getRecord types.
|
||||
* Enum representing various DNS record types.
|
||||
*
|
||||
* <p>Each constant in this enum corresponds to a specific DNS getRecord type, such as "A", "AAAA",
|
||||
* "CNAME", or "TXT". This enum provides a means to standardize the representation of these getRecord
|
||||
* <p>Each constant in this enum corresponds to a specific DNS record type, such as "A", "AAAA",
|
||||
* "CNAME", or "TXT". This enum provides a means to standardize the representation of these record
|
||||
* types throughout the application while allowing easy retrieval of their string representation.
|
||||
*/
|
||||
@Getter
|
||||
public enum RecordType {
|
||||
/**
|
||||
* Represents the DNS A getRecord type.
|
||||
* Represents the DNS A record type.
|
||||
*
|
||||
* <p>The "A" getRecord type is used to map a domain name to an IPv4 address.
|
||||
* <p>The "A" record type is used to map a domain name to an IPv4 address.
|
||||
*/
|
||||
A("A"),
|
||||
/**
|
||||
* Represents the DNS AAAA getRecord type.
|
||||
* Represents the DNS AAAA record type.
|
||||
*
|
||||
* <p>The "AAAA" getRecord type maps a domain name to an IPv6 address.
|
||||
* <p>The "AAAA" record type maps a domain name to an IPv6 address.
|
||||
*/
|
||||
AAAA("AAAA"),
|
||||
/**
|
||||
* Represents the DNS CAA (Certificate Authority Authorization) getRecord type.
|
||||
* Represents the DNS CAA (Certificate Authority Authorization) record type.
|
||||
*
|
||||
* <p>The "CAA" getRecord type is used to specify which certificate authorities (CAs) are allowed to
|
||||
* <p>The "CAA" record type is used to specify which certificate authorities (CAs) are allowed to
|
||||
* issue SSL/TLS certificates for a domain.
|
||||
*/
|
||||
CAA("CAA"),
|
||||
/**
|
||||
* Represents the DNS CERT getRecord type.
|
||||
* Represents the DNS CERT record type.
|
||||
*
|
||||
* <p>The "CERT" getRecord type is used to store certificates and related certificate revocation
|
||||
* <p>The "CERT" record type is used to store certificates and related certificate revocation
|
||||
* lists or certificate authority data in DNS zones.
|
||||
*/
|
||||
CERT("CERT"),
|
||||
/**
|
||||
* Represents the DNS CNAME (Canonical Name) getRecord type.
|
||||
* Represents the DNS CNAME (Canonical Name) record type.
|
||||
*
|
||||
* <p>The "CNAME" getRecord type is used to alias one domain name to another.
|
||||
* <p>The "CNAME" record type is used to alias one domain name to another.
|
||||
*/
|
||||
CNAME("CNAME"),
|
||||
/**
|
||||
* Represents the DNSKEY getRecord type.
|
||||
* Represents the DNSKEY record type.
|
||||
*
|
||||
* <p>The "DNSKEY" getRecord type is used for storing public keys in DNS, as part of the DNS Security
|
||||
* <p>The "DNSKEY" record type is used for storing public keys in DNS, as part of the DNS Security
|
||||
* Extensions (DNSSEC). It helps in verifying the authenticity of DNS responses through digital
|
||||
* signatures.
|
||||
*/
|
||||
DNSKEY("DNSKEY"),
|
||||
/**
|
||||
* Represents the DNS DS (Delegation Signer) getRecord type.
|
||||
* Represents the DNS DS (Delegation Signer) record type.
|
||||
*
|
||||
* <p>The "DS" getRecord type is used in the DNSSEC (Domain Name System Security Extensions)
|
||||
* protocol. It contains a hash of a DNSKEY getRecord which is utilized in establishing a chain of
|
||||
* <p>The "DS" record type is used in the DNSSEC (Domain Name System Security Extensions)
|
||||
* protocol. It contains a hash of a DNSKEY record which is utilized in establishing a chain of
|
||||
* trust from a parent zone to a child zone.
|
||||
*/
|
||||
DS("DS"),
|
||||
/**
|
||||
* Represents the DNS HTTPS (HTTP Service) getRecord type.
|
||||
* Represents the DNS HTTPS (HTTP Service) record type.
|
||||
*
|
||||
* <p>The "HTTPS" getRecord type is used to specify information about the HTTP/3 and related services
|
||||
* <p>The "HTTPS" record type is used to specify information about the HTTP/3 and related services
|
||||
* offered by a domain.
|
||||
*/
|
||||
HTTPS("HTTPS"),
|
||||
/**
|
||||
* Represents the DNS LOC (Location) getRecord type.
|
||||
* Represents the DNS LOC (Location) record type.
|
||||
*
|
||||
* <p>The "LOC" getRecord type is used to store geographical location information for a domain,
|
||||
* <p>The "LOC" record type is used to store geographical location information for a domain,
|
||||
* including latitude, longitude, altitude, and other details. It enables associating domains with
|
||||
* physical locations.
|
||||
*/
|
||||
LOC("LOC"),
|
||||
/**
|
||||
* Represents the DNS MX (Mail Exchange) getRecord type.
|
||||
* Represents the DNS MX (Mail Exchange) record type.
|
||||
*
|
||||
* <p>The "MX" getRecord type is used to specify the mail servers responsible for receiving email
|
||||
* <p>The "MX" record type is used to specify the mail servers responsible for receiving email
|
||||
* messages on behalf of a domain.
|
||||
*/
|
||||
MX("MX"),
|
||||
/**
|
||||
* Represents the NAPTR getRecord type for DNS configurations.
|
||||
* Represents the NAPTR record type for DNS configurations.
|
||||
*
|
||||
* <p>This constant is used to specify NAPTR (Naming Authority Pointer) DNS records, which allow
|
||||
* for service discovery through flexible DNS-based mechanisms. NAPTR records are commonly used in
|
||||
@@ -99,7 +99,7 @@ public enum RecordType {
|
||||
*/
|
||||
NS("NS"),
|
||||
/**
|
||||
* Represents the "OPENPGPKEY" DNS getRecord type.
|
||||
* Represents the "OPENPGPKEY" DNS record type.
|
||||
*
|
||||
* <p>This constant is primarily used to identify DNS records of the type "OPENPGPKEY". It may be
|
||||
* utilized within the system for operations such as creating, retrieving, updating, or managing
|
||||
@@ -107,17 +107,17 @@ public enum RecordType {
|
||||
*/
|
||||
OPENPGPKEY("OPENPGPKEY"),
|
||||
/**
|
||||
* Represents a DNS getRecord type.
|
||||
* Represents a DNS record type.
|
||||
*
|
||||
* <p>The `PTR` value specifically refers to a "pointer getRecord" in the DNS system, which is
|
||||
* <p>The `PTR` value specifically refers to a "pointer record" in the DNS system, which is
|
||||
* typically used for reverse DNS lookups.
|
||||
*/
|
||||
PTR("PTR"),
|
||||
/**
|
||||
* Represents the SMIMEA DNS getRecord type.
|
||||
* Represents the SMIMEA DNS record type.
|
||||
*
|
||||
* <p>The SMIMEA resource getRecord is used to associate a user's certificate information for email
|
||||
* message signing or encryption. This type of DNS getRecord is part of the DNS-based Authentication
|
||||
* <p>The SMIMEA resource record is used to associate a user's certificate information for email
|
||||
* message signing or encryption. This type of DNS record is part of the DNS-based Authentication
|
||||
* of Named Entities (DANE) protocol.
|
||||
*
|
||||
* <p>SMIMEA records provide a mechanism for utilizing certificates in email communication
|
||||
@@ -134,41 +134,41 @@ public enum RecordType {
|
||||
*/
|
||||
SMIMEA("SMIMEA"),
|
||||
/**
|
||||
* Represents a service getRecord (SRV) type in the DNS configuration model.
|
||||
* Represents a service record (SRV) type in the DNS configuration model.
|
||||
*
|
||||
* <p>This constant may be used to identify and work with SRV getRecord types in various DNS-related
|
||||
* <p>This constant may be used to identify and work with SRV record types in various DNS-related
|
||||
* operations or integrations.
|
||||
*/
|
||||
SRV("SRV"),
|
||||
/**
|
||||
* Represents the DNS getRecord type "SSHFP" (SSH Fingerprint), used in DNS to store cryptographic
|
||||
* Represents the DNS record type "SSHFP" (SSH Fingerprint), used in DNS to store cryptographic
|
||||
* fingerprints associated with SSH host keys.
|
||||
*
|
||||
* <p>This DNS getRecord type provides a mechanism for verifying the authenticity of an SSH server
|
||||
* <p>This DNS record type provides a mechanism for verifying the authenticity of an SSH server
|
||||
* before initiating a connection, enhancing the security of SSH communications.
|
||||
*/
|
||||
SSHFP("SSHFP"),
|
||||
/**
|
||||
* Represents the Service Binding (SVCB) DNS getRecord type.
|
||||
* Represents the Service Binding (SVCB) DNS record type.
|
||||
*
|
||||
* <p>The SVCB getRecord is a DNS resource getRecord used to indicate alternative endpoints or specific
|
||||
* <p>The SVCB record is a DNS resource record used to indicate alternative endpoints or specific
|
||||
* configuration details for services. It is commonly applied in service discovery and
|
||||
* protocol-specific configurations.
|
||||
*/
|
||||
SVCB("SVCB"),
|
||||
/**
|
||||
* Represents a constant for the DNS-based Authentication of Named Entities (DANE) TLSA getRecord
|
||||
* Represents a constant for the DNS-based Authentication of Named Entities (DANE) TLSA record
|
||||
* type.
|
||||
*
|
||||
* <p>The TLSA getRecord is used to associate a TLS server certificate or public key with the domain
|
||||
* <p>The TLSA record is used to associate a TLS server certificate or public key with the domain
|
||||
* name (e.g., via DNSSEC). It enables cryptographically secured connections by attaching
|
||||
* certificate and key constraints to the specific domain.
|
||||
*/
|
||||
TLSA("TLSA"),
|
||||
/**
|
||||
* Represents the TXT DNS getRecord type.
|
||||
* Represents the TXT DNS record type.
|
||||
*
|
||||
* <p>The TXT DNS getRecord type is commonly used to store text-based information for various
|
||||
* <p>The TXT DNS record type is commonly used to store text-based information for various
|
||||
* verification and configuration purposes, such as domain ownership verification or email
|
||||
* authentication protocols (e.g., SPF, DKIM).
|
||||
*/
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
package codes.thischwa.cf.model;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.Instant;
|
||||
import java.util.Set;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
@@ -15,7 +15,7 @@ import lombok.EqualsAndHashCode;
|
||||
* <li>Zone name.
|
||||
* <li>Development mode status.
|
||||
* <li>Active and original name servers linked to the zone.
|
||||
* <li>Timestamps indicating when the zone was created, modified, or activated.
|
||||
* <li>Timestamps (UTC) indicating when the zone was created, modified, or activated.
|
||||
* <li>Current operational status of the zone (e.g., active, inactive).
|
||||
* <li>Boolean flag indicating whether the zone is paused.
|
||||
* <li>Zone type, representing the nature of the DNS zone (e.g., full, partial).
|
||||
@@ -31,9 +31,9 @@ public class ZoneEntity extends AbstractEntity {
|
||||
private Integer developmentMode;
|
||||
private Set<String> nameServers;
|
||||
private Set<String> originalNameServers;
|
||||
private LocalDateTime createdOn;
|
||||
private LocalDateTime modifiedOn;
|
||||
private LocalDateTime activatedOn;
|
||||
private Instant createdOn;
|
||||
private Instant modifiedOn;
|
||||
private Instant activatedOn;
|
||||
private String status;
|
||||
private Boolean paused;
|
||||
private String type;
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
package codes.thischwa.cf;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import codes.thischwa.cf.model.ZoneEntity;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Tests the error handling of {@link CfBasicHttpClient} against a local HTTP server.
|
||||
*/
|
||||
class CfBasicHttpClientErrorTest {
|
||||
|
||||
private static final String ZONE_JSON = """
|
||||
{"success":true,"errors":[],"messages":[],
|
||||
"result_info":{"page":1,"per_page":50,"total_pages":1,"count":1,"total_count":1},
|
||||
"result":[{"id":"zone1","name":"example.com","created_on":"2025-01-20T08:56:34.736214Z"}]}
|
||||
""";
|
||||
|
||||
private HttpServer server;
|
||||
private CfDnsClient client;
|
||||
private final AtomicInteger requestCount = new AtomicInteger();
|
||||
private volatile int status;
|
||||
private volatile String body;
|
||||
private volatile long delayMillis;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws IOException {
|
||||
server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
|
||||
server.createContext("/", exchange -> {
|
||||
requestCount.incrementAndGet();
|
||||
if (delayMillis > 0) {
|
||||
try {
|
||||
Thread.sleep(delayMillis);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
|
||||
exchange.sendResponseHeaders(status, bytes.length);
|
||||
try (OutputStream out = exchange.getResponseBody()) {
|
||||
out.write(bytes);
|
||||
}
|
||||
});
|
||||
server.start();
|
||||
client = new CfDnsClient(false, "http://localhost:" + server.getAddress().getPort(),
|
||||
new CfDnsClientBuilder.ApiTokenAuth("test-token"));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() throws IOException {
|
||||
client.close();
|
||||
server.stop(0);
|
||||
}
|
||||
|
||||
private void respond(int status, String body) {
|
||||
this.status = status;
|
||||
this.body = body;
|
||||
}
|
||||
|
||||
@Test
|
||||
void apiErrorContainsStatusCodeAndErrors() {
|
||||
respond(400, """
|
||||
{"success":false,"errors":[{"code":1004,"message":"DNS Validation Error"}],"messages":[],"result":null}
|
||||
""");
|
||||
|
||||
CloudflareApiException e = assertThrows(CloudflareApiException.class, () -> client.zoneList());
|
||||
|
||||
assertEquals(CloudflareApiException.class, e.getClass());
|
||||
assertEquals(400, e.getStatusCode());
|
||||
assertEquals(1, e.getErrors().size());
|
||||
assertEquals(1004, e.getErrors().get(0).getCode());
|
||||
assertTrue(e.getMessage().contains("DNS Validation Error"), e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void status404ThrowsNotFound() {
|
||||
respond(404, """
|
||||
{"success":false,"errors":[{"code":81044,"message":"Record does not exist."}],"messages":[],"result":null}
|
||||
""");
|
||||
ZoneEntity zone = new ZoneEntity();
|
||||
zone.setId("zone1");
|
||||
zone.setName("example.com");
|
||||
|
||||
CloudflareApiException e = assertThrows(CloudflareApiException.class,
|
||||
() -> client.recordDelete(zone, "0123456789abcdef0123456789abcdef"));
|
||||
|
||||
assertInstanceOf(CloudflareNotFoundException.class, e);
|
||||
assertEquals(404, e.getStatusCode());
|
||||
assertEquals(81044, e.getErrors().get(0).getCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void nonJsonErrorResponseKeepsStatusCode() {
|
||||
respond(502, "<html><body>Bad Gateway</body></html>");
|
||||
|
||||
CloudflareApiException e = assertThrows(CloudflareApiException.class, () -> client.zoneList());
|
||||
|
||||
assertEquals(502, e.getStatusCode());
|
||||
assertTrue(e.getErrors().isEmpty());
|
||||
assertTrue(e.getMessage().contains("502"), e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void successWithTimestampsAndReusedClient() throws CloudflareApiException {
|
||||
respond(200, ZONE_JSON);
|
||||
|
||||
ZoneEntity zone = client.zoneGet("example.com");
|
||||
assertNotNull(zone);
|
||||
assertEquals("2025-01-20T08:56:34.736214Z", zone.getCreatedOn().toString());
|
||||
|
||||
// the same client instance can be used for multiple requests
|
||||
assertEquals(1, client.zoneList().size());
|
||||
assertEquals(2, requestCount.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void exceptionWithoutResponseHasNoStatusCode() {
|
||||
CloudflareApiException e = new CloudflareApiException("test");
|
||||
assertEquals(CloudflareApiException.NO_STATUS_CODE, e.getStatusCode());
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
package codes.thischwa.cf;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
@@ -79,10 +79,10 @@ class CfBasicHttpClientTest {
|
||||
});
|
||||
|
||||
assertNotNull(exception);
|
||||
assertTrue(exception.getMessage().contains("Unexpected error"));
|
||||
Throwable cause = exception.getCause();
|
||||
assertInstanceOf(CloudflareApiException.class, cause);
|
||||
assertTrue(cause.getMessage().contains("No route for that URI"), "Expected error message: No route for that URI, but it was: " + cause.getMessage());
|
||||
// the API error must not be wrapped into a generic "Unexpected error"
|
||||
assertTrue(exception.getMessage().contains("No route for that URI"),
|
||||
"Expected error message: No route for that URI, but it was: " + exception.getMessage());
|
||||
assertNull(exception.getCause());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -0,0 +1,838 @@
|
||||
package codes.thischwa.cf;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
import static org.junit.jupiter.api.Assumptions.assumeTrue;
|
||||
|
||||
import codes.thischwa.cf.model.BatchEntry;
|
||||
import codes.thischwa.cf.model.PagingRequest;
|
||||
import codes.thischwa.cf.model.RecordEntity;
|
||||
import codes.thischwa.cf.model.RecordType;
|
||||
import codes.thischwa.cf.model.ZoneEntity;
|
||||
import java.net.IDN;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
@Slf4j
|
||||
public class CfClientIntegrationTest {
|
||||
|
||||
private static final String ZONE_STR = "mein-d-ns.de";
|
||||
private static final String SLD_STR = "devsld";
|
||||
private static final int TTL = 60;
|
||||
|
||||
private static final String API_TOKEN = System.getenv("API_TOKEN");
|
||||
|
||||
private final CfDnsClient client = new CfDnsClientBuilder().withEmptyResultThrowsException(true).withApiTokenAuth(API_TOKEN).build();
|
||||
|
||||
private static final String IP_PREFIX = "130.0.0.";
|
||||
private static final String UPDATED_IP_PREFIX = "130.1.0.";
|
||||
|
||||
private record PagedResult(int total, Set<String> allIds, List<List<RecordEntity>> pages) {
|
||||
}
|
||||
|
||||
@BeforeAll
|
||||
static void checkEnv() {
|
||||
assumeTrue(API_TOKEN != null && !API_TOKEN.isBlank(), "API_TOKEN not set; skipping client tests");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUnknownSld() throws Exception {
|
||||
ZoneEntity zone = client.zoneGet(ZONE_STR);
|
||||
assertThrows(CloudflareNotFoundException.class, () -> client.recordListBySubdomain(zone, "unknown", RecordType.A));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAddHost() throws Exception {
|
||||
ZoneEntity zone = client.zoneGet(ZONE_STR);
|
||||
|
||||
try {
|
||||
// clean-up
|
||||
client.recordDeleteTypeIfExists(zone, SLD_STR, RecordType.A, RecordType.AAAA);
|
||||
|
||||
RecordEntity record = RecordEntity.build(SLD_STR, RecordType.A, TTL, "127.0.0.1");
|
||||
RecordEntity createdRecord = client.recordCreate(zone, record);
|
||||
assertNotNull(createdRecord.getId());
|
||||
assertEquals(SLD_STR, createdRecord.getSubdomain());
|
||||
assertEquals(RecordType.A.getType(), createdRecord.getType());
|
||||
assertEquals(TTL, createdRecord.getTtl());
|
||||
assertEquals("127.0.0.1", createdRecord.getContent());
|
||||
assertNotNull(createdRecord.getCreatedOn());
|
||||
|
||||
List<RecordEntity> records = client.recordListBySubdomain(zone, SLD_STR, RecordType.A);
|
||||
assertEquals(1, records.size());
|
||||
RecordEntity fetchedRecord = records.get(0);
|
||||
assertEquals(createdRecord.getId(), fetchedRecord.getId());
|
||||
assertEquals(createdRecord.getContent(), fetchedRecord.getContent());
|
||||
assertEquals(createdRecord.getType(), fetchedRecord.getType());
|
||||
client.recordDelete(zone, createdRecord);
|
||||
|
||||
// test A and AAAA records for the same SLD
|
||||
RecordEntity recordA = RecordEntity.build(SLD_STR, RecordType.A, TTL, "127.0.0.2");
|
||||
RecordEntity recordAAAA = RecordEntity.build(SLD_STR, RecordType.AAAA, TTL, "2001:db8::1");
|
||||
RecordEntity createdRecordA = client.recordCreate(zone, recordA);
|
||||
RecordEntity createdRecordAAAA = client.recordCreate(zone, recordAAAA);
|
||||
assertNotNull(createdRecordA.getId());
|
||||
assertNotNull(createdRecordAAAA.getId());
|
||||
assertEquals(SLD_STR, createdRecordA.getSubdomain());
|
||||
assertEquals(SLD_STR, createdRecordAAAA.getSubdomain());
|
||||
assertEquals(RecordType.A.getType(), createdRecordA.getType());
|
||||
assertEquals(RecordType.AAAA.getType(), createdRecordAAAA.getType());
|
||||
|
||||
client.recordDeleteTypeIfExists(zone, SLD_STR, RecordType.A, RecordType.AAAA);
|
||||
assertThrows(CloudflareNotFoundException.class,
|
||||
() -> client.recordListBySubdomain(zone, SLD_STR, RecordType.A, RecordType.AAAA));
|
||||
} finally {
|
||||
// cleanup in case of failures during test
|
||||
try {
|
||||
client.recordDeleteTypeIfExists(zone, SLD_STR, RecordType.A, RecordType.AAAA);
|
||||
} catch (Exception e) { /* ignore */ }
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testZoneList() throws CloudflareApiException {
|
||||
List<ZoneEntity> zones = client.zoneList();
|
||||
assertNotNull(zones);
|
||||
assertFalse(zones.isEmpty());
|
||||
assertEquals(ZONE_STR, zones.get(0).getName());
|
||||
|
||||
zones = client.zoneList(PagingRequest.forZones(1, 50));
|
||||
assertNotNull(zones);
|
||||
assertFalse(zones.isEmpty());
|
||||
assertEquals(ZONE_STR, zones.get(0).getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testZoneListAnlFailedSldList() throws Exception {
|
||||
List<ZoneEntity> zList = client.zoneList();
|
||||
assertEquals(1, zList.size());
|
||||
|
||||
assertThrows(CloudflareNotFoundException.class,
|
||||
() -> client.recordListBySubdomain(zList.get(0), "not-existing"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDns() throws Exception {
|
||||
// starting point: already existing zone 'mein-d-ns.de'
|
||||
ZoneEntity z = client.zoneGet(ZONE_STR);
|
||||
assertEquals("cf9d8b12f61423f280e0a3ea2a96d921", z.getId());
|
||||
assertEquals("mein-d-ns.de", z.getName());
|
||||
assertEquals("active", z.getStatus());
|
||||
assertEquals(2, z.getNameServers().size());
|
||||
assertTrue(z.getNameServers().contains("rafe.ns.cloudflare.com"));
|
||||
assertTrue(z.getOriginalNameServers().size() >= 2);
|
||||
assertTrue(z.getOriginalNameServers().contains("blair.ns.cloudflare.com"));
|
||||
assertNotNull(z.getActivatedOn());
|
||||
assertNotNull(z.getModifiedOn());
|
||||
assertNotNull(z.getCreatedOn());
|
||||
|
||||
// for all other functions use a newly created SLD and ensure cleanup at the end
|
||||
String randomSld = SLD_STR + "-" + System.currentTimeMillis();
|
||||
String domain = randomSld + "." + ZONE_STR;
|
||||
|
||||
RecordEntity r;
|
||||
RecordEntity createdRe1;
|
||||
RecordEntity createdRe2;
|
||||
|
||||
try {
|
||||
// ensure clean state
|
||||
client.recordDeleteTypeIfExists(z, randomSld, RecordType.A, RecordType.AAAA);
|
||||
|
||||
// create A record using recordCreate with full domain
|
||||
createdRe1 =
|
||||
client.recordCreate(z, RecordEntity.build(domain, RecordType.A, TTL, "130.0.0.3"));
|
||||
assertNotNull(createdRe1.getId());
|
||||
assertEquals(randomSld + "." + ZONE_STR, createdRe1.getName());
|
||||
assertEquals(randomSld, createdRe1.getSubdomain());
|
||||
assertEquals(RecordType.A.getType(), createdRe1.getType());
|
||||
assertEquals(z.getId(), createdRe1.getZoneId());
|
||||
assertEquals(TTL, createdRe1.getTtl());
|
||||
assertEquals("130.0.0.3", createdRe1.getContent());
|
||||
assertNotNull(createdRe1.getCreatedOn());
|
||||
assertNotNull(createdRe1.getModifiedOn());
|
||||
|
||||
// verify recordList for A
|
||||
List<RecordEntity> aRecords = client.recordListBySubdomain(z, randomSld, RecordType.A);
|
||||
assertEquals(1, aRecords.size());
|
||||
r = aRecords.get(0);
|
||||
assertEquals("130.0.0.3", r.getContent());
|
||||
|
||||
// create AAAA record using recordCreateSubdomain
|
||||
createdRe2 =
|
||||
client.recordCreateSubdomain(z, randomSld, TTL, RecordType.AAAA, "2a0a:4cc0:c0:2e4::1");
|
||||
List<RecordEntity> aaaaRecords = client.recordListBySubdomain(z, randomSld, RecordType.AAAA);
|
||||
assertEquals(1, aaaaRecords.size());
|
||||
r = aaaaRecords.get(0);
|
||||
assertEquals(z.getId(), r.getZoneId());
|
||||
assertEquals("2a0a:4cc0:c0:2e4::1", r.getContent());
|
||||
assertEquals(RecordType.AAAA.getType(), r.getType());
|
||||
|
||||
// test recordList
|
||||
List<RecordEntity> rList = client.recordListBySubdomain(z, randomSld);
|
||||
assertEquals(2, rList.size());
|
||||
for (RecordEntity re : rList) {
|
||||
assertEquals(z.getId(), re.getZoneId());
|
||||
if (Objects.equals(re.getType(), RecordType.A.getType())) {
|
||||
assertEquals("130.0.0.3", re.getContent());
|
||||
} else if (Objects.equals(re.getType(), RecordType.AAAA.getType())) {
|
||||
assertEquals("2a0a:4cc0:c0:2e4::1", re.getContent());
|
||||
} else {
|
||||
fail(String.format("Unexpected record type: %s", re.getType()));
|
||||
}
|
||||
}
|
||||
|
||||
// test recordList without SLD (the unfiltered list may lag behind directly after creating records)
|
||||
List<RecordEntity> fullList = awaitRecords(() -> client.recordList(z),
|
||||
recs -> recs.stream().anyMatch(re -> re.getId().equals(createdRe2.getId())));
|
||||
assertTrue(fullList.size() >= 2);
|
||||
assertTrue(fullList.stream().anyMatch(re -> re.getId().equals(createdRe1.getId())));
|
||||
assertTrue(fullList.stream().anyMatch(re -> re.getId().equals(createdRe2.getId())));
|
||||
assertTrue(
|
||||
fullList.stream().allMatch(re -> re.getType().equals(RecordType.A.getType()) || re.getType().equals(RecordType.AAAA.getType())));
|
||||
|
||||
// test recordList with types without SLD
|
||||
List<RecordEntity> aList = awaitRecords(() -> client.recordListByType(z, RecordType.A),
|
||||
recs -> recs.stream().anyMatch(re -> re.getId().equals(createdRe1.getId())));
|
||||
assertFalse(aList.isEmpty());
|
||||
assertTrue(aList.stream().anyMatch(re -> re.getId().equals(createdRe1.getId())));
|
||||
assertTrue(aList.stream().noneMatch(re -> re.getId().equals(createdRe2.getId())));
|
||||
assertTrue(aList.stream().allMatch(re -> re.getType().equals(RecordType.A.getType())));
|
||||
|
||||
// test fluent api list
|
||||
List<RecordEntity> fluentList = client.zone(ZONE_STR).list(RecordType.A);
|
||||
assertFalse(fluentList.isEmpty());
|
||||
assertTrue(fluentList.stream().anyMatch(re -> re.getId().equals(createdRe1.getId())));
|
||||
|
||||
// update AAAA record, the given record (incl. its timestamps) must not be modified
|
||||
createdRe2.setContent("2a0a:4cc0:c0:2e4::2");
|
||||
Instant createdOn = createdRe2.getCreatedOn();
|
||||
RecordEntity updatedRe2 = client.recordUpdate(z, createdRe2);
|
||||
assertEquals(createdOn, createdRe2.getCreatedOn());
|
||||
assertNotNull(createdRe2.getModifiedOn());
|
||||
assertEquals("2a0a:4cc0:c0:2e4::2", updatedRe2.getContent());
|
||||
assertEquals(z.getId(), updatedRe2.getZoneId());
|
||||
aaaaRecords = client.recordListBySubdomain(z, randomSld, RecordType.AAAA);
|
||||
assertEquals(1, aaaaRecords.size());
|
||||
r = aaaaRecords.get(0);
|
||||
assertEquals("2a0a:4cc0:c0:2e4::2", r.getContent());
|
||||
|
||||
// verify A record still intact
|
||||
aRecords = client.recordListBySubdomain(z, randomSld, RecordType.A);
|
||||
assertEquals(1, aRecords.size());
|
||||
r = aRecords.get(0);
|
||||
assertEquals("130.0.0.3", r.getContent());
|
||||
|
||||
// delete AAAA record and verify it's gone
|
||||
assertTrue(client.recordDelete(z, createdRe2));
|
||||
assertThrows(CloudflareNotFoundException.class,
|
||||
() -> client.recordListBySubdomain(z, randomSld, RecordType.AAAA));
|
||||
|
||||
// delete A record using helper and verify it's gone
|
||||
client.recordDeleteTypeIfExists(z, randomSld, RecordType.A);
|
||||
assertThrows(CloudflareNotFoundException.class,
|
||||
() -> client.recordListBySubdomain(z, randomSld, RecordType.A));
|
||||
} finally {
|
||||
// cleanup in case of failures during test
|
||||
try {
|
||||
client.recordDeleteTypeIfExists(z, randomSld, RecordType.A, RecordType.AAAA);
|
||||
} catch (Exception e) { /* ignore */ }
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRecordEntityInvalidType() {
|
||||
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class,
|
||||
() -> RecordEntity.build("id123", "example.com", "INVALID_TYPE", 60, "192.168.1.1"));
|
||||
assertTrue(exception.getMessage().contains("Invalid record type: INVALID_TYPE"));
|
||||
assertTrue(exception.getMessage().contains("Must be one of:"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testBatch() throws Exception {
|
||||
// starting point: already existing zone 'mein-d-ns.de'
|
||||
ZoneEntity zone = client.zoneGet(ZONE_STR);
|
||||
|
||||
List<String> sldNames = createSldNames();
|
||||
List<RecordEntity> initialRecords = createInitialRecords(sldNames);
|
||||
|
||||
cleanupRecords(zone, sldNames);
|
||||
|
||||
try {
|
||||
testBatchPost(zone, initialRecords, sldNames);
|
||||
testBatchPatch(zone, sldNames);
|
||||
testBatchDelete(zone, sldNames);
|
||||
testBatchPut(zone, sldNames);
|
||||
} finally {
|
||||
cleanupRecords(zone, sldNames);
|
||||
}
|
||||
}
|
||||
|
||||
private List<String> createSldNames() {
|
||||
return List.of(SLD_STR + "-1", SLD_STR + "-2", SLD_STR + "-3");
|
||||
}
|
||||
|
||||
private List<RecordEntity> createInitialRecords(List<String> sldNames) {
|
||||
List<RecordEntity> records = new ArrayList<>();
|
||||
for (int i = 0; i < sldNames.size(); i++) {
|
||||
records.add(RecordEntity.build(sldNames.get(i), RecordType.A, TTL, IP_PREFIX + (i + 1)));
|
||||
}
|
||||
return records;
|
||||
}
|
||||
|
||||
private void cleanupRecords(ZoneEntity zone, List<String> sldNames) {
|
||||
sldNames.forEach(sld -> {
|
||||
try {
|
||||
client.recordDeleteTypeIfExists(zone, sld, RecordType.A);
|
||||
} catch (CloudflareApiException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void testBatchPost(ZoneEntity zone, List<RecordEntity> records, List<String> sldNames) throws Exception {
|
||||
// Use only first 2 records for POST
|
||||
List<RecordEntity> postRecords = records.subList(0, 2);
|
||||
BatchEntry batchEntry = client.recordBatch(zone, postRecords, null, null, null);
|
||||
assertEquals(2, batchEntry.getPosts().size());
|
||||
|
||||
RecordEntity batchedRecord = batchEntry.getPosts().get(0);
|
||||
assertValidBatchedRecord(batchedRecord, postRecords.get(0));
|
||||
|
||||
// Verify only the first 2 records
|
||||
for (int i = 0; i < 2; i++) {
|
||||
List<RecordEntity> records1 = client.recordListBySubdomain(zone, sldNames.get(i), RecordType.A);
|
||||
assertEquals(1, records1.size());
|
||||
assertEquals(IP_PREFIX + (i + 1), records1.get(0).getContent());
|
||||
}
|
||||
}
|
||||
|
||||
private void testBatchPatch(ZoneEntity zone, List<String> sldNames) throws Exception {
|
||||
// Use first 2 records for PATCH
|
||||
List<RecordEntity> patchRecords = new ArrayList<>();
|
||||
for (int i = 0; i < 2; i++) {
|
||||
List<RecordEntity> records = client.recordListBySubdomain(zone, sldNames.get(i), RecordType.A);
|
||||
RecordEntity record = records.get(0);
|
||||
record.setContent(UPDATED_IP_PREFIX + (i + 1));
|
||||
patchRecords.add(record);
|
||||
}
|
||||
|
||||
client.recordBatch(zone, null, null, patchRecords, null);
|
||||
|
||||
// Verify both records were updated
|
||||
for (int i = 0; i < 2; i++) {
|
||||
List<RecordEntity> updatedRecords = client.recordListBySubdomain(zone, sldNames.get(i), RecordType.A);
|
||||
assertEquals(1, updatedRecords.size());
|
||||
assertEquals(UPDATED_IP_PREFIX + (i + 1), updatedRecords.get(0).getContent());
|
||||
}
|
||||
}
|
||||
|
||||
private void testBatchDelete(ZoneEntity zone, List<String> sldNames) throws Exception {
|
||||
// Delete first 2 records
|
||||
List<RecordEntity> deleteRecords = new ArrayList<>();
|
||||
for (int i = 0; i < 2; i++) {
|
||||
List<RecordEntity> records = client.recordListBySubdomain(zone, sldNames.get(i), RecordType.A);
|
||||
deleteRecords.add(records.get(0));
|
||||
}
|
||||
|
||||
client.recordBatch(zone, null, null, null, deleteRecords);
|
||||
|
||||
// Verify both records are deleted
|
||||
for (int i = 0; i < 2; i++) {
|
||||
String sldName = sldNames.get(i);
|
||||
assertThrows(CloudflareNotFoundException.class,
|
||||
() -> client.recordListBySubdomain(zone, sldName, RecordType.A));
|
||||
}
|
||||
}
|
||||
|
||||
private void testBatchPut(ZoneEntity zone, List<String> sldNames) throws Exception {
|
||||
// Create 2 new records first for PUT test
|
||||
List<RecordEntity> newRecords = new ArrayList<>();
|
||||
for (int i = 0; i < 2; i++) {
|
||||
RecordEntity record = RecordEntity.build(sldNames.get(i), RecordType.A, TTL, IP_PREFIX + (i + 1));
|
||||
newRecords.add(record);
|
||||
}
|
||||
client.recordBatch(zone, newRecords, null, null, null);
|
||||
|
||||
// Now use PUT to replace them
|
||||
List<RecordEntity> putRecords = new ArrayList<>();
|
||||
for (int i = 0; i < 2; i++) {
|
||||
List<RecordEntity> records = client.recordListBySubdomain(zone, sldNames.get(i), RecordType.A);
|
||||
RecordEntity record = records.get(0);
|
||||
record.setContent(UPDATED_IP_PREFIX + (i + 1));
|
||||
putRecords.add(record);
|
||||
}
|
||||
client.recordBatch(zone, null, putRecords, null, null);
|
||||
|
||||
// Verify both records were updated
|
||||
for (int i = 0; i < 2; i++) {
|
||||
List<RecordEntity> updatedRecords = client.recordListBySubdomain(zone, sldNames.get(i), RecordType.A);
|
||||
assertEquals(1, updatedRecords.size());
|
||||
assertEquals(UPDATED_IP_PREFIX + (i + 1), updatedRecords.get(0).getContent());
|
||||
}
|
||||
}
|
||||
|
||||
private void assertValidBatchedRecord(RecordEntity batchedRecord, RecordEntity originalRecord) {
|
||||
assertNotNull(batchedRecord.getId());
|
||||
assertEquals(originalRecord.getSubdomain(), batchedRecord.getSubdomain());
|
||||
assertEquals(originalRecord.getType(), batchedRecord.getType());
|
||||
assertNotNull(batchedRecord.getCreatedOn());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testFluentApi() throws Exception {
|
||||
ZoneEntity zone = client.zoneGet(ZONE_STR);
|
||||
String fluentSld = "fluent-" + System.currentTimeMillis();
|
||||
|
||||
try {
|
||||
// Test fluent create
|
||||
RecordEntity created = client.zone(ZONE_STR)
|
||||
.getRecord(fluentSld)
|
||||
.create(RecordType.A, "192.168.100.1", TTL);
|
||||
|
||||
assertNotNull(created.getId());
|
||||
assertEquals(fluentSld, created.getSubdomain());
|
||||
assertEquals("192.168.100.1", created.getContent());
|
||||
|
||||
// Test fluent get
|
||||
List<RecordEntity> records = client.zone(ZONE_STR)
|
||||
.getRecord(fluentSld, RecordType.A)
|
||||
.get();
|
||||
|
||||
assertEquals(1, records.size());
|
||||
assertEquals("192.168.100.1", records.get(0).getContent());
|
||||
|
||||
// Test fluent update
|
||||
RecordEntity updated = client.zone(ZONE_STR)
|
||||
.getRecord(fluentSld, RecordType.A)
|
||||
.update("192.168.100.2");
|
||||
|
||||
assertEquals("192.168.100.2", updated.getContent());
|
||||
|
||||
// Test fluent delete
|
||||
client.zone(ZONE_STR)
|
||||
.getRecord(fluentSld)
|
||||
.delete(RecordType.A);
|
||||
|
||||
assertThrows(CloudflareNotFoundException.class,
|
||||
() -> client.zone(ZONE_STR).getRecord(fluentSld, RecordType.A).get());
|
||||
|
||||
} finally {
|
||||
try {
|
||||
client.recordDeleteTypeIfExists(zone, fluentSld, RecordType.A);
|
||||
} catch (Exception e) { /* ignore */ }
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGroupRecordsByFqdn_withValidRecords() {
|
||||
// Arrange
|
||||
RecordEntity rec1 = RecordEntity.build("1", "example.com.", "A", 300, "192.168.1.1");
|
||||
RecordEntity rec2 = RecordEntity.build("2", "example.com.", "AAAA", 300, "::1");
|
||||
RecordEntity rec3 = RecordEntity.build("3", "sub.example.com.", "CNAME", 300, "example.com.");
|
||||
List<RecordEntity> records = Arrays.asList(rec1, rec2, rec3);
|
||||
|
||||
// Act
|
||||
Map<String, List<RecordEntity>> groupedRecords = CfDnsClient.groupRecordsByFqdn(records);
|
||||
|
||||
// Assert
|
||||
assertNotNull(groupedRecords, "Resulting map should not be null.");
|
||||
assertEquals(2, groupedRecords.size(), "The grouping should result in 2 FQDN keys.");
|
||||
assertEquals(2, groupedRecords.get("example.com.").size(), "The key 'example.com.' should have 2 records.");
|
||||
assertEquals(1, groupedRecords.get("sub.example.com.").size(), "The key 'sub.example.com.' should have 1 record.");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGroupRecordsByFqdn_withMultipleRecordsSameFqdn() {
|
||||
// Arrange
|
||||
RecordEntity rec1 = RecordEntity.build("1", "example.com.", "A", 300, "192.168.1.1");
|
||||
RecordEntity rec2 = RecordEntity.build("2", "example.com.", "AAAA", 300, "::1");
|
||||
List<RecordEntity> records = Arrays.asList(rec1, rec2);
|
||||
|
||||
// Act
|
||||
Map<String, List<RecordEntity>> groupedRecords = CfDnsClient.groupRecordsByFqdn(records);
|
||||
|
||||
// Assert
|
||||
assertNotNull(groupedRecords, "Resulting map should not be null.");
|
||||
assertEquals(1, groupedRecords.size(), "The grouping should result in 1 FQDN key.");
|
||||
assertEquals(2, groupedRecords.get("example.com.").size(), "The key 'example.com.' should have 2 records.");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testPaging() throws Exception {
|
||||
ZoneEntity zone = client.zoneGet(ZONE_STR);
|
||||
String pagingSld = "paging-" + System.currentTimeMillis();
|
||||
List<RecordEntity> createdRecords = new ArrayList<>();
|
||||
Set<String> createdIds = new HashSet<>();
|
||||
|
||||
try {
|
||||
List<RecordEntity> staleRecords = List.of();
|
||||
try {
|
||||
staleRecords = client.recordList(zone).stream()
|
||||
.filter(record -> record.getName() != null && record.getName().startsWith("paging-"))
|
||||
.toList();
|
||||
} catch (CloudflareNotFoundException ignored) {
|
||||
// The zone is empty.
|
||||
}
|
||||
deleteQuietly(zone, staleRecords);
|
||||
|
||||
// Each record gets its own name, so the order by name is unambiguous.
|
||||
for (int i = 1; i <= 12; i++) {
|
||||
String name = String.format("%s-%02d.%s", pagingSld, i, ZONE_STR);
|
||||
RecordEntity record = RecordEntity.build(name, RecordType.A, TTL, "127.0.0." + i);
|
||||
RecordEntity created = client.recordCreate(zone, record);
|
||||
createdRecords.add(created);
|
||||
assertNotNull(created.getId());
|
||||
createdIds.add(created.getId());
|
||||
}
|
||||
|
||||
PagedResult pagedResult = pageThrough(zone, createdIds, 5);
|
||||
List<String> pagedIds = pagedResult.pages().stream()
|
||||
.flatMap(List::stream)
|
||||
.map(RecordEntity::getId)
|
||||
.toList();
|
||||
Set<String> pagedIdSet = new HashSet<>(pagedIds);
|
||||
|
||||
for (int page = 1; page <= pagedResult.pages().size(); page++) {
|
||||
int expected = Math.max(0, Math.min(5,
|
||||
pagedResult.total() - 5 * (page - 1)));
|
||||
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");
|
||||
|
||||
List<String> createdNamesInPageOrder = pagedResult.pages().stream()
|
||||
.flatMap(List::stream)
|
||||
.filter(record -> createdIds.contains(record.getId()))
|
||||
.map(RecordEntity::getName)
|
||||
.toList();
|
||||
assertEquals(createdRecords.stream().map(RecordEntity::getName).toList(),
|
||||
createdNamesInPageOrder, "The test records should be sorted by name");
|
||||
|
||||
// Without PagingRequest all pages must be fetched, also if the page size is small
|
||||
try (CfDnsClient smallPageClient = new CfDnsClient(true, CfDnsClientBuilder.DEFAULT_BASEURL,
|
||||
new CfDnsClientBuilder.ApiTokenAuth(API_TOKEN), 5)) {
|
||||
List<RecordEntity> allRecords = awaitRecords(() -> smallPageClient.recordList(zone),
|
||||
recs -> ids(recs).containsAll(createdIds));
|
||||
assertTrue(ids(allRecords).containsAll(createdIds));
|
||||
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 {
|
||||
deleteQuietly(zone, createdRecords);
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
void testApiErrorDetails() throws Exception {
|
||||
ZoneEntity zone = client.zoneGet(ZONE_STR);
|
||||
String sub = "invalid-" + System.currentTimeMillis();
|
||||
try {
|
||||
// an A record with an invalid IP is rejected by Cloudflare
|
||||
CloudflareApiException e = assertThrows(CloudflareApiException.class,
|
||||
() -> client.recordCreateSubdomain(zone, sub, TTL, RecordType.A, "not-an-ip"));
|
||||
assertEquals(CloudflareApiException.class, e.getClass());
|
||||
assertEquals(400, e.getStatusCode());
|
||||
assertFalse(e.getErrors().isEmpty());
|
||||
assertTrue(e.getErrors().get(0).getCode() > 0);
|
||||
// the Cloudflare error message is part of the exception message, not wrapped
|
||||
assertTrue(e.getMessage().contains(e.getErrors().get(0).getMessage()), e.getMessage());
|
||||
} finally {
|
||||
try {
|
||||
client.recordDeleteTypeIfExists(zone, sub, RecordType.A);
|
||||
} catch (Exception e) { /* ignore */ }
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRecordDeleteUnknownId() throws Exception {
|
||||
ZoneEntity zone = client.zoneGet(ZONE_STR);
|
||||
CloudflareApiException e = assertThrows(CloudflareApiException.class,
|
||||
() -> client.recordDelete(zone, "0123456789abcdef0123456789abcdef"));
|
||||
assertInstanceOf(CloudflareNotFoundException.class, e);
|
||||
assertEquals(404, e.getStatusCode());
|
||||
assertFalse(e.getErrors().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testZoneNotFound() throws Exception {
|
||||
String unknownZone = "not-existing-" + System.currentTimeMillis() + ".de";
|
||||
// emptyResultThrowsException = true
|
||||
assertThrows(CloudflareNotFoundException.class, () -> client.zoneGet(unknownZone));
|
||||
assertThrows(CloudflareNotFoundException.class, () -> client.zone(unknownZone));
|
||||
|
||||
// emptyResultThrowsException = false
|
||||
try (CfDnsClient lenientClient = new CfDnsClientBuilder().withApiTokenAuth(API_TOKEN).build()) {
|
||||
assertNull(lenientClient.zoneGet(unknownZone));
|
||||
assertThrows(CloudflareNotFoundException.class, () -> lenientClient.zone(unknownZone));
|
||||
assertNotNull(lenientClient.zoneGet(ZONE_STR));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testClientClose() throws Exception {
|
||||
CfDnsClient closeableClient = new CfDnsClientBuilder().withApiTokenAuth(API_TOKEN).build();
|
||||
// multiple requests with the same client
|
||||
assertNotNull(closeableClient.zoneGet(ZONE_STR));
|
||||
assertFalse(closeableClient.zoneList().isEmpty());
|
||||
assertDoesNotThrow(closeableClient::close);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testMultiLevelSubdomainAndApex() throws Exception {
|
||||
ZoneEntity zone = client.zoneGet(ZONE_STR);
|
||||
String multiLevel = "a.b-" + System.currentTimeMillis();
|
||||
String apexContent = "cf-client-test-" + System.currentTimeMillis();
|
||||
List<RecordEntity> created = new ArrayList<>();
|
||||
try {
|
||||
// multi-level subdomain
|
||||
RecordEntity rec = client.recordCreateSubdomain(zone, multiLevel, TTL, RecordType.A, "130.0.0.10");
|
||||
created.add(rec);
|
||||
assertEquals(multiLevel + "." + ZONE_STR, rec.getName());
|
||||
assertEquals(multiLevel, rec.getSubdomain());
|
||||
List<RecordEntity> fetched = client.recordListBySubdomain(zone, multiLevel, RecordType.A);
|
||||
assertEquals(1, fetched.size());
|
||||
assertEquals(multiLevel, fetched.get(0).getSubdomain());
|
||||
assertEquals(ZONE_STR, fetched.get(0).getZoneName());
|
||||
|
||||
// batch with a multi-level name must not cut the name
|
||||
String batchName = "c.d-" + System.currentTimeMillis() + "." + ZONE_STR;
|
||||
BatchEntry batchResult = client.recordBatch(zone,
|
||||
List.of(RecordEntity.build(batchName, RecordType.A, TTL, "130.0.0.11")), null, null, null);
|
||||
RecordEntity batched = batchResult.getPosts().get(0);
|
||||
created.add(batched);
|
||||
assertEquals(batchName, batched.getName());
|
||||
|
||||
// zone apex (TXT record with unique content, existing apex records stay untouched)
|
||||
RecordEntity apex = client.recordCreateSubdomain(zone, CfDnsClient.APEX, TTL, RecordType.TXT,
|
||||
"\"" + apexContent + "\"");
|
||||
created.add(apex);
|
||||
assertEquals(ZONE_STR, apex.getName());
|
||||
assertEquals(CfDnsClient.APEX, apex.getSubdomain());
|
||||
assertTrue(client.recordListBySubdomain(zone, CfDnsClient.APEX, RecordType.TXT).stream()
|
||||
.anyMatch(r -> r.getId().equals(apex.getId()) && CfDnsClient.APEX.equals(r.getSubdomain())));
|
||||
} finally {
|
||||
deleteQuietly(zone, created);
|
||||
}
|
||||
}
|
||||
|
||||
@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
|
||||
void testTypeFilter() throws Exception {
|
||||
ZoneEntity zone = client.zoneGet(ZONE_STR);
|
||||
String sub = "types-" + System.currentTimeMillis();
|
||||
List<RecordEntity> created = new ArrayList<>();
|
||||
try {
|
||||
created.add(client.recordCreateSubdomain(zone, sub, TTL, RecordType.A, "130.0.0.20"));
|
||||
created.add(client.recordCreateSubdomain(zone, sub, TTL, RecordType.AAAA, "2001:db8::20"));
|
||||
created.add(client.recordCreateSubdomain(zone, sub, TTL, RecordType.TXT, "\"type filter\""));
|
||||
|
||||
// one type: filtered by Cloudflare
|
||||
List<RecordEntity> txt = client.recordListBySubdomain(zone, sub, RecordType.TXT);
|
||||
assertEquals(1, txt.size());
|
||||
assertEquals(RecordType.TXT.getType(), txt.get(0).getType());
|
||||
assertTrue(client.recordListByType(zone, RecordType.TXT).stream()
|
||||
.allMatch(r -> RecordType.TXT.getType().equals(r.getType())));
|
||||
|
||||
// multiple types: filtered by the client
|
||||
List<RecordEntity> ip = client.recordListBySubdomain(zone, sub, RecordType.A, RecordType.AAAA);
|
||||
assertEquals(Set.of("A", "AAAA"), ip.stream().map(RecordEntity::getType).collect(Collectors.toSet()));
|
||||
|
||||
// no type: all records
|
||||
assertEquals(3, client.recordListBySubdomain(zone, sub).size());
|
||||
} finally {
|
||||
deleteQuietly(zone, created);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRecordAttributes() throws Exception {
|
||||
ZoneEntity zone = client.zoneGet(ZONE_STR);
|
||||
String sub = "attr-" + System.currentTimeMillis();
|
||||
List<RecordEntity> created = new ArrayList<>();
|
||||
Instant start = Instant.now().minusSeconds(60);
|
||||
try {
|
||||
// MX record with priority and comment
|
||||
RecordEntity mx = RecordEntity.build(sub + "." + ZONE_STR, RecordType.MX, TTL, "mail." + ZONE_STR);
|
||||
mx.setPriority(10);
|
||||
mx.setComment("cf client test");
|
||||
RecordEntity createdMx = client.recordCreate(zone, mx);
|
||||
created.add(createdMx);
|
||||
assertEquals(10, createdMx.getPriority());
|
||||
assertEquals("cf client test", createdMx.getComment());
|
||||
assertNull(mx.getId(), "the given record must not be modified");
|
||||
// timestamps are Instants (UTC)
|
||||
assertTrue(createdMx.getCreatedOn().isAfter(start), createdMx.getCreatedOn().toString());
|
||||
assertTrue(createdMx.getCreatedOn().isBefore(Instant.now().plusSeconds(60)));
|
||||
|
||||
RecordEntity fetchedMx = client.recordListBySubdomain(zone, sub, RecordType.MX).get(0);
|
||||
assertEquals(10, fetchedMx.getPriority());
|
||||
assertEquals("cf client test", fetchedMx.getComment());
|
||||
|
||||
// partial update keeps the attributes which aren't sent
|
||||
RecordEntity updatedMx = client.recordUpdate(zone, RecordEntity.build(fetchedMx.getId(), "mx2." + ZONE_STR));
|
||||
assertEquals("mx2." + ZONE_STR, updatedMx.getContent());
|
||||
assertEquals(10, updatedMx.getPriority());
|
||||
assertEquals("cf client test", updatedMx.getComment());
|
||||
|
||||
// batch PATCH changes the priority
|
||||
fetchedMx = client.recordListBySubdomain(zone, sub, RecordType.MX).get(0);
|
||||
fetchedMx.setPriority(20);
|
||||
client.recordBatch(zone, null, null, List.of(fetchedMx), null);
|
||||
assertEquals(20, client.recordListBySubdomain(zone, sub, RecordType.MX).get(0).getPriority());
|
||||
|
||||
// SRV record with structured data, for SRV records the priority is part of the data
|
||||
String srvName = "_sip._tcp." + sub + "." + ZONE_STR;
|
||||
RecordEntity srv = RecordEntity.build(srvName, RecordType.SRV, TTL, null);
|
||||
srv.setData(Map.of("priority", 10, "weight", 5, "port", 5060, "target", "sip." + ZONE_STR));
|
||||
RecordEntity createdSrv = client.recordCreate(zone, srv);
|
||||
created.add(createdSrv);
|
||||
assertEquals(srvName, createdSrv.getName());
|
||||
assertEquals(10, ((Number) createdSrv.getData().get("priority")).intValue());
|
||||
assertEquals(5060, ((Number) createdSrv.getData().get("port")).intValue());
|
||||
assertEquals(5, ((Number) createdSrv.getData().get("weight")).intValue());
|
||||
assertEquals("sip." + ZONE_STR, createdSrv.getData().get("target"));
|
||||
} finally {
|
||||
deleteQuietly(zone, created);
|
||||
}
|
||||
}
|
||||
|
||||
private void deleteQuietly(ZoneEntity zone, List<RecordEntity> records) {
|
||||
for (RecordEntity rec : records) {
|
||||
try {
|
||||
client.recordDelete(zone, rec.getId());
|
||||
} catch (Exception e) {
|
||||
log.warn("Couldn't delete test record {}: {}", rec.getName(), e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@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;
|
||||
}
|
||||
}
|
||||
@@ -56,17 +56,17 @@ public class CfClientPenTest {
|
||||
"doesnotexist", "abcdef12345", "unwahrscheinlich-" + System.currentTimeMillis());
|
||||
|
||||
for (String sld : syntacticallyInvalidSlds) {
|
||||
assertThrows(IllegalArgumentException.class, () -> client.recordList(zone, sld),
|
||||
assertThrows(IllegalArgumentException.class, () -> client.recordListBySubdomain(zone, sld),
|
||||
"Should throw IllegalArgumentException for invalid SLD '" + sld + "'");
|
||||
}
|
||||
for (String sld : syntacticallyValidOrNotAllowedFromCloudflare) {
|
||||
assertThrows(CloudflareNotFoundException.class, () -> client.recordList(zone, sld),
|
||||
assertThrows(CloudflareNotFoundException.class, () -> client.recordListBySubdomain(zone, sld),
|
||||
"Should throw CloudflareNotFoundException for valid but non-existing SLD '" + sld + "'");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Invalid getRecord content and TTL boundaries must be rejected by API")
|
||||
@DisplayName("Invalid record content and TTL boundaries must be rejected by API")
|
||||
void testInvalidRecordCreateInputsRejected() throws Exception {
|
||||
CfDnsClient client = newClient();
|
||||
ZoneEntity zone = client.zoneGet(ZONE_STR);
|
||||
@@ -81,11 +81,11 @@ public class CfClientPenTest {
|
||||
}
|
||||
|
||||
try {
|
||||
// A getRecord with invalid IPv4
|
||||
// A record with invalid IPv4
|
||||
assertThrows(CloudflareApiException.class,
|
||||
() -> client.recordCreate(zone, fqdn, 60, RecordType.A, "999.999.999.999"));
|
||||
|
||||
// AAAA getRecord with non-IP content
|
||||
// AAAA record with non-IP content
|
||||
assertThrows(CloudflareApiException.class,
|
||||
() -> client.recordCreate(zone, fqdn, 60, RecordType.AAAA, "not-an-ipv6"));
|
||||
|
||||
|
||||
@@ -1,528 +0,0 @@
|
||||
package codes.thischwa.cf;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
import static org.junit.jupiter.api.Assumptions.assumeTrue;
|
||||
|
||||
import codes.thischwa.cf.model.BatchEntry;
|
||||
import codes.thischwa.cf.model.PagingRequest;
|
||||
import codes.thischwa.cf.model.RecordEntity;
|
||||
import codes.thischwa.cf.model.RecordType;
|
||||
import codes.thischwa.cf.model.ZoneEntity;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
@Slf4j
|
||||
public class CfClientTest {
|
||||
|
||||
private static final String ZONE_STR = "mein-d-ns.de";
|
||||
private static final String SLD_STR = "devsld";
|
||||
private static final int TTL = 60;
|
||||
|
||||
private static final String API_TOKEN = System.getenv("API_TOKEN");
|
||||
|
||||
private final CfDnsClient client = new CfDnsClientBuilder().withEmptyResultThrowsException(true).withApiTokenAuth(API_TOKEN).build();
|
||||
|
||||
@BeforeAll
|
||||
static void checkEnv() {
|
||||
assumeTrue(API_TOKEN != null && !API_TOKEN.isBlank(), "API_TOKEN not set; skipping client tests");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUnknownSld() throws Exception {
|
||||
ZoneEntity zone = client.zoneGet(ZONE_STR);
|
||||
assertThrows(CloudflareNotFoundException.class, () -> client.recordList(zone, "unknown", RecordType.A));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAddHost() throws Exception {
|
||||
ZoneEntity zone = client.zoneGet(ZONE_STR);
|
||||
|
||||
try {
|
||||
// clean-up
|
||||
client.recordDeleteTypeIfExists(zone, SLD_STR, RecordType.A, RecordType.AAAA);
|
||||
|
||||
RecordEntity record = RecordEntity.build(SLD_STR, RecordType.A, TTL, "127.0.0.1");
|
||||
RecordEntity createdRecord = client.recordCreate(zone, record);
|
||||
assertNotNull(createdRecord.getId());
|
||||
assertEquals(SLD_STR, createdRecord.getSld());
|
||||
assertEquals(RecordType.A.getType(), createdRecord.getType());
|
||||
assertEquals(TTL, createdRecord.getTtl());
|
||||
assertEquals("127.0.0.1", createdRecord.getContent());
|
||||
assertNotNull(createdRecord.getCreatedOn());
|
||||
|
||||
List<RecordEntity> records = client.recordList(zone, SLD_STR, RecordType.A);
|
||||
assertEquals(1, records.size());
|
||||
RecordEntity fetchedRecord = records.get(0);
|
||||
assertEquals(createdRecord.getId(), fetchedRecord.getId());
|
||||
assertEquals(createdRecord.getContent(), fetchedRecord.getContent());
|
||||
assertEquals(createdRecord.getType(), fetchedRecord.getType());
|
||||
client.recordDelete(zone, createdRecord);
|
||||
|
||||
// test A and AAAA records for the same SLD
|
||||
RecordEntity recordA = RecordEntity.build(SLD_STR, RecordType.A, TTL, "127.0.0.2");
|
||||
RecordEntity recordAAAA = RecordEntity.build(SLD_STR, RecordType.AAAA, TTL, "2001:db8::1");
|
||||
RecordEntity createdRecordA = client.recordCreate(zone, recordA);
|
||||
RecordEntity createdRecordAAAA = client.recordCreate(zone, recordAAAA);
|
||||
assertNotNull(createdRecordA.getId());
|
||||
assertNotNull(createdRecordAAAA.getId());
|
||||
assertEquals(SLD_STR, createdRecordA.getSld());
|
||||
assertEquals(SLD_STR, createdRecordAAAA.getSld());
|
||||
assertEquals(RecordType.A.getType(), createdRecordA.getType());
|
||||
assertEquals(RecordType.AAAA.getType(), createdRecordAAAA.getType());
|
||||
|
||||
client.recordDeleteTypeIfExists(zone, SLD_STR, RecordType.A, RecordType.AAAA);
|
||||
assertThrows(CloudflareNotFoundException.class,
|
||||
() -> client.recordList(zone, SLD_STR, RecordType.A, RecordType.AAAA));
|
||||
} finally {
|
||||
// cleanup in case of failures during test
|
||||
try {
|
||||
client.recordDeleteTypeIfExists(zone, SLD_STR, RecordType.A, RecordType.AAAA);
|
||||
} catch (Exception e) { /* ignore */ }
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testZoneList() throws CloudflareApiException {
|
||||
List<ZoneEntity> zones = client.zoneList();
|
||||
assertNotNull(zones);
|
||||
assertFalse(zones.isEmpty());
|
||||
assertEquals(ZONE_STR, zones.get(0).getName());
|
||||
|
||||
zones = client.zoneList(PagingRequest.of(1, 100));
|
||||
assertNotNull(zones);
|
||||
assertFalse(zones.isEmpty());
|
||||
assertEquals(ZONE_STR, zones.get(0).getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testZoneListAnlFailedSldList() throws Exception {
|
||||
List<ZoneEntity> zList = client.zoneList();
|
||||
assertEquals(1, zList.size());
|
||||
|
||||
assertThrows(CloudflareNotFoundException.class,
|
||||
() -> client.recordList(zList.get(0), "not-existing"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDns() throws Exception {
|
||||
// starting point: already existing zone 'mein-d-ns.de'
|
||||
ZoneEntity z = client.zoneGet(ZONE_STR);
|
||||
assertEquals("cf9d8b12f61423f280e0a3ea2a96d921", z.getId());
|
||||
assertEquals("mein-d-ns.de", z.getName());
|
||||
assertEquals("active", z.getStatus());
|
||||
assertEquals(2, z.getNameServers().size());
|
||||
assertTrue(z.getNameServers().contains("rafe.ns.cloudflare.com"));
|
||||
assertTrue(z.getOriginalNameServers().size() >= 2);
|
||||
assertTrue(z.getOriginalNameServers().contains("blair.ns.cloudflare.com"));
|
||||
assertNotNull(z.getActivatedOn());
|
||||
assertNotNull(z.getModifiedOn());
|
||||
assertNotNull(z.getCreatedOn());
|
||||
|
||||
// for all other functions use a newly created SLD and ensure cleanup at the end
|
||||
String randomSld = SLD_STR + "-" + System.currentTimeMillis();
|
||||
String domain = randomSld + "." + ZONE_STR;
|
||||
|
||||
RecordEntity r;
|
||||
RecordEntity createdRe1;
|
||||
RecordEntity createdRe2;
|
||||
|
||||
try {
|
||||
// ensure clean state
|
||||
client.recordDeleteTypeIfExists(z, randomSld, RecordType.A, RecordType.AAAA);
|
||||
|
||||
// create A getRecord using recordCreate with full domain
|
||||
createdRe1 =
|
||||
client.recordCreate(z, RecordEntity.build(domain, RecordType.A, TTL, "130.0.0.3"));
|
||||
assertNotNull(createdRe1.getId());
|
||||
assertEquals(randomSld + "." + ZONE_STR, createdRe1.getName());
|
||||
assertEquals(randomSld, createdRe1.getSld());
|
||||
assertEquals(RecordType.A.getType(), createdRe1.getType());
|
||||
assertEquals(z.getId(), createdRe1.getZoneId());
|
||||
assertEquals(TTL, createdRe1.getTtl());
|
||||
assertEquals("130.0.0.3", createdRe1.getContent());
|
||||
assertNotNull(createdRe1.getCreatedOn());
|
||||
assertNotNull(createdRe1.getModifiedOn());
|
||||
|
||||
// verify recordList for A
|
||||
List<RecordEntity> aRecords = client.recordList(z, randomSld, RecordType.A);
|
||||
assertEquals(1, aRecords.size());
|
||||
r = aRecords.get(0);
|
||||
assertEquals("130.0.0.3", r.getContent());
|
||||
|
||||
// create AAAA getRecord using recordCreateSld
|
||||
createdRe2 =
|
||||
client.recordCreateSld(z, randomSld, TTL, RecordType.AAAA, "2a0a:4cc0:c0:2e4::1");
|
||||
List<RecordEntity> aaaaRecords = client.recordList(z, randomSld, RecordType.AAAA);
|
||||
assertEquals(1, aaaaRecords.size());
|
||||
r = aaaaRecords.get(0);
|
||||
assertEquals(z.getId(), r.getZoneId());
|
||||
assertEquals("2a0a:4cc0:c0:2e4::1", r.getContent());
|
||||
assertEquals(RecordType.AAAA.getType(), r.getType());
|
||||
|
||||
// test recordList
|
||||
List<RecordEntity> rList = client.recordList(z, randomSld);
|
||||
assertEquals(2, rList.size());
|
||||
for (RecordEntity re : rList) {
|
||||
assertEquals(z.getId(), re.getZoneId());
|
||||
if (Objects.equals(re.getType(), RecordType.A.getType())) {
|
||||
assertEquals("130.0.0.3", re.getContent());
|
||||
} else if (Objects.equals(re.getType(), RecordType.AAAA.getType())) {
|
||||
assertEquals("2a0a:4cc0:c0:2e4::1", re.getContent());
|
||||
} else {
|
||||
fail(String.format("Unexpected getRecord type: %s", re.getType()));
|
||||
}
|
||||
}
|
||||
|
||||
// test recordList without SLD
|
||||
List<RecordEntity> fullList = client.recordList(z);
|
||||
assertTrue(fullList.size() >= 2);
|
||||
assertTrue(fullList.stream().anyMatch(re -> re.getId().equals(createdRe1.getId())));
|
||||
assertTrue(fullList.stream().anyMatch(re -> re.getId().equals(createdRe2.getId())));
|
||||
assertTrue(
|
||||
fullList.stream().allMatch(re -> re.getType().equals(RecordType.A.getType()) || re.getType().equals(RecordType.AAAA.getType())));
|
||||
|
||||
// test recordList with types without SLD
|
||||
List<RecordEntity> aList = client.recordList(z, RecordType.A);
|
||||
assertFalse(aList.isEmpty());
|
||||
assertTrue(aList.stream().anyMatch(re -> re.getId().equals(createdRe1.getId())));
|
||||
assertTrue(aList.stream().noneMatch(re -> re.getId().equals(createdRe2.getId())));
|
||||
assertTrue(aList.stream().allMatch(re -> re.getType().equals(RecordType.A.getType())));
|
||||
|
||||
// test fluent api list
|
||||
List<RecordEntity> fluentList = client.zone(ZONE_STR).list(RecordType.A);
|
||||
assertFalse(fluentList.isEmpty());
|
||||
assertTrue(fluentList.stream().anyMatch(re -> re.getId().equals(createdRe1.getId())));
|
||||
|
||||
// update AAAA getRecord
|
||||
createdRe2.setContent("2a0a:4cc0:c0:2e4::2");
|
||||
client.recordUpdate(z, createdRe2);
|
||||
aaaaRecords = client.recordList(z, randomSld, RecordType.AAAA);
|
||||
assertEquals(1, aaaaRecords.size());
|
||||
r = aaaaRecords.get(0);
|
||||
assertEquals("2a0a:4cc0:c0:2e4::2", r.getContent());
|
||||
|
||||
// verify A getRecord still intact
|
||||
aRecords = client.recordList(z, randomSld, RecordType.A);
|
||||
assertEquals(1, aRecords.size());
|
||||
r = aRecords.get(0);
|
||||
assertEquals("130.0.0.3", r.getContent());
|
||||
|
||||
// delete AAAA getRecord and verify it's gone
|
||||
assertTrue(client.recordDelete(z, createdRe2));
|
||||
assertThrows(CloudflareNotFoundException.class,
|
||||
() -> client.recordList(z, randomSld, RecordType.AAAA));
|
||||
|
||||
// delete A getRecord using helper and verify it's gone
|
||||
client.recordDeleteTypeIfExists(z, randomSld, RecordType.A);
|
||||
assertThrows(CloudflareNotFoundException.class,
|
||||
() -> client.recordList(z, randomSld, RecordType.A));
|
||||
} finally {
|
||||
// cleanup in case of failures during test
|
||||
try {
|
||||
client.recordDeleteTypeIfExists(z, randomSld, RecordType.A, RecordType.AAAA);
|
||||
} catch (Exception e) { /* ignore */ }
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRecordEntityInvalidType() {
|
||||
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class,
|
||||
() -> RecordEntity.build("id123", "example.com", "INVALID_TYPE", 60, "192.168.1.1"));
|
||||
assertTrue(exception.getMessage().contains("Invalid getRecord type: INVALID_TYPE"));
|
||||
assertTrue(exception.getMessage().contains("Must be one of:"));
|
||||
}
|
||||
|
||||
private static final String IP_PREFIX = "130.0.0.";
|
||||
private static final String UPDATED_IP_PREFIX = "130.1.0.";
|
||||
|
||||
|
||||
@Test
|
||||
void testBatch() throws Exception {
|
||||
// starting point: already existing zone 'mein-d-ns.de'
|
||||
ZoneEntity zone = client.zoneGet(ZONE_STR);
|
||||
|
||||
List<String> sldNames = createSldNames();
|
||||
List<RecordEntity> initialRecords = createInitialRecords(sldNames);
|
||||
|
||||
cleanupRecords(zone, sldNames);
|
||||
|
||||
try {
|
||||
testBatchPost(zone, initialRecords, sldNames);
|
||||
testBatchPatch(zone, sldNames);
|
||||
testBatchDelete(zone, sldNames);
|
||||
testBatchPut(zone, sldNames);
|
||||
} finally {
|
||||
cleanupRecords(zone, sldNames);
|
||||
}
|
||||
}
|
||||
|
||||
private List<String> createSldNames() {
|
||||
return List.of(SLD_STR + "-1", SLD_STR + "-2", SLD_STR + "-3");
|
||||
}
|
||||
|
||||
private List<RecordEntity> createInitialRecords(List<String> sldNames) {
|
||||
List<RecordEntity> records = new ArrayList<>();
|
||||
for (int i = 0; i < sldNames.size(); i++) {
|
||||
records.add(RecordEntity.build(sldNames.get(i), RecordType.A, TTL, IP_PREFIX + (i + 1)));
|
||||
}
|
||||
return records;
|
||||
}
|
||||
|
||||
private void cleanupRecords(ZoneEntity zone, List<String> sldNames) {
|
||||
sldNames.forEach(sld -> {
|
||||
try {
|
||||
client.recordDeleteTypeIfExists(zone, sld, RecordType.A);
|
||||
} catch (CloudflareApiException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void testBatchPost(ZoneEntity zone, List<RecordEntity> records, List<String> sldNames) throws Exception {
|
||||
// Use only first 2 records for POST
|
||||
List<RecordEntity> postRecords = records.subList(0, 2);
|
||||
BatchEntry batchEntry = client.recordBatch(zone, postRecords, null, null, null);
|
||||
assertEquals(2, batchEntry.getPosts().size());
|
||||
|
||||
RecordEntity batchedRecord = batchEntry.getPosts().get(0);
|
||||
assertValidBatchedRecord(batchedRecord, postRecords.get(0));
|
||||
|
||||
// Verify only the first 2 records
|
||||
for (int i = 0; i < 2; i++) {
|
||||
List<RecordEntity> records1 = client.recordList(zone, sldNames.get(i), RecordType.A);
|
||||
assertEquals(1, records1.size());
|
||||
assertEquals(IP_PREFIX + (i + 1), records1.get(0).getContent());
|
||||
}
|
||||
}
|
||||
|
||||
private void testBatchPatch(ZoneEntity zone, List<String> sldNames) throws Exception {
|
||||
// Use first 2 records for PATCH
|
||||
List<RecordEntity> patchRecords = new ArrayList<>();
|
||||
for (int i = 0; i < 2; i++) {
|
||||
List<RecordEntity> records = client.recordList(zone, sldNames.get(i), RecordType.A);
|
||||
RecordEntity record = records.get(0);
|
||||
record.setContent(UPDATED_IP_PREFIX + (i + 1));
|
||||
patchRecords.add(record);
|
||||
}
|
||||
|
||||
client.recordBatch(zone, null, null, patchRecords, null);
|
||||
|
||||
// Verify both records were updated
|
||||
for (int i = 0; i < 2; i++) {
|
||||
List<RecordEntity> updatedRecords = client.recordList(zone, sldNames.get(i), RecordType.A);
|
||||
assertEquals(1, updatedRecords.size());
|
||||
assertEquals(UPDATED_IP_PREFIX + (i + 1), updatedRecords.get(0).getContent());
|
||||
}
|
||||
}
|
||||
|
||||
private void testBatchDelete(ZoneEntity zone, List<String> sldNames) throws Exception {
|
||||
// Delete first 2 records
|
||||
List<RecordEntity> deleteRecords = new ArrayList<>();
|
||||
for (int i = 0; i < 2; i++) {
|
||||
List<RecordEntity> records = client.recordList(zone, sldNames.get(i), RecordType.A);
|
||||
deleteRecords.add(records.get(0));
|
||||
}
|
||||
|
||||
client.recordBatch(zone, null, null, null, deleteRecords);
|
||||
|
||||
// Verify both records are deleted
|
||||
for (int i = 0; i < 2; i++) {
|
||||
String sldName = sldNames.get(i);
|
||||
assertThrows(CloudflareNotFoundException.class,
|
||||
() -> client.recordList(zone, sldName, RecordType.A));
|
||||
}
|
||||
}
|
||||
|
||||
private void testBatchPut(ZoneEntity zone, List<String> sldNames) throws Exception {
|
||||
// Create 2 new records first for PUT test
|
||||
List<RecordEntity> newRecords = new ArrayList<>();
|
||||
for (int i = 0; i < 2; i++) {
|
||||
RecordEntity record = RecordEntity.build(sldNames.get(i), RecordType.A, TTL, IP_PREFIX + (i + 1));
|
||||
newRecords.add(record);
|
||||
}
|
||||
client.recordBatch(zone, newRecords, null, null, null);
|
||||
|
||||
// Now use PUT to replace them
|
||||
List<RecordEntity> putRecords = new ArrayList<>();
|
||||
for (int i = 0; i < 2; i++) {
|
||||
List<RecordEntity> records = client.recordList(zone, sldNames.get(i), RecordType.A);
|
||||
RecordEntity record = records.get(0);
|
||||
record.setContent(UPDATED_IP_PREFIX + (i + 1));
|
||||
putRecords.add(record);
|
||||
}
|
||||
client.recordBatch(zone, null, putRecords, null, null);
|
||||
|
||||
// Verify both records were updated
|
||||
for (int i = 0; i < 2; i++) {
|
||||
List<RecordEntity> updatedRecords = client.recordList(zone, sldNames.get(i), RecordType.A);
|
||||
assertEquals(1, updatedRecords.size());
|
||||
assertEquals(UPDATED_IP_PREFIX + (i + 1), updatedRecords.get(0).getContent());
|
||||
}
|
||||
}
|
||||
|
||||
private void assertValidBatchedRecord(RecordEntity batchedRecord, RecordEntity originalRecord) {
|
||||
assertNotNull(batchedRecord.getId());
|
||||
assertEquals(originalRecord.getSld(), batchedRecord.getSld());
|
||||
assertEquals(originalRecord.getType(), batchedRecord.getType());
|
||||
assertNotNull(batchedRecord.getCreatedOn());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testFluentApi() throws Exception {
|
||||
ZoneEntity zone = client.zoneGet(ZONE_STR);
|
||||
String fluentSld = "fluent-" + System.currentTimeMillis();
|
||||
|
||||
try {
|
||||
// Test fluent create
|
||||
RecordEntity created = client.zone(ZONE_STR)
|
||||
.getRecord(fluentSld)
|
||||
.create(RecordType.A, "192.168.100.1", TTL);
|
||||
|
||||
assertNotNull(created.getId());
|
||||
assertEquals(fluentSld, created.getSld());
|
||||
assertEquals("192.168.100.1", created.getContent());
|
||||
|
||||
// Test fluent get
|
||||
List<RecordEntity> records = client.zone(ZONE_STR)
|
||||
.getRecord(fluentSld, RecordType.A)
|
||||
.get();
|
||||
|
||||
assertEquals(1, records.size());
|
||||
assertEquals("192.168.100.1", records.get(0).getContent());
|
||||
|
||||
// Test fluent update
|
||||
RecordEntity updated = client.zone(ZONE_STR)
|
||||
.getRecord(fluentSld, RecordType.A)
|
||||
.update("192.168.100.2");
|
||||
|
||||
assertEquals("192.168.100.2", updated.getContent());
|
||||
|
||||
// Test fluent delete
|
||||
client.zone(ZONE_STR)
|
||||
.getRecord(fluentSld)
|
||||
.delete(RecordType.A);
|
||||
|
||||
assertThrows(CloudflareNotFoundException.class,
|
||||
() -> client.zone(ZONE_STR).getRecord(fluentSld, RecordType.A).get());
|
||||
|
||||
} finally {
|
||||
try {
|
||||
client.recordDeleteTypeIfExists(zone, fluentSld, RecordType.A);
|
||||
} catch (Exception e) { /* ignore */ }
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGroupRecordsByFqdn_withValidRecords() {
|
||||
// Arrange
|
||||
RecordEntity rec1 = RecordEntity.build("1", "example.com.", "A", 300, "192.168.1.1");
|
||||
RecordEntity rec2 = RecordEntity.build("2", "example.com.", "AAAA", 300, "::1");
|
||||
RecordEntity rec3 = RecordEntity.build("3", "sub.example.com.", "CNAME", 300, "example.com.");
|
||||
List<RecordEntity> records = Arrays.asList(rec1, rec2, rec3);
|
||||
|
||||
// Act
|
||||
Map<String, List<RecordEntity>> groupedRecords = CfDnsClient.groupRecordsByFqdn(records);
|
||||
|
||||
// Assert
|
||||
assertNotNull(groupedRecords, "Resulting map should not be null.");
|
||||
assertEquals(2, groupedRecords.size(), "The grouping should result in 2 FQDN keys.");
|
||||
assertEquals(2, groupedRecords.get("example.com.").size(), "The key 'example.com.' should have 2 records.");
|
||||
assertEquals(1, groupedRecords.get("sub.example.com.").size(), "The key 'sub.example.com.' should have 1 getRecord.");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGroupRecordsByFqdn_withMultipleRecordsSameFqdn() {
|
||||
// Arrange
|
||||
RecordEntity rec1 = RecordEntity.build("1", "example.com.", "A", 300, "192.168.1.1");
|
||||
RecordEntity rec2 = RecordEntity.build("2", "example.com.", "AAAA", 300, "::1");
|
||||
List<RecordEntity> records = Arrays.asList(rec1, rec2);
|
||||
|
||||
// Act
|
||||
Map<String, List<RecordEntity>> groupedRecords = CfDnsClient.groupRecordsByFqdn(records);
|
||||
|
||||
// Assert
|
||||
assertNotNull(groupedRecords, "Resulting map should not be null.");
|
||||
assertEquals(1, groupedRecords.size(), "The grouping should result in 1 FQDN key.");
|
||||
assertEquals(2, groupedRecords.get("example.com.").size(), "The key 'example.com.' should have 2 records.");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void testPaging() throws Exception {
|
||||
ZoneEntity zone = client.zoneGet(ZONE_STR);
|
||||
String pagingSld = "paging-" + System.currentTimeMillis();
|
||||
|
||||
try {
|
||||
int existingCount = 0;
|
||||
try {
|
||||
List<RecordEntity> allRecords = client.recordList(zone);
|
||||
existingCount = allRecords.size();
|
||||
} catch (CloudflareApiException e) {
|
||||
// ignore
|
||||
}
|
||||
|
||||
// Calculate how many records we need to create to reach at least 12 total A records
|
||||
// (to test paging with pageSize 5: page 1 = 5, page 2 = 5, page 3 = 2+)
|
||||
int targetCount = 12;
|
||||
int recordsToCreate = Math.max(0, targetCount - existingCount);
|
||||
|
||||
// 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);
|
||||
createdRecords.add(created);
|
||||
assertNotNull(created.getId());
|
||||
}
|
||||
|
||||
// Test paging with page size of 5
|
||||
PagingRequest page1Request = PagingRequest.of(1, 5);
|
||||
List<RecordEntity> page1Records = client.recordList(zone, page1Request);
|
||||
assertEquals(5, page1Records.size(), "First page should contain 5 records");
|
||||
|
||||
// 2nd page should also contain 5 records (if we have at least 12 total)
|
||||
PagingRequest page2Request = PagingRequest.of(2, 5);
|
||||
List<RecordEntity> page2Records = client.recordList(zone, page2Request);
|
||||
assertEquals(5, page2Records.size(), "Second page should contain at least 5 records");
|
||||
|
||||
// 3rd page should contain 2 records
|
||||
PagingRequest page3Request = PagingRequest.of(3, 5);
|
||||
List<RecordEntity> page3Records = client.recordList(zone, page3Request);
|
||||
assertEquals(2, page3Records.size(), "Third page should contain 2 records");
|
||||
|
||||
// Verify no overlap between pages
|
||||
List<String> page1Ids = page1Records.stream().map(RecordEntity::getId).toList();
|
||||
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));
|
||||
} finally {
|
||||
try {
|
||||
client.recordDeleteTypeIfExists(zone, pagingSld, RecordType.A);
|
||||
} catch (Exception e) { /* ignore */ }
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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.assertThrows;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.time.Duration;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
@@ -124,18 +126,6 @@ class CfDnsClientBuilderTest {
|
||||
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
|
||||
void testEmptyResultThrowsExceptionToggle() {
|
||||
// Test toggling the flag multiple times (last one wins)
|
||||
@@ -147,4 +137,65 @@ class CfDnsClientBuilderTest {
|
||||
|
||||
assertNotNull(client);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testBaseUrlMustUseHttps() {
|
||||
CfDnsClientBuilder builder = new CfDnsClientBuilder().withApiTokenAuth("test-token");
|
||||
assertThrows(IllegalArgumentException.class, () -> builder.withBaseUrl("http://api.example.com"));
|
||||
assertThrows(IllegalArgumentException.class, () -> builder.withBaseUrl("ftp://api.example.com"));
|
||||
assertThrows(IllegalArgumentException.class, () -> builder.withBaseUrl("api.example.com"));
|
||||
assertThrows(IllegalArgumentException.class, () -> builder.withBaseUrl("https://"));
|
||||
assertThrows(IllegalArgumentException.class, () -> builder.withBaseUrl("https://api example.com"));
|
||||
assertThrows(IllegalArgumentException.class, () -> builder.withBaseUrl("https://api.example.com/v4?x=1"));
|
||||
assertThrows(IllegalArgumentException.class, () -> builder.withBaseUrl("https://api.example.com/v4#x"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void 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());
|
||||
}
|
||||
}
|
||||
@@ -5,10 +5,12 @@ import codes.thischwa.cf.model.*;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.net.IDN;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@@ -118,6 +120,34 @@ class CfDnsClientMockTest {
|
||||
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
|
||||
void testZoneGet() throws Exception {
|
||||
// Create mock zone response
|
||||
@@ -188,7 +218,7 @@ class CfDnsClientMockTest {
|
||||
@Test
|
||||
void testRecordList_WithPaging() throws Exception {
|
||||
ZoneEntity zone = createTestZone();
|
||||
PagingRequest pagingRequest = PagingRequest.of(10, 1);
|
||||
PagingRequest pagingRequest = PagingRequest.forRecords(10, 1);
|
||||
|
||||
RecordMultipleResponse mockResponse = new RecordMultipleResponse();
|
||||
mockResponse.setResultInfo(createResultInfo(1));
|
||||
@@ -218,7 +248,7 @@ class CfDnsClientMockTest {
|
||||
CfDnsClient spyClient = spy(client);
|
||||
doReturn(mockResponse).when(spyClient).getRequest(anyString(), eq(RecordMultipleResponse.class));
|
||||
|
||||
List<RecordEntity> records = spyClient.recordList(zone, "test");
|
||||
List<RecordEntity> records = spyClient.recordListBySubdomain(zone, "test");
|
||||
|
||||
assertNotNull(records);
|
||||
assertEquals(1, records.size());
|
||||
@@ -239,7 +269,7 @@ class CfDnsClientMockTest {
|
||||
CfDnsClient spyClient = spy(client);
|
||||
doReturn(mockResponse).when(spyClient).getRequest(anyString(), eq(RecordMultipleResponse.class));
|
||||
|
||||
List<RecordEntity> records = spyClient.recordList(zone, "test", RecordType.A);
|
||||
List<RecordEntity> records = spyClient.recordListBySubdomain(zone, "test", RecordType.A);
|
||||
|
||||
assertNotNull(records);
|
||||
assertEquals(1, records.size());
|
||||
@@ -260,7 +290,7 @@ class CfDnsClientMockTest {
|
||||
CfDnsClient spyClient = spy(client);
|
||||
doReturn(mockResponse).when(spyClient).getRequest(anyString(), eq(RecordMultipleResponse.class));
|
||||
|
||||
List<RecordEntity> records = spyClient.recordList(zone, RecordType.A);
|
||||
List<RecordEntity> records = spyClient.recordListByType(zone, RecordType.A);
|
||||
|
||||
assertNotNull(records);
|
||||
assertEquals(1, records.size());
|
||||
@@ -360,7 +390,7 @@ class CfDnsClientMockTest {
|
||||
ZoneEntity zone = createTestZone();
|
||||
|
||||
CfDnsClient spyClient = spy(client);
|
||||
doThrow(new CloudflareNotFoundException("Not found")).when(spyClient).recordList(any(), anyString(), any());
|
||||
doThrow(new CloudflareNotFoundException("Not found")).when(spyClient).recordListBySubdomain(any(), anyString(), any());
|
||||
|
||||
// Should not throw exception when record doesn't exist
|
||||
assertDoesNotThrow(() -> spyClient.recordDeleteTypeIfExists(zone, "test", RecordType.A));
|
||||
@@ -396,4 +426,487 @@ class CfDnsClientMockTest {
|
||||
assertEquals(1, result.getPosts().size());
|
||||
assertEquals(TEST_ZONE_ID, result.getPosts().get(0).getZoneId());
|
||||
}
|
||||
|
||||
private ZoneMultipleResponse zoneResponse(List<ZoneEntity> zones, ResultInfo resultInfo) {
|
||||
ZoneMultipleResponse resp = new ZoneMultipleResponse();
|
||||
resp.setResult(zones);
|
||||
resp.setResultInfo(resultInfo);
|
||||
resp.setResponseResultInfo(createSuccessResultInfo());
|
||||
return resp;
|
||||
}
|
||||
|
||||
private RecordMultipleResponse recordResponse(List<RecordEntity> records, ResultInfo resultInfo) {
|
||||
RecordMultipleResponse resp = new RecordMultipleResponse();
|
||||
resp.setResult(records);
|
||||
resp.setResultInfo(resultInfo);
|
||||
resp.setResponseResultInfo(createSuccessResultInfo());
|
||||
return resp;
|
||||
}
|
||||
|
||||
private static ZoneEntity zone(String id, String name) {
|
||||
ZoneEntity zone = new ZoneEntity();
|
||||
zone.setId(id);
|
||||
zone.setName(name);
|
||||
return zone;
|
||||
}
|
||||
|
||||
@Test
|
||||
void testZoneGet_NotFound_ReturnsNull() throws Exception {
|
||||
CfDnsClient spyClient = spy(client);
|
||||
doReturn(zoneResponse(List.of(), new ResultInfo(0)))
|
||||
.when(spyClient).getRequest(anyString(), eq(ZoneMultipleResponse.class));
|
||||
|
||||
assertNull(spyClient.zoneGet("unknown.com"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testZoneGet_NotFound_ThrowsIfEnabled() throws Exception {
|
||||
CfDnsClient throwingClient = spy(new CfDnsClientBuilder()
|
||||
.withApiTokenAuth("test-token")
|
||||
.withEmptyResultThrowsException(true)
|
||||
.build());
|
||||
doReturn(zoneResponse(List.of(), new ResultInfo(0)))
|
||||
.when(throwingClient).getRequest(anyString(), eq(ZoneMultipleResponse.class));
|
||||
|
||||
assertThrows(CloudflareNotFoundException.class, () -> throwingClient.zoneGet("unknown.com"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testZone_NotFound_Throws() throws Exception {
|
||||
CfDnsClient spyClient = spy(client);
|
||||
doReturn(zoneResponse(List.of(), new ResultInfo(0)))
|
||||
.when(spyClient).getRequest(anyString(), eq(ZoneMultipleResponse.class));
|
||||
|
||||
assertThrows(CloudflareNotFoundException.class, () -> spyClient.zone("unknown.com"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testZoneList_FetchesAllPages() throws Exception {
|
||||
CfDnsClient spyClient = spy(client);
|
||||
doReturn(zoneResponse(List.of(zone("z1", "a.com"), zone("z2", "b.com")),
|
||||
new ResultInfo(1, 2, 2, 2, 3)))
|
||||
.when(spyClient).getRequest(eq("/zones?page=1&per_page=" + PagingRequest.DEFAULT_PAGE_SIZE),
|
||||
eq(ZoneMultipleResponse.class));
|
||||
doReturn(zoneResponse(List.of(zone("z3", "c.com")), new ResultInfo(2, 2, 2, 1, 3)))
|
||||
.when(spyClient).getRequest(eq("/zones?page=2&per_page=" + PagingRequest.DEFAULT_PAGE_SIZE),
|
||||
eq(ZoneMultipleResponse.class));
|
||||
|
||||
List<ZoneEntity> zones = spyClient.zoneList();
|
||||
|
||||
assertEquals(List.of("a.com", "b.com", "c.com"), zones.stream().map(ZoneEntity::getName).toList());
|
||||
verify(spyClient, times(2)).getRequest(anyString(), eq(ZoneMultipleResponse.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRecordListByType_FetchesAllPages() throws Exception {
|
||||
ZoneEntity zone = createTestZone();
|
||||
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);
|
||||
doReturn(recordResponse(List.of(RecordEntity.build("a.example.com", RecordType.A, 60, "1.1.1.1")),
|
||||
new ResultInfo(1, 1, 2, 1, 2)))
|
||||
.when(spyClient).getRequest(eq(String.format(base, 1)), eq(RecordMultipleResponse.class));
|
||||
doReturn(recordResponse(List.of(RecordEntity.build("b.example.com", RecordType.A, 60, "2.2.2.2")),
|
||||
new ResultInfo(2, 1, 2, 1, 2)))
|
||||
.when(spyClient).getRequest(eq(String.format(base, 2)), eq(RecordMultipleResponse.class));
|
||||
|
||||
List<RecordEntity> records = spyClient.recordListByType(zone, RecordType.A);
|
||||
|
||||
assertEquals(2, records.size());
|
||||
assertEquals("b.example.com", records.get(1).getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRecordListBySld_FetchesAllPages() throws Exception {
|
||||
ZoneEntity zone = createTestZone();
|
||||
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 spyClient = spy(client);
|
||||
doReturn(recordResponse(List.of(RecordEntity.build("test.example.com", RecordType.A, 60, "1.1.1.1")),
|
||||
new ResultInfo(1, 1, 2, 1, 2)))
|
||||
.when(spyClient).getRequest(eq(String.format(base, 1)), eq(RecordMultipleResponse.class));
|
||||
doReturn(recordResponse(List.of(RecordEntity.build("test.example.com", RecordType.AAAA, 60, "::1")),
|
||||
new ResultInfo(2, 1, 2, 1, 2)))
|
||||
.when(spyClient).getRequest(eq(String.format(base, 2)), eq(RecordMultipleResponse.class));
|
||||
|
||||
assertEquals(2, spyClient.recordListBySubdomain(zone, "test").size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRecordList_SetsZoneNameForSld() throws Exception {
|
||||
ZoneEntity zone = createTestZone();
|
||||
CfDnsClient spyClient = spy(client);
|
||||
doReturn(recordResponse(List.of(
|
||||
RecordEntity.build("example.com", RecordType.A, 60, "1.1.1.1"),
|
||||
RecordEntity.build("my.sub.example.com", RecordType.A, 60, "2.2.2.2")),
|
||||
new ResultInfo(2)))
|
||||
.when(spyClient).getRequest(anyString(), eq(RecordMultipleResponse.class));
|
||||
|
||||
List<RecordEntity> records = spyClient.recordList(zone);
|
||||
|
||||
assertEquals(TEST_ZONE_NAME, records.get(0).getZoneName());
|
||||
assertEquals("@", records.get(0).getSubdomain());
|
||||
assertEquals("my.sub", records.get(1).getSubdomain());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRecordListByApex() throws Exception {
|
||||
ZoneEntity zone = createTestZone();
|
||||
CfDnsClient spyClient = spy(client);
|
||||
doReturn(recordResponse(List.of(), new ResultInfo(0)))
|
||||
.when(spyClient).getRequest(anyString(), eq(RecordMultipleResponse.class));
|
||||
|
||||
spyClient.recordListBySubdomain(zone, CfDnsClient.APEX);
|
||||
|
||||
verify(spyClient).getRequest(
|
||||
eq("/zones/" + TEST_ZONE_ID + "/dns_records?name=example.com&order=name&direction=asc&page=1&per_page="
|
||||
+ CfDnsClient.RECORDS_PER_PAGE),
|
||||
eq(RecordMultipleResponse.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRecordDelete_NoResult_ReturnsFalse() throws Exception {
|
||||
RecordSingleResponse mockResponse = new RecordSingleResponse();
|
||||
mockResponse.setResponseResultInfo(createSuccessResultInfo());
|
||||
CfDnsClient spyClient = spy(client);
|
||||
doReturn(mockResponse).when(spyClient).deleteRequest(anyString(), eq(RecordSingleResponse.class));
|
||||
|
||||
assertFalse(spyClient.recordDelete(createTestZone(), TEST_RECORD_ID));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRecordDelete_OtherId_ReturnsFalse() throws Exception {
|
||||
RecordSingleResponse mockResponse = new RecordSingleResponse();
|
||||
RecordEntity other = new RecordEntity();
|
||||
other.setId("other");
|
||||
mockResponse.setResult(other);
|
||||
mockResponse.setResponseResultInfo(createSuccessResultInfo());
|
||||
CfDnsClient spyClient = spy(client);
|
||||
doReturn(mockResponse).when(spyClient).deleteRequest(anyString(), eq(RecordSingleResponse.class));
|
||||
|
||||
assertFalse(spyClient.recordDelete(createTestZone(), TEST_RECORD_ID));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRecordBatch_UsesFullRecordName() throws Exception {
|
||||
ZoneEntity zone = createTestZone();
|
||||
RecordEntity apex = RecordEntity.build("example.com", RecordType.A, 300, "1.2.3.4");
|
||||
RecordEntity multiLevel = RecordEntity.build("a.b.example.com", RecordType.A, 300, "1.2.3.5");
|
||||
|
||||
BatchResponse mockResponse = createBatchResponse();
|
||||
mockResponse.setResult(new BatchEntry());
|
||||
mockResponse.setResponseResultInfo(createSuccessResultInfo());
|
||||
CfDnsClient spyClient = spy(client);
|
||||
doReturn(mockResponse).when(spyClient).postRequest(anyString(), any(), eq(BatchResponse.class));
|
||||
|
||||
spyClient.recordBatch(zone, List.of(apex, multiLevel), List.of(multiLevel), null, List.of(apex));
|
||||
|
||||
ArgumentCaptor<Object> payload = ArgumentCaptor.forClass(Object.class);
|
||||
verify(spyClient).postRequest(anyString(), payload.capture(), eq(BatchResponse.class));
|
||||
BatchEntry sent = (BatchEntry) payload.getValue();
|
||||
assertEquals(List.of("example.com", "a.b.example.com"),
|
||||
sent.getPosts().stream().map(RecordEntity::getName).toList());
|
||||
assertEquals("a.b.example.com", sent.getPuts().get(0).getName());
|
||||
// deletes only need the ID
|
||||
assertNull(sent.getDeletes().get(0).getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRecordList_NullPagingIsUnambiguousAndFetchesAll() throws Exception {
|
||||
CfDnsClient spyClient = spy(client);
|
||||
doReturn(recordResponse(List.of(RecordEntity.build("a.example.com", RecordType.A, 60, "1.1.1.1")),
|
||||
new ResultInfo(1)))
|
||||
.when(spyClient).getRequest(anyString(), eq(RecordMultipleResponse.class));
|
||||
|
||||
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
|
||||
void testRecordListByType_SingleTypeIsFilteredServerSide() throws Exception {
|
||||
CfDnsClient spyClient = spy(client);
|
||||
doReturn(recordResponse(List.of(), new ResultInfo(0)))
|
||||
.when(spyClient).getRequest(anyString(), eq(RecordMultipleResponse.class));
|
||||
|
||||
spyClient.recordListByType(createTestZone(), RecordType.MX);
|
||||
spyClient.recordListBySubdomain(createTestZone(), "www", RecordType.TXT);
|
||||
|
||||
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));
|
||||
verify(spyClient).getRequest(eq("/zones/" + TEST_ZONE_ID
|
||||
+ "/dns_records?name=www.example.com&type=TXT&order=name&direction=asc&page=1&per_page="
|
||||
+ CfDnsClient.RECORDS_PER_PAGE), eq(RecordMultipleResponse.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRecordListByType_MultipleTypesAreFilteredClientSide() throws Exception {
|
||||
RecordEntity unknownType = new RecordEntity();
|
||||
unknownType.setName("x.example.com");
|
||||
unknownType.setType("UNKNOWN_FUTURE_TYPE");
|
||||
CfDnsClient spyClient = spy(client);
|
||||
doReturn(recordResponse(List.of(
|
||||
RecordEntity.build("a.example.com", RecordType.A, 60, "1.1.1.1"),
|
||||
RecordEntity.build("a.example.com", RecordType.AAAA, 60, "::1"),
|
||||
RecordEntity.build("a.example.com", RecordType.TXT, 60, "txt"),
|
||||
unknownType), new ResultInfo(4)))
|
||||
.when(spyClient).getRequest(anyString(), eq(RecordMultipleResponse.class));
|
||||
|
||||
// an unknown record type in the response must not break the filter
|
||||
List<RecordEntity> records = spyClient.recordListByType(createTestZone(), RecordType.A, RecordType.AAAA);
|
||||
|
||||
assertEquals(List.of("A", "AAAA"), records.stream().map(RecordEntity::getType).toList());
|
||||
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));
|
||||
}
|
||||
|
||||
private static RecordEntity fetchedMxRecord() {
|
||||
RecordEntity rec = RecordEntity.build("example.com", RecordType.MX, 300, "mail.example.com");
|
||||
rec.setId(TEST_RECORD_ID);
|
||||
rec.setPriority(10);
|
||||
rec.setProxied(false);
|
||||
rec.setComment("primary mx");
|
||||
rec.setTags(List.of("env:prod"));
|
||||
rec.setZoneId(TEST_ZONE_ID);
|
||||
rec.setZoneName(TEST_ZONE_NAME);
|
||||
rec.setLocked(false);
|
||||
rec.setProxiable(false);
|
||||
rec.setCreatedOn(java.time.Instant.parse("2025-01-01T00:00:00Z"));
|
||||
rec.setModifiedOn(java.time.Instant.parse("2025-01-02T00:00:00Z"));
|
||||
return rec;
|
||||
}
|
||||
|
||||
private static void assertOnlyWritableFields(RecordEntity sent) {
|
||||
assertEquals("example.com", sent.getName());
|
||||
assertEquals("MX", sent.getType());
|
||||
assertEquals("mail.example.com", sent.getContent());
|
||||
assertEquals(10, sent.getPriority());
|
||||
assertEquals(false, sent.getProxied());
|
||||
assertEquals("primary mx", sent.getComment());
|
||||
assertEquals(List.of("env:prod"), sent.getTags());
|
||||
assertNull(sent.getZoneId());
|
||||
assertNull(sent.getZoneName());
|
||||
assertNull(sent.getLocked());
|
||||
assertNull(sent.getProxiable());
|
||||
assertNull(sent.getCreatedOn());
|
||||
assertNull(sent.getModifiedOn());
|
||||
}
|
||||
|
||||
private RecordSingleResponse singleResponse(RecordEntity rec) {
|
||||
RecordSingleResponse resp = new RecordSingleResponse();
|
||||
resp.setResult(rec);
|
||||
resp.setResponseResultInfo(createSuccessResultInfo());
|
||||
return resp;
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRecordUpdate_DoesNotModifyGivenRecordAndSendsWritableFields() throws Exception {
|
||||
RecordEntity rec = fetchedMxRecord();
|
||||
RecordEntity before = fetchedMxRecord();
|
||||
CfDnsClient spyClient = spy(client);
|
||||
doReturn(singleResponse(fetchedMxRecord()))
|
||||
.when(spyClient).patchRequest(anyString(), any(), eq(RecordSingleResponse.class));
|
||||
|
||||
spyClient.recordUpdate(createTestZone(), rec);
|
||||
|
||||
assertEquals(before, rec);
|
||||
ArgumentCaptor<Object> payload = ArgumentCaptor.forClass(Object.class);
|
||||
verify(spyClient).patchRequest(eq("/zones/" + TEST_ZONE_ID + "/dns_records/" + TEST_RECORD_ID),
|
||||
payload.capture(), eq(RecordSingleResponse.class));
|
||||
assertOnlyWritableFields((RecordEntity) payload.getValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRecordCreate_SendsWritableFieldsWithoutId() throws Exception {
|
||||
RecordEntity rec = fetchedMxRecord();
|
||||
CfDnsClient spyClient = spy(client);
|
||||
doReturn(singleResponse(fetchedMxRecord()))
|
||||
.when(spyClient).postRequest(anyString(), any(), eq(RecordSingleResponse.class));
|
||||
|
||||
spyClient.recordCreate(createTestZone(), rec);
|
||||
|
||||
ArgumentCaptor<Object> payload = ArgumentCaptor.forClass(Object.class);
|
||||
verify(spyClient).postRequest(anyString(), payload.capture(), eq(RecordSingleResponse.class));
|
||||
RecordEntity sent = (RecordEntity) payload.getValue();
|
||||
assertOnlyWritableFields(sent);
|
||||
assertNull(sent.getId());
|
||||
assertEquals(TEST_RECORD_ID, rec.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRecordBatch_KeepsPriorityDataAndProxied() throws Exception {
|
||||
RecordEntity srv = RecordEntity.build("_sip._tcp.example.com", RecordType.SRV, 300, null);
|
||||
srv.setId("srv1");
|
||||
srv.setPriority(10);
|
||||
srv.setData(Map.of("priority", 10, "weight", 5, "port", 5060, "target", "sip.example.com"));
|
||||
RecordEntity proxied = RecordEntity.build("www.example.com", RecordType.A, 1, "1.2.3.4");
|
||||
proxied.setId("www1");
|
||||
proxied.setProxied(true);
|
||||
|
||||
BatchResponse mockResponse = createBatchResponse();
|
||||
mockResponse.setResult(new BatchEntry());
|
||||
mockResponse.setResponseResultInfo(createSuccessResultInfo());
|
||||
CfDnsClient spyClient = spy(client);
|
||||
doReturn(mockResponse).when(spyClient).postRequest(anyString(), any(), eq(BatchResponse.class));
|
||||
|
||||
spyClient.recordBatch(createTestZone(), List.of(srv), List.of(proxied), List.of(srv), null);
|
||||
|
||||
ArgumentCaptor<Object> payload = ArgumentCaptor.forClass(Object.class);
|
||||
verify(spyClient).postRequest(anyString(), payload.capture(), eq(BatchResponse.class));
|
||||
BatchEntry sent = (BatchEntry) payload.getValue();
|
||||
RecordEntity sentPost = sent.getPosts().get(0);
|
||||
assertNull(sentPost.getId());
|
||||
assertEquals(10, sentPost.getPriority());
|
||||
assertEquals(5060, sentPost.getData().get("port"));
|
||||
assertEquals("www1", sent.getPuts().get(0).getId());
|
||||
assertEquals(true, sent.getPuts().get(0).getProxied());
|
||||
assertEquals("srv1", sent.getPatches().get(0).getId());
|
||||
assertEquals(10, sent.getPatches().get(0).getPriority());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testInvalidSubdomainIsRejectedBeforeRequest() throws Exception {
|
||||
CfDnsClient spyClient = spy(client);
|
||||
ZoneEntity zone = createTestZone();
|
||||
for (String sub : List.of("; rm -rf /", "| cat /etc/passwd", "`shutdown -h now`",
|
||||
"<script>alert('x')</script>", "\"quoted\"", "a b", "x?y", "x#y", "x&y", "x\ty", " ", "")) {
|
||||
assertThrows(IllegalArgumentException.class, () -> spyClient.recordListBySubdomain(zone, sub), sub);
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> spyClient.recordCreateSubdomain(zone, sub, 60, RecordType.A, "1.2.3.4"), sub);
|
||||
}
|
||||
assertThrows(IllegalArgumentException.class, () -> spyClient.recordListBySubdomain(zone, null));
|
||||
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,
|
||||
() -> 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"));
|
||||
}
|
||||
}
|
||||
@@ -3,12 +3,15 @@ package codes.thischwa.cf;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
import codes.thischwa.cf.model.AbstractResponse;
|
||||
import codes.thischwa.cf.model.BatchResponse;
|
||||
import codes.thischwa.cf.model.RecordEntity;
|
||||
import codes.thischwa.cf.model.RecordMultipleResponse;
|
||||
import codes.thischwa.cf.model.RecordSingleResponse;
|
||||
import codes.thischwa.cf.model.RecordType;
|
||||
import codes.thischwa.cf.model.ResponseResultInfo;
|
||||
import codes.thischwa.cf.model.ZoneMultipleResponse;
|
||||
import java.io.InputStream;
|
||||
@@ -50,4 +53,35 @@ public class ObjectMapperTest {
|
||||
fail("fail for " + clazz + ": " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSubdomainIsNotSerialized() {
|
||||
RecordEntity rec = RecordEntity.build("www.example.com", RecordType.A, 60, "1.2.3.4");
|
||||
rec.setZoneName("example.com");
|
||||
String json = mapper.writeValueAsString(rec);
|
||||
assertTrue(json.contains("\"name\":\"www.example.com\""), json);
|
||||
assertFalse(json.contains("subdomain"), json);
|
||||
assertFalse(json.contains("sld"), json);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRecordFieldsAreMappedInSnakeCase() {
|
||||
String json = """
|
||||
{"id":"r1","name":"_sip._tcp.example.com","type":"SRV","ttl":300,"priority":10,
|
||||
"comment":"sip","tags":["env:prod"],
|
||||
"data":{"weight":5,"port":5060,"target":"sip.example.com"},
|
||||
"created_on":"2025-01-20T08:56:34.736214Z","modified_on":"2025-01-21T08:56:34Z"}
|
||||
""";
|
||||
RecordEntity rec = mapper.readValue(json, RecordEntity.class);
|
||||
assertEquals(10, rec.getPriority());
|
||||
assertEquals("sip", rec.getComment());
|
||||
assertEquals(List.of("env:prod"), rec.getTags());
|
||||
assertEquals(5060, rec.getData().get("port"));
|
||||
assertEquals(java.time.Instant.parse("2025-01-20T08:56:34.736214Z"), rec.getCreatedOn());
|
||||
assertEquals(java.time.Instant.parse("2025-01-21T08:56:34Z"), rec.getModifiedOn());
|
||||
|
||||
String out = mapper.writeValueAsString(rec);
|
||||
assertTrue(out.contains("\"priority\":10"), out);
|
||||
assertTrue(out.contains("\"created_on\":\"2025-01-20T08:56:34.736214Z\""), out);
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,8 @@ import codes.thischwa.cf.model.RecordMultipleResponse;
|
||||
import codes.thischwa.cf.model.RecordSingleResponse;
|
||||
import codes.thischwa.cf.model.ResponseResultInfo;
|
||||
import codes.thischwa.cf.model.ResultInfo;
|
||||
import codes.thischwa.cf.model.ZoneEntity;
|
||||
import codes.thischwa.cf.model.ZoneMultipleResponse;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
@@ -130,4 +132,44 @@ class ResponseValidatorTest {
|
||||
assertDoesNotThrow(() -> validatorWithException.validate(mockSingleResponse, false));
|
||||
assertDoesNotThrow(() -> validatorWithoutException.validate(mockSingleResponse, false));
|
||||
}
|
||||
|
||||
private static ZoneMultipleResponse zoneResponse(int count) {
|
||||
ZoneMultipleResponse resp = new ZoneMultipleResponse();
|
||||
ResponseResultInfo info = new ResponseResultInfo();
|
||||
info.setSuccess(true);
|
||||
resp.setResponseResultInfo(info);
|
||||
List<ZoneEntity> zones = new ArrayList<>();
|
||||
for (int i = 0; i < count; i++) {
|
||||
zones.add(new ZoneEntity());
|
||||
}
|
||||
resp.setResult(zones);
|
||||
return resp;
|
||||
}
|
||||
|
||||
@Test
|
||||
void validateZoneResponseEmptyWithExceptionEnabled() {
|
||||
ZoneMultipleResponse resp = zoneResponse(0);
|
||||
resp.setResultInfo(new ResultInfo(0));
|
||||
assertThrows(CloudflareNotFoundException.class, () -> validatorWithException.validate(resp, true));
|
||||
assertDoesNotThrow(() -> validatorWithoutException.validate(resp, true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void validateZoneResponseMultipleWhenSingleExpected() {
|
||||
ZoneMultipleResponse resp = zoneResponse(2);
|
||||
resp.setResultInfo(new ResultInfo(2));
|
||||
CloudflareApiException exception = assertThrows(CloudflareApiException.class,
|
||||
() -> validatorWithoutException.validate(resp, true));
|
||||
assertTrue(exception.getMessage().contains("Unexpected result count: 2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void validateMultipleResponseWithoutResultInfoFallsBackToResultSize() {
|
||||
// no result_info -> count is derived from the result list
|
||||
assertThrows(CloudflareNotFoundException.class,
|
||||
() -> validatorWithException.validate(zoneResponse(0), false));
|
||||
assertThrows(CloudflareApiException.class,
|
||||
() -> validatorWithoutException.validate(zoneResponse(2), true));
|
||||
assertDoesNotThrow(() -> validatorWithException.validate(zoneResponse(1), true));
|
||||
}
|
||||
}
|
||||
@@ -59,7 +59,7 @@ class FluentApiTest {
|
||||
RecordEntity rec2 = RecordEntity.build("www.example.com", RecordType.A, 300, "1.2.3.5");
|
||||
List<RecordEntity> expectedRecords = List.of(rec1, rec2);
|
||||
|
||||
when(mockClient.recordList(eq(testZone), any(RecordType[].class)))
|
||||
when(mockClient.recordListByType(eq(testZone), any(RecordType[].class)))
|
||||
.thenReturn(expectedRecords);
|
||||
|
||||
ZoneOperations zoneOps = new ZoneOperationsImpl(mockClient, testZone);
|
||||
@@ -67,7 +67,7 @@ class FluentApiTest {
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(2, result.size());
|
||||
verify(mockClient, times(1)).recordList(eq(testZone), any(RecordType[].class));
|
||||
verify(mockClient, times(1)).recordListByType(eq(testZone), any(RecordType[].class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -75,7 +75,7 @@ class FluentApiTest {
|
||||
RecordEntity rec1 = RecordEntity.build("test.example.com", RecordType.A, 300, "1.2.3.4");
|
||||
List<RecordEntity> expectedRecords = List.of(rec1);
|
||||
|
||||
when(mockClient.recordList(eq(testZone), any(RecordType[].class)))
|
||||
when(mockClient.recordListByType(eq(testZone), any(RecordType[].class)))
|
||||
.thenReturn(expectedRecords);
|
||||
|
||||
ZoneOperations zoneOps = new ZoneOperationsImpl(mockClient, testZone);
|
||||
@@ -83,7 +83,7 @@ class FluentApiTest {
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(1, result.size());
|
||||
verify(mockClient, times(1)).recordList(eq(testZone), any(RecordType[].class));
|
||||
verify(mockClient, times(1)).recordListByType(eq(testZone), any(RecordType[].class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -91,7 +91,7 @@ class FluentApiTest {
|
||||
RecordEntity rec1 = RecordEntity.build("test.example.com", RecordType.A, 300, "1.2.3.4");
|
||||
List<RecordEntity> expectedRecords = List.of(rec1);
|
||||
|
||||
when(mockClient.recordList(eq(testZone), eq(TEST_SLD), any()))
|
||||
when(mockClient.recordListBySubdomain(eq(testZone), eq(TEST_SLD), any()))
|
||||
.thenReturn(expectedRecords);
|
||||
|
||||
RecordOperations recordOps = new RecordOperationsImpl(mockClient, testZone, TEST_SLD, null);
|
||||
@@ -100,7 +100,7 @@ class FluentApiTest {
|
||||
assertNotNull(result);
|
||||
assertEquals(1, result.size());
|
||||
assertEquals("1.2.3.4", result.get(0).getContent());
|
||||
verify(mockClient, times(1)).recordList(eq(testZone), eq(TEST_SLD), any());
|
||||
verify(mockClient, times(1)).recordListBySubdomain(eq(testZone), eq(TEST_SLD), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -109,7 +109,7 @@ class FluentApiTest {
|
||||
List<RecordEntity> expectedRecords = List.of(rec1);
|
||||
|
||||
RecordType[] types = {RecordType.A};
|
||||
when(mockClient.recordList(eq(testZone), eq(TEST_SLD), eq(types)))
|
||||
when(mockClient.recordListBySubdomain(eq(testZone), eq(TEST_SLD), eq(types)))
|
||||
.thenReturn(expectedRecords);
|
||||
|
||||
RecordOperations recordOps = new RecordOperationsImpl(mockClient, testZone, TEST_SLD, types);
|
||||
@@ -117,7 +117,7 @@ class FluentApiTest {
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(1, result.size());
|
||||
verify(mockClient, times(1)).recordList(eq(testZone), eq(TEST_SLD), eq(types));
|
||||
verify(mockClient, times(1)).recordListBySubdomain(eq(testZone), eq(TEST_SLD), eq(types));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -125,7 +125,7 @@ class FluentApiTest {
|
||||
RecordEntity createdRecord = RecordEntity.build("test.example.com", RecordType.A, 300, "1.2.3.4");
|
||||
createdRecord.setId(TEST_RECORD_ID);
|
||||
|
||||
when(mockClient.recordCreateSld(eq(testZone), eq(TEST_SLD), eq(300), eq(RecordType.A), eq("1.2.3.4")))
|
||||
when(mockClient.recordCreateSubdomain(eq(testZone), eq(TEST_SLD), eq(300), eq(RecordType.A), eq("1.2.3.4")))
|
||||
.thenReturn(createdRecord);
|
||||
|
||||
RecordOperations recordOps = new RecordOperationsImpl(mockClient, testZone, TEST_SLD, null);
|
||||
@@ -134,7 +134,7 @@ class FluentApiTest {
|
||||
assertNotNull(result);
|
||||
assertEquals(TEST_RECORD_ID, result.getId());
|
||||
assertEquals("1.2.3.4", result.getContent());
|
||||
verify(mockClient, times(1)).recordCreateSld(eq(testZone), eq(TEST_SLD), eq(300), eq(RecordType.A), eq("1.2.3.4"));
|
||||
verify(mockClient, times(1)).recordCreateSubdomain(eq(testZone), eq(TEST_SLD), eq(300), eq(RecordType.A), eq("1.2.3.4"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -145,7 +145,7 @@ class FluentApiTest {
|
||||
RecordEntity updatedRecord = RecordEntity.build("test.example.com", RecordType.A, 300, "1.2.3.5");
|
||||
updatedRecord.setId(TEST_RECORD_ID);
|
||||
|
||||
when(mockClient.recordList(eq(testZone), eq(TEST_SLD), any()))
|
||||
when(mockClient.recordListBySubdomain(eq(testZone), eq(TEST_SLD), any()))
|
||||
.thenReturn(List.of(existingRecord));
|
||||
when(mockClient.recordUpdate(eq(testZone), any(RecordEntity.class)))
|
||||
.thenReturn(updatedRecord);
|
||||
@@ -155,13 +155,17 @@ class FluentApiTest {
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals("1.2.3.5", result.getContent());
|
||||
verify(mockClient, times(1)).recordList(eq(testZone), eq(TEST_SLD), any());
|
||||
verify(mockClient, times(1)).recordUpdate(eq(testZone), any(RecordEntity.class));
|
||||
verify(mockClient, times(1)).recordListBySubdomain(eq(testZone), eq(TEST_SLD), any());
|
||||
// only ID and new content are sent (partial update)
|
||||
verify(mockClient, times(1)).recordUpdate(eq(testZone), argThat(rec ->
|
||||
TEST_RECORD_ID.equals(rec.getId()) && "1.2.3.5".equals(rec.getContent())
|
||||
&& rec.getName() == null && rec.getTtl() == null));
|
||||
assertEquals("1.2.3.4", existingRecord.getContent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRecordOperations_Update_NoRecordsFound() throws CloudflareApiException {
|
||||
when(mockClient.recordList(eq(testZone), eq(TEST_SLD), any()))
|
||||
when(mockClient.recordListBySubdomain(eq(testZone), eq(TEST_SLD), any()))
|
||||
.thenReturn(List.of());
|
||||
|
||||
RecordOperations recordOps = new RecordOperationsImpl(mockClient, testZone, TEST_SLD, null);
|
||||
@@ -171,7 +175,7 @@ class FluentApiTest {
|
||||
});
|
||||
|
||||
assertTrue(exception.getMessage().contains("No recs found"));
|
||||
verify(mockClient, times(1)).recordList(eq(testZone), eq(TEST_SLD), any());
|
||||
verify(mockClient, times(1)).recordListBySubdomain(eq(testZone), eq(TEST_SLD), any());
|
||||
verify(mockClient, never()).recordUpdate(any(), any());
|
||||
}
|
||||
|
||||
@@ -180,7 +184,7 @@ class FluentApiTest {
|
||||
RecordEntity rec1 = RecordEntity.build("test.example.com", RecordType.A, 300, "1.2.3.4");
|
||||
RecordEntity rec2 = RecordEntity.build("test.example.com", RecordType.AAAA, 300, "::1");
|
||||
|
||||
when(mockClient.recordList(eq(testZone), eq(TEST_SLD), any()))
|
||||
when(mockClient.recordListBySubdomain(eq(testZone), eq(TEST_SLD), any()))
|
||||
.thenReturn(List.of(rec1, rec2));
|
||||
|
||||
RecordOperations recordOps = new RecordOperationsImpl(mockClient, testZone, TEST_SLD, null);
|
||||
@@ -190,7 +194,7 @@ class FluentApiTest {
|
||||
});
|
||||
|
||||
assertTrue(exception.getMessage().contains("Multiple recs found"));
|
||||
verify(mockClient, times(1)).recordList(eq(testZone), eq(TEST_SLD), any());
|
||||
verify(mockClient, times(1)).recordListBySubdomain(eq(testZone), eq(TEST_SLD), any());
|
||||
verify(mockClient, never()).recordUpdate(any(), any());
|
||||
}
|
||||
|
||||
@@ -220,7 +224,7 @@ class FluentApiTest {
|
||||
RecordEntity createdRecord = RecordEntity.build("test.example.com", RecordType.A, 300, "1.2.3.4");
|
||||
createdRecord.setId(TEST_RECORD_ID);
|
||||
|
||||
when(mockClient.recordCreateSld(eq(testZone), eq(TEST_SLD), eq(300), eq(RecordType.A), eq("1.2.3.4")))
|
||||
when(mockClient.recordCreateSubdomain(eq(testZone), eq(TEST_SLD), eq(300), eq(RecordType.A), eq("1.2.3.4")))
|
||||
.thenReturn(createdRecord);
|
||||
|
||||
ZoneOperations zoneOps = new ZoneOperationsImpl(mockClient, testZone);
|
||||
|
||||
@@ -1,43 +1,80 @@
|
||||
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 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
|
||||
void testBuildPath() {
|
||||
String result = PagingRequest.defaultPaging().addQueryString("/zones");
|
||||
assertEquals("/zones?page=1&per_page=1000", result);
|
||||
}
|
||||
@Test
|
||||
void testBuildPathWithExistingQuery() {
|
||||
String result = PagingRequest.forRecords(10, 100).addQueryString("/zones?foo=bar");
|
||||
assertEquals("/zones?foo=bar&page=10&per_page=100", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testBuildPathAdditional() {
|
||||
String result = new PagingRequest( 10, 100).addQueryString("/zones?foo=bar");
|
||||
assertEquals("/zones?foo=bar&page=10&per_page=100", result);
|
||||
}
|
||||
@Test
|
||||
void testPagingRequestBoundaries() {
|
||||
assertDoesNotThrow(() -> PagingRequest.forRecords(1, 1));
|
||||
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
|
||||
void testGetPagingParams() {
|
||||
PagingRequest request = PagingRequest.of(2, 50);
|
||||
java.util.Map<String, String> params = request.getPagingParams();
|
||||
assertEquals("2", params.get("page"));
|
||||
assertEquals("50", params.get("perPage"));
|
||||
}
|
||||
@Test
|
||||
void testZonePageSizeBoundaries() {
|
||||
assertDoesNotThrow(() -> PagingRequest.forZones(1, PagingRequest.MIN_ZONES_PER_PAGE));
|
||||
assertDoesNotThrow(() -> PagingRequest.forZones(1, PagingRequest.MAX_ZONES_PER_PAGE));
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> PagingRequest.forZones(1, PagingRequest.MIN_ZONES_PER_PAGE - 1));
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> PagingRequest.forZones(1, PagingRequest.MAX_ZONES_PER_PAGE + 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testLombokMethods() {
|
||||
PagingRequest req1 = PagingRequest.of(1, 10);
|
||||
PagingRequest req2 = PagingRequest.of(1, 10);
|
||||
assertEquals(req1, req2);
|
||||
assertEquals(req1.hashCode(), req2.hashCode());
|
||||
assertTrue(req1.toString().contains("page=1"));
|
||||
@Test
|
||||
void testNextAndWithPageReturnNewRequests() {
|
||||
PagingRequest request = PagingRequest.forRecords(2, 50);
|
||||
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -41,19 +41,19 @@ public class RecordEntityTest {
|
||||
@Test
|
||||
void testGetSld() {
|
||||
RecordEntity rec = new RecordEntity();
|
||||
assertNull(rec.getSld());
|
||||
assertNull(rec.getSubdomain());
|
||||
|
||||
rec.setName("sub.example.com");
|
||||
assertEquals("sub", rec.getSld());
|
||||
assertEquals("sub", rec.getSubdomain());
|
||||
|
||||
rec.setName("example.com");
|
||||
assertEquals("example", rec.getSld());
|
||||
assertEquals("example", rec.getSubdomain());
|
||||
|
||||
rec.setName("host");
|
||||
assertEquals("host", rec.getSld());
|
||||
assertEquals("host", rec.getSubdomain());
|
||||
|
||||
rec.setName(".dotstart");
|
||||
assertEquals(".dotstart", rec.getSld());
|
||||
assertEquals(".dotstart", rec.getSubdomain());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -61,10 +61,47 @@ public class RecordEntityTest {
|
||||
RecordEntity rec = new RecordEntity();
|
||||
rec.setName("sub.example.com");
|
||||
rec.setZoneName("example.com");
|
||||
assertEquals("sub", rec.getSld());
|
||||
assertEquals("sub", rec.getSubdomain());
|
||||
|
||||
rec.setName("my.sub.example.com");
|
||||
rec.setZoneName("example.com");
|
||||
assertEquals("my.sub", rec.getSld());
|
||||
assertEquals("my.sub", rec.getSubdomain());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetSldApexWithZoneName() {
|
||||
RecordEntity rec = new RecordEntity();
|
||||
rec.setName("example.com");
|
||||
rec.setZoneName("example.com");
|
||||
assertEquals("@", rec.getSubdomain());
|
||||
|
||||
rec.setName("Example.COM");
|
||||
assertEquals("@", rec.getSubdomain());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetSldZoneNameIsNoLabelSuffix() {
|
||||
// "notexample.com" ends with "example.com", but is not part of the zone
|
||||
RecordEntity rec = new RecordEntity();
|
||||
rec.setName("notexample.com");
|
||||
rec.setZoneName("example.com");
|
||||
assertEquals("notexample", rec.getSubdomain());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetSldCaseInsensitive() {
|
||||
RecordEntity rec = new RecordEntity();
|
||||
rec.setName("WWW.Example.com");
|
||||
rec.setZoneName("example.com");
|
||||
assertEquals("WWW", rec.getSubdomain());
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("removal")
|
||||
void testDeprecatedGetSldDelegatesToGetSubdomain() {
|
||||
RecordEntity rec = new RecordEntity();
|
||||
rec.setName("my.sub.example.com");
|
||||
rec.setZoneName("example.com");
|
||||
assertEquals(rec.getSubdomain(), rec.getSld());
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@ package codes.thischwa.cf.model;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.Instant;
|
||||
import java.util.Set;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
@@ -18,7 +18,7 @@ public class ZoneEntityTest {
|
||||
Set<String> ns = Set.of("ns1.cloudflare.com", "ns2.cloudflare.com");
|
||||
zone.setNameServers(ns);
|
||||
zone.setOriginalNameServers(ns);
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
Instant now = Instant.now();
|
||||
zone.setCreatedOn(now);
|
||||
zone.setModifiedOn(now);
|
||||
zone.setActivatedOn(now);
|
||||
|
||||
Reference in new issue
Block a user