16 Commits
Author SHA1 Message Date
gitea-actions-bot dc1a1fde86 ci: update test report [skip ci] 2026-11-04 16:10:22 +00:00
thischwa 4603753e7a Merge remote-tracking branch 'origin/feature/ki-review' into feature/ki-review
Build and Analyse / build-and-analyse (push) Failing after 1m27s
2026-11-04 17:08:51 +01:00
thischwaandClaude Opus 5.5 09eabb0d59 fix: stable and consistent paging of DNS records (#2)
- list DNS records with order=name&direction=asc, without an order
  Cloudflare's pages can overlap and miss records
- de-duplicate fetched entries by ID, fetch the pages again (up to 3
  times) if fewer entries than total_count were fetched, otherwise log
  a warning; debug log per fetched page
- testPaging: unique record names for an unambiguous order
- testDns: wait for the unfiltered record list, which can lag behind
  directly after creating records

refs #2

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 14:43:22 +01:00
gitea-actions-bot 4ca2c96c4b ci: update test report [skip ci] 2026-11-04 11:51:19 +00:00
thischwa 6eb6c2b778 Merge remote-tracking branch 'origin/feature/ki-review' into feature/ki-review
Build and Analyse / build-and-analyse (push) Failing after 1m21s
2026-11-04 12:49:04 +01:00
thischwaandClaude Opus 5.5 c7f27f2ac0 security: encode request parameters, enforce HTTPS, add timeouts (#2)
- query values (zone names, subdomains) are URL-encoded, zone and
  record IDs must be alphanumeric: prevents query parameter injection
  and path traversal
- zone names and subdomains with whitespace, control characters or
  \ ? # & ; | < > " ' ` are rejected with an IllegalArgumentException
- withBaseUrl only accepts HTTPS (plain HTTP only for loopback hosts),
  no query/fragment, trailing slash is removed
- connect and response timeouts (defaults 10 s / 30 s), configurable
  via withConnectTimeout / withResponseTimeout; values below 1 ms or
  overflowing milliseconds are rejected
- null credentials throw an IllegalArgumentException, build() without
  authentication an IllegalStateException
- tests, README and changelog updated

refs #2

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 12:48:54 +01:00
gitea-actions-bot d7df7cde9a ci: update test report [skip ci] 2026-11-03 17:27:38 +00:00
gitea-actions-bot d6b1333056 ci: update test report [skip ci] 2026-11-03 17:25:33 +00:00
thischwa f6c0544d9a Merge remote-tracking branch 'origin/feature/ki-review' into feature/ki-review
Build and Analyse / build-and-analyse (push) Failing after 1m17s
2026-11-03 18:24:06 +01:00
thischwa 0e6f4bb9c0 ci: add API_TOKEN environment variable to enable live tests in build-and-analyse workflow 2026-11-03 18:23:53 +01:00
gitea-actions-bot 88601efa1b ci: update test report [skip ci] 2026-11-03 17:19:07 +00:00
gitea-actions-bot 9e7118bcf8 ci: update test report [skip ci] 2026-11-03 17:04:41 +00:00
thischwaandClaude Opus 5.5 c3a5c5f3e5 test: cover AI code review changes in CfClientTest (#2)
Build and Analyse / build-and-analyse (push) Successful in 30s
- live tests for API error details (status code, Cloudflare errors),
  404 on deleting an unknown record, unknown zones with and without
  emptyResultThrowsException, closing the client, multi-level
  subdomains and the zone apex, server- and client-side type filter,
  record attributes (priority, comment, SRV data) and Instant
  timestamps
- testPaging fetches all pages with a small page size, therefore
  CfDnsClient got a package-private constructor with a custom page size
- testDns checks that recordUpdate doesn't modify the given record
- SRV records: the priority is part of the data, fixed javadoc,
  README and changelog accordingly

refs #2

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 18:02:16 +01:00
gitea-actions-bot 20fabf9667 ci: update test report [skip ci] 2026-11-03 16:34:48 +00:00
thischwaandClaude Opus 5.5 b6821b0076 ci: run build workflow for feature/** branches
Build and Analyse / build-and-analyse (push) Successful in 27s
"feature*" doesn't match branch names containing a slash like
feature/ki-review, so the workflow wasn't triggered.

refs #2

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 17:33:33 +01:00
thischwaandClaude Opus 5.5 732f92ee78 AI code review: fix bugs, rename sld to subdomain, improve usability (#2)
- bug fixes: API errors are no longer wrapped into "Unexpected error!",
  zoneGet no longer crashes on unknown zones, getSubdomain handles apex
  and multi-level names, batch operations send the full record name,
  list methods fetch all pages, recordDelete handles empty results
- rename "sld" to "subdomain": getSubdomain(), recordCreateSubdomain(),
  old methods deprecated; "@" (CfDnsClient.APEX) addresses the apex
- one shared HTTP client with connection pooling, CfDnsClient
  implements AutoCloseable
- CloudflareApiException provides HTTP status code and Cloudflare
  errors, HTTP 404 throws CloudflareNotFoundException
- RecordEntity supports priority, data, comment and tags
- recordCreate/recordUpdate send only writable attributes and don't
  modify the given record
- breaking: recordList overloads replaced by recordListBySubdomain and
  recordListByType, timestamps are java.time.Instant
- single record type is filtered server-side (?type=)
- tests, README and changelog updated

refs #2

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 15:44:25 +01:00
18 changed files with 252 additions and 581 deletions

No files matched your search

+2 -19
View File
@@ -4,9 +4,6 @@ inputs:
token: token:
description: Gitea token with write access to the repository. description: Gitea token with write access to the repository.
required: true required: true
build-outcome:
description: Outcome of the build and test step.
required: true
runs: runs:
using: composite using: composite
@@ -20,7 +17,6 @@ runs:
run: | run: |
mkdir -p junit-short mkdir -p junit-short
shopt -s globstar nullglob shopt -s globstar nullglob
rm -f junit-short/*.xml
for f in **/target/*-reports/TEST-*.xml; do for f in **/target/*-reports/TEST-*.xml; do
base="$(basename "$f")" base="$(basename "$f")"
short="${base#TEST-}" short="${base#TEST-}"
@@ -29,12 +25,10 @@ runs:
- name: Generate Markdown Test Report - name: Generate Markdown Test Report
shell: bash shell: bash
env:
BUILD_OUTCOME: ${{ inputs.build-outcome }}
run: | run: |
mkdir -p reports mkdir -p reports
python3 - <<'EOF' python3 - <<'EOF'
import glob, os, xml.etree.ElementTree as ET import glob, xml.etree.ElementTree as ET
from datetime import datetime, timezone from datetime import datetime, timezone
generated_at = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC") generated_at = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")
@@ -63,17 +57,7 @@ runs:
test_rows.append(f"| {status} | {name} | {tests} | {passed} | {failures + errors} | {skipped} |") test_rows.append(f"| {status} | {name} | {tests} | {passed} | {failures + errors} | {skipped} |")
total_passed = total_tests - total_failures - total_errors - total_skipped total_passed = total_tests - total_failures - total_errors - total_skipped
build_outcome = os.environ.get("BUILD_OUTCOME", "unknown") overall = "✅ All tests passed" if (total_failures + total_errors) == 0 else "❌ Some tests failed"
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 --- # --- JaCoCo ---
def counter(el, type_): def counter(el, type_):
@@ -103,7 +87,6 @@ runs:
"# Test Report\n\n" "# Test Report\n\n"
f"_Generated on {generated_at}_\n\n" f"_Generated on {generated_at}_\n\n"
f"**{overall}**\n\n" f"**{overall}**\n\n"
f"Build outcome: **{build_outcome}**\n\n"
"## Test Results\n\n" "## Test Results\n\n"
"| | Tests | Passed | Failed | Skipped |\n" "| | Tests | Passed | Failed | Skipped |\n"
"|---|---|---|---|---|\n" "|---|---|---|---|---|\n"
-57
View File
@@ -1,57 +0,0 @@
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()
+1 -4
View File
@@ -7,7 +7,6 @@ on:
- 'feature/**' - 'feature/**'
pull_request: pull_request:
types: [ opened, synchronize, reopened ] types: [ opened, synchronize, reopened ]
workflow_dispatch:
defaults: defaults:
run: run:
@@ -26,15 +25,13 @@ jobs:
uses: ./.gitea/actions/setup-java-maven uses: ./.gitea/actions/setup-java-maven
- name: Build and test - name: Build and test
id: build
env: env:
# required by the live tests (CfClientTest, CfClientPenTest), they are skipped if not set # required by the live tests (CfClientTest, CfClientPenTest), they are skipped if not set
API_TOKEN: ${{ secrets.API_TOKEN }} API_TOKEN: ${{ secrets.API_TOKEN }}
run: mvn -B clean verify run: mvn -B verify
- name: Publish Test Report - name: Publish Test Report
uses: ./.gitea/actions/publish-report uses: ./.gitea/actions/publish-report
if: ${{ always() }} if: ${{ always() }}
with: with:
token: ${{ secrets.GITHUB_TOKEN }} token: ${{ secrets.GITHUB_TOKEN }}
build-outcome: ${{ steps.build.outcome }}
-1
View File
@@ -12,4 +12,3 @@
cf.yml cf.yml
/docs/apidocs/javadoc.sh /docs/apidocs/javadoc.sh
/.claude/settings.local.json /.claude/settings.local.json
/.junie/
+5 -18
View File
@@ -2,8 +2,6 @@
[![Build and Analyse](https://git.mein-gateway.de/thischwa/CloudflareDNS-java/actions/workflows/build-and-analyse.yml/badge.svg?branch=develop)](https://git.mein-gateway.de/thischwa/CloudflareDNS-java/actions?workflow=build-and-analyse.yml) [![Build and Analyse](https://git.mein-gateway.de/thischwa/CloudflareDNS-java/actions/workflows/build-and-analyse.yml/badge.svg?branch=develop)](https://git.mein-gateway.de/thischwa/CloudflareDNS-java/actions?workflow=build-and-analyse.yml)
[![release](https://img.shields.io/maven-metadata/v?metadataUrl=https%3A%2F%2Fgit.mein-gateway.de%2Fapi%2Fpackages%2Fthischwa%2Fmaven%2Fcodes%2Fthischwa%2Fcloudflaredns%2Fmaven-metadata.xml)](https://git.mein-gateway.de/thischwa/-/packages/maven/codes.thischwa:cloudflaredns/)
[Test report](reports/test.md) [Test report](reports/test.md)
## Preface ## Preface
@@ -68,7 +66,7 @@ CfDnsClient cfDnsClient = new CfDnsClientBuilder()
```java ```java
CfDnsClient cfDnsClient = new CfDnsClientBuilder() CfDnsClient cfDnsClient = new CfDnsClientBuilder()
.withApiTokenAuth("your-api-token") .withApiTokenAuth("your-api-token")
.withBaseUrl("https://api.cloudflare.com/client/v4") // HTTPS required; .withBaseUrl("https://custom-api.example.com/client/v4") // must use HTTPS
.withConnectTimeout(Duration.ofSeconds(5)) // default: 10 s .withConnectTimeout(Duration.ofSeconds(5)) // default: 10 s
.withResponseTimeout(Duration.ofSeconds(15)) // default: 30 s .withResponseTimeout(Duration.ofSeconds(15)) // default: 30 s
.withEmptyResultThrowsException(true) // default: false .withEmptyResultThrowsException(true) // default: false
@@ -97,18 +95,12 @@ List<ZoneEntity> zones = cfDnsClient.zoneList();
zones.forEach(zone -> System.out.println("Zone: " + zone.getName())); zones.forEach(zone -> System.out.println("Zone: " + zone.getName()));
``` ```
Without a `PagingRequest`, `zoneList()` fetches zones in pages of 50, requesting further pages as needed. By default, up to 1000 zones are fetched in a single request. Use a `PagingRequest` to control paging:
Use a `PagingRequest` to retrieve a specific page:
```java ```java
List<ZoneEntity> zones = cfDnsClient.zoneList(PagingRequest.forZones(1, 50)); // page 1, 50 zones per page List<ZoneEntity> zones = cfDnsClient.zoneList(PagingRequest.of(1, 50)); // page 1, 50 zones per page
``` ```
Page numbers start at 1. `PagingRequest` is immutable; use `forRecords(page, perPage)` for DNS records and
`forZones(page, perPage)` for zones. Cloudflare accepts page sizes from 5 to 50 for zones and from
1 to 5,000,000 for DNS records. `PagingRequest.defaultPaging()` requests page 1 with 50 items; it
does not fetch additional pages. Use `next()` or `withPage(page)` to create another page request.
--- ---
### `zoneGet` ### `zoneGet`
@@ -168,11 +160,10 @@ If exactly one record type is given, the filtering is done by Cloudflare, otherw
List<RecordEntity> allZoneRecords = cfDnsClient.recordList(zone); List<RecordEntity> allZoneRecords = cfDnsClient.recordList(zone);
// Get the records of a zone page by page (page 2, 100 records per page) // Get the records of a zone page by page (page 2, 100 records per page)
List<RecordEntity> pagedRecords = cfDnsClient.recordList(zone, PagingRequest.forRecords(2, 100)); List<RecordEntity> pagedRecords = cfDnsClient.recordList(zone, PagingRequest.of(2, 100));
``` ```
Without a `PagingRequest`, all pages are fetched using 1,000 records per page and combined into one result. Without a `PagingRequest`, all pages are fetched and the complete result is returned.
This large page size can consume substantial memory. If paging remains inconsistent after three attempts, the client logs a warning and may return an incomplete list. Use a smaller `PagingRequest` to retrieve one page at a time; further pages must be requested explicitly.
With a `PagingRequest`, exactly the requested page is returned. With a `PagingRequest`, exactly the requested page is returned.
`RecordEntity#getSubdomain()` returns the record name relative to its zone, e.g. `my.sub` for `RecordEntity#getSubdomain()` returns the record name relative to its zone, e.g. `my.sub` for
@@ -282,8 +273,6 @@ cfDnsClient.recordDeleteTypeIfExists(zone, "api", RecordType.A, RecordType.AAAA)
System.out.println("Deletion attempt completed."); System.out.println("Deletion attempt completed.");
``` ```
If no record types are specified, records of all types for the subdomain are selected. Each record deletion is attempted independently: a `CloudflareApiException` from one deletion is logged and later records are still processed. No per-record result is returned, so a normal return does not guarantee that every selected record was deleted. Errors while retrieving the records are still reported; no matching records are treated as a no-op.
### Batch Operations ### Batch Operations
Process multiple DNS record operations (POST, PUT, PATCH, DELETE) in a single batch request. Process multiple DNS record operations (POST, PUT, PATCH, DELETE) in a single batch request.
@@ -436,8 +425,6 @@ client.zone("example.com")
.delete(RecordType.A, RecordType.AAAA); .delete(RecordType.A, RecordType.AAAA);
``` ```
The types passed to `delete` determine which record types are selected; a type filter passed to `getRecord` does not restrict deletion. Calling `delete()` without type arguments selects all record types for that subdomain. A `CloudflareApiException` from an individual deletion is logged and does not stop later attempts; no per-record result is returned.
### Advantages of Fluent API ### Advantages of Fluent API
- **More Readable**: The chain of method calls reads like natural language - **More Readable**: The chain of method calls reads like natural language
+8 -9
View File
@@ -1,15 +1,12 @@
# Changelog # Changelog
- 1.0.0: - 0.6.0-SNAPSHOT:
- **Breaking Changes**: - **Breaking Changes**:
- `recordList` overloads replaced, because they were ambiguous (e.g. `recordList(zone, null)` didn't compile): - `recordList` overloads replaced, because they were ambiguous (e.g. `recordList(zone, null)` didn't compile):
- `recordList(zone, String subdomain, RecordType... types)` and `recordList(zone, String subdomain)` → `recordListBySubdomain(zone, subdomain, types...)` - `recordList(zone, String subdomain, RecordType... types)` and `recordList(zone, String subdomain)` → `recordListBySubdomain(zone, subdomain, types...)`
- `recordList(zone, RecordType... types)` → `recordListByType(zone, types...)` - `recordList(zone, RecordType... types)` → `recordListByType(zone, types...)`
- `recordList(zone)` and `recordList(zone, PagingRequest)` remain unchanged - `recordList(zone)` and `recordList(zone, PagingRequest)` remain unchanged
- `CfDnsClient#recordCreateSld(...)` was removed; use `recordCreateSubdomain(...)` - `withBaseUrl` only accepts HTTPS URLs (plain HTTP only for loopback hosts like `localhost`), otherwise an `IllegalArgumentException` is thrown
- `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` - `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 - zone names and subdomains with whitespace, control characters or `\ ? # & ; | < > " ' `` ` `` are rejected with an `IllegalArgumentException`, zone and record IDs must be alphanumeric
- timestamps of `RecordEntity` and `ZoneEntity` (`createdOn`, `modifiedOn`, `activatedOn`) are of type `java.time.Instant` instead of `LocalDateTime`, so the time zone (UTC) isn't lost anymore - timestamps of `RecordEntity` and `ZoneEntity` (`createdOn`, `modifiedOn`, `activatedOn`) are of type `java.time.Instant` instead of `LocalDateTime`, so the time zone (UTC) isn't lost anymore
@@ -17,7 +14,6 @@
- unexpected runtime exceptions aren't wrapped into a `CloudflareApiException("Unexpected error!")` anymore - unexpected runtime exceptions aren't wrapped into a `CloudflareApiException("Unexpected error!")` anymore
- batch DELETE sends only the record IDs, batch PATCH sends all writable attributes which aren't `null` (before: only the content) - batch DELETE sends only the record IDs, batch PATCH sends all writable attributes which aren't `null` (before: only the content)
- security: query values (zone names, subdomains) are URL-encoded and IDs are validated, which prevents query parameter injection and path traversal - security: query values (zone names, subdomains) are URL-encoded and IDs are validated, which prevents query parameter injection and path traversal
- Unicode subdomains are converted to Punycode before requests are sent
- connect and response timeouts (defaults: 10 s / 30 s), configurable via `withConnectTimeout` / `withResponseTimeout` - connect and response timeouts (defaults: 10 s / 30 s), configurable via `withConnectTimeout` / `withResponseTimeout`
- `CfDnsClient` uses one shared HTTP client with connection pooling instead of a new one per request and implements `AutoCloseable`, call `close()` to release the connections - `CfDnsClient` uses one shared HTTP client with connection pooling instead of a new one per request and implements `AutoCloseable`, call `close()` to release the connections
- `CloudflareApiException` provides the HTTP status code (`getStatusCode()`) and the errors reported by Cloudflare (`getErrors()`) - `CloudflareApiException` provides the HTTP status code (`getStatusCode()`) and the errors reported by Cloudflare (`getErrors()`)
@@ -27,13 +23,16 @@
- filtering by exactly one record type is done by Cloudflare (`?type=`), unknown record types in responses don't break the client-side filter anymore - filtering by exactly one record type is done by Cloudflare (`?type=`), unknown record types in responses don't break the client-side filter anymore
- updated dependencies: jackson 3.2.4, httpclient5 5.6.4, lombok 1.18.48, logback-classic 1.6.6, mockito-junit-jupiter 5.24.0 - updated dependencies: jackson 3.2.4, httpclient5 5.6.4, lombok 1.18.48, logback-classic 1.6.6, mockito-junit-jupiter 5.24.0
- updated maven plugins: maven-compiler-plugin 3.16.0, maven-surefire-plugin 3.6.0, maven-jar-plugin 3.5.1 - updated maven plugins: maven-compiler-plugin 3.16.0, maven-surefire-plugin 3.6.0, maven-jar-plugin 3.5.1
- fixed "getRecord" wording in log and exception messages (e.g. "Invalid record type") - README: fixed fluent API examples, documented paging and further methods
- **Deprecation**: the misleading term "sld" was renamed to "subdomain": `RecordEntity#getSld()` is deprecated for removal; use `RecordEntity#getSubdomain()` - fixed "getRecord" wording in javadoc, log and exception messages (e.g. "Invalid record type")
- **Deprecation**: the misleading term "sld" was renamed to "subdomain", the old methods will be removed in a future release:
- `RecordEntity#getSld()` → `RecordEntity#getSubdomain()`
- `CfDnsClient#recordCreateSld(...)` → `CfDnsClient#recordCreateSubdomain(...)`
- `getSubdomain()` returns `"@"` for the zone apex; `CfDnsClient.APEX` can be used to address the zone apex - `getSubdomain()` returns `"@"` for the zone apex; `CfDnsClient.APEX` can be used to address the zone apex
- fixed: API errors were wrapped into a generic "Unexpected error!" exception - fixed: API errors were wrapped into a generic "Unexpected error!" exception
- fixed: `zoneGet` threw an `IndexOutOfBoundsException` for unknown zones, it now returns `null` or throws a `CloudflareNotFoundException` (depending on `emptyResultThrowsException`) - fixed: `zoneGet` threw an `IndexOutOfBoundsException` for unknown zones, it now returns `null` or throws a `CloudflareNotFoundException` (depending on `emptyResultThrowsException`)
- fixed: `getSubdomain()` failed for apex records and records with multi-level subdomains, batch operations now send the full record name - fixed: `getSubdomain()` failed for apex records and records with multi-level subdomains, batch operations now send the full record name
- fixed: `zoneList()` and `recordList(...)` without `PagingRequest` returned only the first page, now all pages are fetched; `recordList(zone, null)` uses a page size of 1,000 to limit response memory use - fixed: `zoneList()` and `recordList(...)` without `PagingRequest` returned only the first page, now all pages are fetched
- 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: DNS records are listed with a stable order (`order=name`), because without it Cloudflare's pages can overlap and miss records; fetched records are de-duplicated and inconsistent pages are fetched again
- fixed: `recordDelete` threw a `NullPointerException` for an empty result - fixed: `recordDelete` threw a `NullPointerException` for an empty result
- 0.5.0: - 0.5.0:
+1 -1
View File
@@ -4,7 +4,7 @@
<groupId>codes.thischwa</groupId> <groupId>codes.thischwa</groupId>
<artifactId>cloudflaredns</artifactId> <artifactId>cloudflaredns</artifactId>
<version>1.1.0-SNAPSHOT</version> <version>0.6.0-SNAPSHOT</version>
<name>CloudflareDNS-java</name> <name>CloudflareDNS-java</name>
<inceptionYear>2025</inceptionYear> <inceptionYear>2025</inceptionYear>
<packaging>jar</packaging> <packaging>jar</packaging>
+8 -16
View File
@@ -1,41 +1,33 @@
# Test Report # Test Report
_Generated on 2026-11-21 12:07:43 UTC_ _Generated on 2026-11-04 16:10:22 UTC_
**✅ All tests passed** **❌ Some tests failed**
Build outcome: **success**
## Test Results ## Test Results
| | Tests | Passed | Failed | Skipped | | | Tests | Passed | Failed | Skipped |
|---|---|---|---|---| |---|---|---|---|---|
| **Total** | 165 | 165 | 0 | 0 | | **Total** | 157 | 156 | 1 | 0 |
### Details ### Details
| Status | Suite | Tests | Passed | Failed | Skipped | | Status | Suite | Tests | Passed | Failed | Skipped |
|---|---|---|---|---|---| |---|---|---|---|---|---|
| ✅ | codes.thischwa.cf.CfBasicHttpClientErrorTest | 6 | 6 | 0 | 0 | | ✅ | codes.thischwa.cf.CfBasicHttpClientErrorTest | 7 | 7 | 0 | 0 |
| ✅ | codes.thischwa.cf.CfBasicHttpClientTest | 9 | 9 | 0 | 0 | | ✅ | codes.thischwa.cf.CfBasicHttpClientTest | 9 | 9 | 0 | 0 |
| ✅ | codes.thischwa.cf.CfClientIntegrationTest | 19 | 19 | 0 | 0 |
| ✅ | codes.thischwa.cf.CfClientPenTest | 4 | 4 | 0 | 0 | | ✅ | codes.thischwa.cf.CfClientPenTest | 4 | 4 | 0 | 0 |
| ❌ | codes.thischwa.cf.CfClientTest | 18 | 17 | 1 | 0 |
| ✅ | codes.thischwa.cf.CfDnsClientBuilderTest | 21 | 21 | 0 | 0 | | ✅ | codes.thischwa.cf.CfDnsClientBuilderTest | 21 | 21 | 0 | 0 |
| ✅ | codes.thischwa.cf.CfDnsClientMockTest | 42 | 42 | 0 | 0 | | ✅ | codes.thischwa.cf.CfDnsClientMockTest | 38 | 38 | 0 | 0 |
| ✅ | codes.thischwa.cf.CfRequestTest | 10 | 10 | 0 | 0 | | ✅ | codes.thischwa.cf.CfRequestTest | 10 | 10 | 0 | 0 |
| ✅ | codes.thischwa.cf.ObjectMapperTest | 4 | 4 | 0 | 0 | | ✅ | codes.thischwa.cf.ObjectMapperTest | 4 | 4 | 0 | 0 |
| ✅ | codes.thischwa.cf.ResponseValidatorTest | 11 | 11 | 0 | 0 | | ✅ | codes.thischwa.cf.ResponseValidatorTest | 11 | 11 | 0 | 0 |
| ✅ | codes.thischwa.cf.fluent.FluentApiTest | 15 | 15 | 0 | 0 | | ✅ | codes.thischwa.cf.fluent.FluentApiTest | 15 | 15 | 0 | 0 |
| ✅ | codes.thischwa.cf.model.BatchEntryTest | 2 | 2 | 0 | 0 | | ✅ | codes.thischwa.cf.model.BatchEntryTest | 2 | 2 | 0 | 0 |
| ✅ | codes.thischwa.cf.model.PagingRequestTest | 8 | 8 | 0 | 0 | | ✅ | codes.thischwa.cf.model.PagingRequestTest | 4 | 4 | 0 | 0 |
| ✅ | codes.thischwa.cf.model.RecordEntityTest | 10 | 10 | 0 | 0 | | ✅ | codes.thischwa.cf.model.RecordEntityTest | 10 | 10 | 0 | 0 |
| ✅ | codes.thischwa.cf.model.RecordTypeTest | 3 | 3 | 0 | 0 | | ✅ | codes.thischwa.cf.model.RecordTypeTest | 3 | 3 | 0 | 0 |
| ✅ | codes.thischwa.cf.model.ZoneEntityTest | 1 | 1 | 0 | 0 | | ✅ | codes.thischwa.cf.model.ZoneEntityTest | 1 | 1 | 0 | 0 |
## Coverage _No JaCoCo report found._
| Package | Line Coverage | Branch Coverage |
|---|---|---|
| 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) |
@@ -15,7 +15,6 @@ import codes.thischwa.cf.model.ResponseEntity;
import codes.thischwa.cf.model.ResultInfo; import codes.thischwa.cf.model.ResultInfo;
import codes.thischwa.cf.model.ZoneEntity; import codes.thischwa.cf.model.ZoneEntity;
import codes.thischwa.cf.model.ZoneMultipleResponse; import codes.thischwa.cf.model.ZoneMultipleResponse;
import java.net.IDN;
import java.time.Duration; import java.time.Duration;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
@@ -77,17 +76,22 @@ import org.jetbrains.annotations.Nullable;
* .build(); * .build();
* </code></pre> * </code></pre>
* *
* <p>Example specifying the Cloudflare API base URL: * <p>Example with custom base URL:
* <pre><code> * <pre><code>
* CfDnsClient cfDnsClient = new CfDnsClientBuilder() * CfDnsClient cfDnsClient = new CfDnsClientBuilder()
* .withApiTokenAuth("your-api-token") * .withApiTokenAuth("your-api-token")
* .withBaseUrl(CfDnsClientBuilder.DEFAULT_BASEURL) * .withBaseUrl("https://custom-api.example.com")
* .build(); * .build();
* </code></pre> * </code></pre>
*/ */
@Slf4j @Slf4j
public class CfDnsClient extends CfBasicHttpClient { public class CfDnsClient extends CfBasicHttpClient {
/**
* Page size used when fetching all zones. Cloudflare allows max. 50 zones per page.
*/
static final int ZONES_PER_PAGE = 50;
/** /**
* Page size used when fetching all DNS records. * Page size used when fetching all DNS records.
*/ */
@@ -177,17 +181,7 @@ public class CfDnsClient extends CfBasicHttpClient {
if (APEX.equals(subdomain)) { if (APEX.equals(subdomain)) {
return zone.getName(); return zone.getName();
} }
String asciiSubdomain = subdomain; return subdomain + "." + zone.getName();
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();
} }
/** /**
@@ -239,30 +233,19 @@ public class CfDnsClient extends CfBasicHttpClient {
* @throws CloudflareApiException If an error occurs during the API request or response handling. * @throws CloudflareApiException If an error occurs during the API request or response handling.
*/ */
public List<ZoneEntity> zoneList() throws CloudflareApiException { public List<ZoneEntity> zoneList() throws CloudflareApiException {
return getAllPages(CfRequest.ZONE_LIST.buildPath(), ZoneMultipleResponse.class, return getAllPages(CfRequest.ZONE_LIST.buildPath(), ZoneMultipleResponse.class, ZONES_PER_PAGE);
PagingRequest.DEFAULT_PAGE_SIZE);
} }
/** /**
* Retrieves a single page of DNS zones using the provided paging request parameters. * Retrieves a single page of DNS zones using the provided paging request parameters.
* Cloudflare requires a page size between 5 and 50 for this endpoint.
* *
* @param pagingRequest the pagination request object containing parameters for paging and * @param pagingRequest the pagination request object containing parameters for paging and
* filtering zone data * filtering zone data
* @return a list of {@code ZoneEntity} objects representing the DNS zones retrieved from the API * @return a list of {@code ZoneEntity} objects representing the DNS zones retrieved from the API
* @throws CloudflareApiException if there is an error during the API request or response * @throws CloudflareApiException if there is an error during the API request or response
* processing * processing
* @throws IllegalArgumentException if the page size is outside the range 5 to 50
*/ */
public List<ZoneEntity> zoneList(PagingRequest pagingRequest) throws CloudflareApiException { public List<ZoneEntity> zoneList(PagingRequest pagingRequest) throws CloudflareApiException {
Objects.requireNonNull(pagingRequest, "pagingRequest must not be null");
int perPage = pagingRequest.perPage();
if (perPage < PagingRequest.MIN_ZONES_PER_PAGE
|| perPage > PagingRequest.MAX_ZONES_PER_PAGE) {
throw new IllegalArgumentException("Zone page size must be between "
+ PagingRequest.MIN_ZONES_PER_PAGE + " and " + PagingRequest.MAX_ZONES_PER_PAGE
+ ", but was " + perPage);
}
String endpoint = pagingRequest.addQueryString(CfRequest.ZONE_LIST.buildPath()); String endpoint = pagingRequest.addQueryString(CfRequest.ZONE_LIST.buildPath());
ZoneMultipleResponse response = getRequest(endpoint, ZoneMultipleResponse.class); ZoneMultipleResponse response = getRequest(endpoint, ZoneMultipleResponse.class);
checkResponse(response); checkResponse(response);
@@ -307,8 +290,7 @@ public class CfDnsClient extends CfBasicHttpClient {
* *
* @param zone The zone entity containing information about the target zone. * @param zone The zone entity containing information about the target zone.
* @param pagingRequest The paging request containing parameters such as page size and number. * @param pagingRequest The paging request containing parameters such as page size and number.
* If {@code null}, all pages are fetched using an internal page size of 1,000. * If {@code null}, all pages are fetched.
* For a specific page, Cloudflare allows a page size between 1 and 5,000,000.
* @return A list of RecordEntity objects representing the DNS records of the specified zone. * @return A list of RecordEntity objects representing the DNS records of the specified zone.
* @throws CloudflareApiException If an error occurs during the API request or response processing. * @throws CloudflareApiException If an error occurs during the API request or response processing.
*/ */
@@ -329,17 +311,15 @@ public class CfDnsClient extends CfBasicHttpClient {
* Optionally, filters by one or more DNS record types. * Optionally, filters by one or more DNS record types.
* *
* @param zone The zone entity containing information about the domain zone. * @param zone The zone entity containing information about the domain zone.
* @param subdomain The subdomain relative to the zone (e.g. "www" for "www.example.com"); * @param subdomain The subdomain relative to the zone (e.g. "www" for "www.example.com"),
* Unicode subdomains are converted to Punycode. {@link #APEX} indicates the * or {@link #APEX} for the zone apex.
* zone apex.
* @param types Optional DNS record types to filter the results. If none are given, records of * @param types Optional DNS record types to filter the results. If none are given, records of
* all types are returned. * all types are returned.
* @return A list of {@code RecordEntity} objects representing the DNS records for the specified domain. * @return A list of {@code RecordEntity} objects representing the DNS records for the specified domain.
* @throws CloudflareNotFoundException if no records were found and 'emptyResultThrowsException' * @throws CloudflareNotFoundException if no records were found and 'emptyResultThrowsException'
* is enabled * is enabled
* @throws CloudflareApiException if an error occurs while interacting with the Cloudflare API * @throws CloudflareApiException if an error occurs while interacting with the Cloudflare API
* @throws IllegalArgumentException if the subdomain is blank, contains invalid characters or * @throws IllegalArgumentException if the subdomain is blank or contains invalid characters
* cannot be converted to Punycode
*/ */
public List<RecordEntity> recordListBySubdomain(ZoneEntity zone, String subdomain, public List<RecordEntity> recordListBySubdomain(ZoneEntity zone, String subdomain,
@Nullable RecordType... types) @Nullable RecordType... types)
@@ -374,9 +354,8 @@ public class CfDnsClient extends CfBasicHttpClient {
* Creates a new DNS record for a given subdomain within the specified zone. * Creates a new DNS record for a given subdomain within the specified zone.
* *
* @param zone The ZoneEntity representing the DNS zone where the record is to be created. * @param zone The ZoneEntity representing the DNS zone where the record is to be created.
* @param subdomain The subdomain relative to the zone (e.g. "api" for "api.example.com"); * @param subdomain The subdomain relative to the zone (e.g. "api" for "api.example.com"),
* Unicode subdomains are converted to Punycode. {@link #APEX} indicates the * or {@link #APEX} for the zone apex.
* zone apex.
* @param ttl The time-to-live (TTL) value for the DNS record in seconds. * @param ttl The time-to-live (TTL) value for the DNS record in seconds.
* @param type The RecordType specifying the type of the DNS record (e.g., A, AAAA, CNAME). * @param type The RecordType specifying the type of the DNS record (e.g., A, AAAA, CNAME).
* @param content The content of the DNS record (e.g., IP address for A/AAAA records, target * @param content The content of the DNS record (e.g., IP address for A/AAAA records, target
@@ -384,8 +363,7 @@ public class CfDnsClient extends CfBasicHttpClient {
* @return The created RecordEntity object containing details of the newly created DNS record. * @return The created RecordEntity object containing details of the newly created DNS record.
* @throws CloudflareApiException If an error occurs while communicating with the Cloudflare API * @throws CloudflareApiException If an error occurs while communicating with the Cloudflare API
* or creating the record. * or creating the record.
* @throws IllegalArgumentException if the subdomain is blank, contains invalid characters or * @throws IllegalArgumentException if the subdomain is blank or contains invalid characters
* cannot be converted to Punycode
*/ */
public RecordEntity recordCreateSubdomain(ZoneEntity zone, String subdomain, int ttl, RecordType type, public RecordEntity recordCreateSubdomain(ZoneEntity zone, String subdomain, int ttl, RecordType type,
String content) throws CloudflareApiException { String content) throws CloudflareApiException {
@@ -393,6 +371,26 @@ public class CfDnsClient extends CfBasicHttpClient {
return recordCreate(zone, fqdn, ttl, type, content); return recordCreate(zone, fqdn, ttl, type, content);
} }
/**
* Creates a new DNS record for a given subdomain within the specified zone.
*
* @param zone The ZoneEntity representing the DNS zone where the record is to be created.
* @param subdomain The subdomain relative to the zone.
* @param ttl The time-to-live (TTL) value for the DNS record in seconds.
* @param type The RecordType specifying the type of the DNS record.
* @param content The content of the DNS record.
* @return The created RecordEntity object containing details of the newly created DNS record.
* @throws CloudflareApiException If an error occurs while communicating with the Cloudflare API
* or creating the record.
* @deprecated The name was misleading, use
* {@link #recordCreateSubdomain(ZoneEntity, String, int, RecordType, String)} instead.
*/
@Deprecated(since = "0.6.0", forRemoval = true)
public RecordEntity recordCreateSld(ZoneEntity zone, String subdomain, int ttl, RecordType type,
String content) throws CloudflareApiException {
return recordCreateSubdomain(zone, subdomain, ttl, type, content);
}
/** /**
* Creates a DNS record in the specified DNS zone with the provided details. * Creates a DNS record in the specified DNS zone with the provided details.
* *
@@ -498,16 +496,13 @@ public class CfDnsClient extends CfBasicHttpClient {
} }
/** /**
* Attempts to delete DNS records of the specified types within a given zone. If no record types * Deletes DNS records of a specific type within a given zone if they exist. If no record of the
* are specified, all types for the subdomain are selected. If no matching record exists, this is * specified type exists, it logs this occurrence without throwing an exception.
* treated as a no-op. Deletions are attempted independently; an error deleting an individual
* record is logged and processing continues. No per-record result is returned, so a normal return
* does not guarantee that every selected record was deleted.
* *
* @param zone The DNS zone entity in which the record exists. * @param zone The DNS zone entity in which the record exists.
* @param subdomain The subdomain relative to the zone for which the records are being checked. * @param subdomain The subdomain relative to the zone for which the records are being checked.
* @param recordTypes The DNS record types to delete; if empty or {@code null}, all types are selected. * @param recordTypes The types of DNS records that should be deleted if they exist.
* @throws CloudflareApiException If an error occurs while retrieving the records to delete. * @throws CloudflareApiException If an error occurs during API communication.
* @throws IllegalArgumentException if the subdomain is blank or contains invalid characters * @throws IllegalArgumentException if the subdomain is blank or contains invalid characters
*/ */
public void recordDeleteTypeIfExists(ZoneEntity zone, String subdomain, RecordType... recordTypes) public void recordDeleteTypeIfExists(ZoneEntity zone, String subdomain, RecordType... recordTypes)
@@ -694,10 +689,9 @@ public class CfDnsClient extends CfBasicHttpClient {
Map<String, E> byId = new LinkedHashMap<>(); Map<String, E> byId = new LinkedHashMap<>();
List<E> withoutId = new ArrayList<>(); List<E> withoutId = new ArrayList<>();
int expectedCount = -1; int expectedCount = -1;
PagingRequest pagingRequest = new PagingRequest(1, perPage); int page = 1;
while (true) { while (true) {
int page = pagingRequest.page(); String pagedEndpoint = PagingRequest.of(page, perPage).addQueryString(endpoint);
String pagedEndpoint = pagingRequest.addQueryString(endpoint);
R resp = getRequest(pagedEndpoint, responseType); R resp = getRequest(pagedEndpoint, responseType);
checkResponse(resp); checkResponse(resp);
List<E> pageResult = resp.getResult(); List<E> pageResult = resp.getResult();
@@ -722,7 +716,7 @@ public class CfDnsClient extends CfBasicHttpClient {
all.addAll(withoutId); all.addAll(withoutId);
return new PagingResult<>(all, info == null || page == 1 ? -1 : expectedCount); return new PagingResult<>(all, info == null || page == 1 ? -1 : expectedCount);
} }
pagingRequest = pagingRequest.next(); page++;
} }
} }
@@ -3,6 +3,7 @@ package codes.thischwa.cf;
import java.net.URI; import java.net.URI;
import java.time.Duration; import java.time.Duration;
import java.util.Locale; import java.util.Locale;
import java.util.Set;
import org.apache.hc.core5.http.ClassicHttpRequest; import org.apache.hc.core5.http.ClassicHttpRequest;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@@ -28,6 +29,11 @@ public class CfDnsClientBuilder {
*/ */
public static final Duration DEFAULT_RESPONSE_TIMEOUT = Duration.ofSeconds(30); public static final Duration DEFAULT_RESPONSE_TIMEOUT = Duration.ofSeconds(30);
/**
* Hosts for which plain HTTP is allowed (e.g. for local tests).
*/
private static final Set<String> LOOPBACK_HOSTS = Set.of("localhost", "127.0.0.1", "[::1]", "::1");
private boolean emptyResultThrowsException; private boolean emptyResultThrowsException;
private CfAuth auth; private CfAuth auth;
private Duration connectTimeout = DEFAULT_CONNECT_TIMEOUT; private Duration connectTimeout = DEFAULT_CONNECT_TIMEOUT;
@@ -56,14 +62,13 @@ public class CfDnsClientBuilder {
* Sets the base URL to be used by the {@code CfDnsClient}. * Sets the base URL to be used by the {@code CfDnsClient}.
* This method allows configuring the base URL for API requests, overriding any default value. * This method allows configuring the base URL for API requests, overriding any default value.
* *
* <p>Only HTTPS URLs with a host are accepted. User information, query parameters and fragments * <p>To protect the credentials, the URL must use HTTPS. Plain HTTP is only allowed for
* are not permitted. Credentials are sent to the configured host, so only use trusted URLs. * loopback hosts (e.g. {@code localhost}) for testing purposes.
* *
* @param baseUrl the base URL to be used for API requests, {@code null} resets it to * @param baseUrl the base URL to be used for API requests, {@code null} resets it to
* {@link #DEFAULT_BASEURL} * {@link #DEFAULT_BASEURL}
* @return the current instance of {@code CfDnsClientBuilder}, enabling method chaining * @return the current instance of {@code CfDnsClientBuilder}, enabling method chaining
* @throws IllegalArgumentException if the URL is invalid, doesn't use HTTPS, has no host or * @throws IllegalArgumentException if the URL is invalid or doesn't use HTTPS
* contains user information, a query or a fragment
*/ */
public CfDnsClientBuilder withBaseUrl(@Nullable String baseUrl) { public CfDnsClientBuilder withBaseUrl(@Nullable String baseUrl) {
this.baseUrl = baseUrl == null ? null : validateBaseUrl(baseUrl); this.baseUrl = baseUrl == null ? null : validateBaseUrl(baseUrl);
@@ -119,6 +124,7 @@ public class CfDnsClientBuilder {
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Invalid base URL: " + baseUrl, e); throw new IllegalArgumentException("Invalid base URL: " + baseUrl, e);
} }
String scheme = uri.getScheme() == null ? "" : uri.getScheme().toLowerCase(Locale.ROOT);
String host = uri.getHost(); String host = uri.getHost();
if (host == null || host.isBlank()) { if (host == null || host.isBlank()) {
throw new IllegalArgumentException("Base URL must contain a host: " + baseUrl); throw new IllegalArgumentException("Base URL must contain a host: " + baseUrl);
@@ -126,11 +132,9 @@ public class CfDnsClientBuilder {
if (uri.getRawQuery() != null || uri.getRawFragment() != null) { if (uri.getRawQuery() != null || uri.getRawFragment() != null) {
throw new IllegalArgumentException("Base URL must not contain a query or fragment: " + baseUrl); throw new IllegalArgumentException("Base URL must not contain a query or fragment: " + baseUrl);
} }
if (uri.getRawUserInfo() != null) { boolean https = "https".equals(scheme);
throw new IllegalArgumentException("Base URL must not contain user information: " + baseUrl); boolean loopbackHttp = "http".equals(scheme) && LOOPBACK_HOSTS.contains(host.toLowerCase(Locale.ROOT));
} if (!https && !loopbackHttp) {
String scheme = uri.getScheme() == null ? "" : uri.getScheme().toLowerCase(Locale.ROOT);
if (!"https".equals(scheme)) {
throw new IllegalArgumentException("Base URL must use HTTPS: " + baseUrl); throw new IllegalArgumentException("Base URL must use HTTPS: " + baseUrl);
} }
String normalized = uri.toString(); String normalized = uri.toString();
@@ -40,15 +40,10 @@ public interface RecordOperations {
RecordEntity update(String newContent) throws CloudflareApiException; RecordEntity update(String newContent) throws CloudflareApiException;
/** /**
* Deletes DNS records of the specified types for the selected subdomain. The types passed here * Deletes DNS records of the specified types.
* determine which records are deleted, independently of any type filter used to select the
* subdomain. If no types are specified, records of all types for that subdomain are selected for
* deletion. A {@link CloudflareApiException} from an individual deletion is logged and does not
* stop later attempts. No per-record result is returned, so returning normally does not guarantee
* that all selected records were deleted.
* *
* @param types the DNS record types to delete * @param types the DNS record types to delete
* @throws CloudflareApiException if an error occurs while retrieving records to delete * @throws CloudflareApiException if an error occurs while deleting records
*/ */
void delete(RecordType... types) throws CloudflareApiException; void delete(RecordType... types) throws CloudflareApiException;
} }
@@ -21,10 +21,6 @@ public interface ZoneOperations {
/** /**
* Selects a record with specific types within the zone for further operations. * Selects a record with specific types within the zone for further operations.
* <p>The type filter does not restrict a subsequent {@link RecordOperations#delete(RecordType...)} call;
* that method uses its own type arguments, and calling it without arguments deletes all record types
* for the selected subdomain. A {@link CloudflareApiException} from an individual deletion is
* logged and does not stop later attempts; see {@link RecordOperations#delete(RecordType...)}.
* *
* @param subdomain the subdomain relative to the zone (e.g. "www"), or "@" for the zone apex * @param subdomain the subdomain relative to the zone (e.g. "www"), or "@" for the zone apex
* @param types optional DNS record types to filter by * @param types optional DNS record types to filter by
@@ -36,7 +32,7 @@ public interface ZoneOperations {
/** /**
* Lists all DNS records within the zone, optionally filtered by types. * Lists all DNS records within the zone, optionally filtered by types.
* *
* @param types optional DNS record types to filter by * @param types optional DNS record types to filter by
* @return a list of RecordEntity objects matching the criteria * @return a list of RecordEntity objects matching the criteria
* @throws CloudflareApiException if an error occurs while retrieving records * @throws CloudflareApiException if an error occurs while retrieving records
*/ */
@@ -1,118 +1,83 @@
package codes.thischwa.cf.model; package codes.thischwa.cf.model;
import java.util.Objects; import java.util.Map;
import lombok.Data;
/** /**
* Immutable pagination parameters for Cloudflare list endpoints. Page numbers start at 1. * Represents a request model for paginated data.
* *
* <p>Use {@link #forZones(int, int)} for zone requests and {@link #forRecords(int, int)} for DNS * <p>This class encapsulates the page number and the number of items per page for a paginated
* record requests. For example: * request, along with utility methods for constructing and retrieving pagination parameters.
* *
* <pre>{@code * <p>Key functionalities:
* List<RecordEntity> records = client.recordList(zone, PagingRequest.forRecords(1, 100)); *
* List<ZoneEntity> zones = client.zoneList(PagingRequest.forZones(1, 50)); * <ul>
* }</pre> * <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>
*/ */
public record PagingRequest(int page, int perPage) { @Data
public class PagingRequest {
/** 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;
/** /**
* Validates the page number and page size. * 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.
* @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
*/ */
public PagingRequest { private static final int DEFAULT_ALL_RECORDS_PAGE_SIZE = 1000;
if (page < 1) {
throw new IllegalArgumentException("page must be at least 1, but was " + page); private int page;
} private int perPage;
if (perPage < 1 || perPage > MAX_RECORDS_PER_PAGE) {
throw new IllegalArgumentException("perPage must be between 1 and " + MAX_RECORDS_PER_PAGE PagingRequest(int page, int perPage) {
+ ", but was " + perPage); this.page = page;
} this.perPage = perPage;
} }
/** /**
* Creates pagination parameters for a DNS record request. * Creates a new {@code PagingRequest} instance with the specified page number and items per page.
* *
* @param page the 1-based page number * @param page the page number to be requested
* @param perPage the number of records per page, from 1 to {@value #MAX_RECORDS_PER_PAGE} * @param perPage the number of items to be included per page
* @return the validated pagination request * @return a new {@code PagingRequest} instance with the provided parameters
* @throws IllegalArgumentException if either value is outside its allowed range
*/ */
public static PagingRequest forRecords(int page, int perPage) { public static PagingRequest of(int page, int perPage) {
return new PagingRequest(page, perPage); return new PagingRequest(page, perPage);
} }
/** /**
* Creates pagination parameters for a zone request. * 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.
* *
* @param page the 1-based page number * @return a default {@code PagingRequest} instance with predefined pagination parameters
* @param perPage the number of zones per page, from {@value #MIN_ZONES_PER_PAGE} to
* {@value #MAX_ZONES_PER_PAGE}
* @return the validated pagination request
* @throws IllegalArgumentException if either value is outside its allowed range
*/
public static PagingRequest forZones(int page, int perPage) {
if (perPage < MIN_ZONES_PER_PAGE || perPage > MAX_ZONES_PER_PAGE) {
throw new IllegalArgumentException("Zone page size must be between " + MIN_ZONES_PER_PAGE
+ " and " + MAX_ZONES_PER_PAGE + ", but was " + perPage);
}
return new PagingRequest(page, perPage);
}
/**
* Creates a request for page 1 with {@value #DEFAULT_PAGE_SIZE} items per page.
* This requests one page; it does not fetch additional pages.
*
* @return the default pagination request
*/ */
public static PagingRequest defaultPaging() { public static PagingRequest defaultPaging() {
return new PagingRequest(1, DEFAULT_PAGE_SIZE); return new PagingRequest(1, DEFAULT_ALL_RECORDS_PAGE_SIZE);
} }
/** /**
* Returns a request for the next page, retaining the current page size. * Retrieves the pagination parameters in a key-value map format.
* *
* @return the next page request * @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.
*/ */
public PagingRequest next() { public Map<String, String> getPagingParams() {
return new PagingRequest(page + 1, perPage); return Map.of("page", String.valueOf(page), "perPage", String.valueOf(perPage));
} }
/** /**
* Returns a copy of this request with the specified page number. * Appends a query string with pagination parameters (page and perPage) to the provided endpoint.
* *
* @param page the 1-based page number * @param endpoint the base URL or API endpoint to which the query string will be appended
* @return the updated pagination request * @return the complete URL with the appended query string for pagination
*/
public PagingRequest withPage(int page) {
return new PagingRequest(page, perPage);
}
/**
* Appends Cloudflare-compatible pagination parameters ({@code page} and {@code per_page}) to an
* endpoint.
*
* @param endpoint the base URL or API endpoint, optionally containing a query string
* @return the endpoint with pagination parameters appended
* @throws NullPointerException if {@code endpoint} is {@code null}
*/ */
public String addQueryString(String endpoint) { public String addQueryString(String endpoint) {
Objects.requireNonNull(endpoint, "endpoint must not be null"); return endpoint + queryString(endpoint.contains("?"));
return endpoint + (endpoint.contains("?") ? "&" : "?") }
+ "page=" + page + "&per_page=" + perPage;
private String queryString(boolean add) {
String qs = "page=" + page + "&per_page=" + perPage;
return add ? "&" + qs : "?" + qs;
} }
} }
@@ -35,6 +35,7 @@ class CfBasicHttpClientErrorTest {
private final AtomicInteger requestCount = new AtomicInteger(); private final AtomicInteger requestCount = new AtomicInteger();
private volatile int status; private volatile int status;
private volatile String body; private volatile String body;
private volatile String lastPath;
private volatile long delayMillis; private volatile long delayMillis;
@BeforeEach @BeforeEach
@@ -42,6 +43,7 @@ class CfBasicHttpClientErrorTest {
server = HttpServer.create(new InetSocketAddress("localhost", 0), 0); server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
server.createContext("/", exchange -> { server.createContext("/", exchange -> {
requestCount.incrementAndGet(); requestCount.incrementAndGet();
lastPath = exchange.getRequestURI().getRawPath();
if (delayMillis > 0) { if (delayMillis > 0) {
try { try {
Thread.sleep(delayMillis); Thread.sleep(delayMillis);
@@ -56,8 +58,10 @@ class CfBasicHttpClientErrorTest {
} }
}); });
server.start(); server.start();
client = new CfDnsClient(false, "http://localhost:" + server.getAddress().getPort(), client = new CfDnsClientBuilder()
new CfDnsClientBuilder.ApiTokenAuth("test-token")); .withApiTokenAuth("test-token")
.withBaseUrl("http://localhost:" + server.getAddress().getPort())
.build();
} }
@AfterEach @AfterEach
@@ -134,14 +138,27 @@ class CfBasicHttpClientErrorTest {
assertTrue(e.getErrors().isEmpty()); assertTrue(e.getErrors().isEmpty());
} }
@Test
void trailingSlashOfBaseUrlIsRemoved() throws Exception {
respond(200, ZONE_JSON);
try (CfDnsClient slashClient = new CfDnsClientBuilder()
.withApiTokenAuth("test-token")
.withBaseUrl("http://localhost:" + server.getAddress().getPort() + "/client/v4/")
.build()) {
slashClient.zoneList();
}
assertEquals("/client/v4/zones", lastPath);
}
@Test @Test
void responseTimeoutIsApplied() throws Exception { void responseTimeoutIsApplied() throws Exception {
respond(200, ZONE_JSON); respond(200, ZONE_JSON);
delayMillis = 2000; delayMillis = 2000;
try (CfDnsClient timeoutClient = new CfDnsClient(false, try (CfDnsClient timeoutClient = new CfDnsClientBuilder()
"http://localhost:" + server.getAddress().getPort(), .withApiTokenAuth("test-token")
new CfDnsClientBuilder.ApiTokenAuth("test-token"), CfDnsClient.RECORDS_PER_PAGE, .withBaseUrl("http://localhost:" + server.getAddress().getPort())
CfDnsClientBuilder.DEFAULT_CONNECT_TIMEOUT, Duration.ofMillis(200))) { .withResponseTimeout(Duration.ofMillis(200))
.build()) {
long start = System.nanoTime(); long start = System.nanoTime();
CloudflareApiException e = assertThrows(CloudflareApiException.class, timeoutClient::zoneList); CloudflareApiException e = assertThrows(CloudflareApiException.class, timeoutClient::zoneList);
long elapsedMillis = (System.nanoTime() - start) / 1_000_000; long elapsedMillis = (System.nanoTime() - start) / 1_000_000;
@@ -16,7 +16,6 @@ import codes.thischwa.cf.model.PagingRequest;
import codes.thischwa.cf.model.RecordEntity; import codes.thischwa.cf.model.RecordEntity;
import codes.thischwa.cf.model.RecordType; import codes.thischwa.cf.model.RecordType;
import codes.thischwa.cf.model.ZoneEntity; import codes.thischwa.cf.model.ZoneEntity;
import java.net.IDN;
import java.time.Instant; import java.time.Instant;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
@@ -31,7 +30,7 @@ import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@Slf4j @Slf4j
public class CfClientIntegrationTest { public class CfClientTest {
private static final String ZONE_STR = "mein-d-ns.de"; private static final String ZONE_STR = "mein-d-ns.de";
private static final String SLD_STR = "devsld"; private static final String SLD_STR = "devsld";
@@ -44,9 +43,6 @@ public class CfClientIntegrationTest {
private static final String IP_PREFIX = "130.0.0."; private static final String IP_PREFIX = "130.0.0.";
private static final String UPDATED_IP_PREFIX = "130.1.0."; private static final String UPDATED_IP_PREFIX = "130.1.0.";
private record PagedResult(int total, Set<String> allIds, List<List<RecordEntity>> pages) {
}
@BeforeAll @BeforeAll
static void checkEnv() { static void checkEnv() {
assumeTrue(API_TOKEN != null && !API_TOKEN.isBlank(), "API_TOKEN not set; skipping client tests"); assumeTrue(API_TOKEN != null && !API_TOKEN.isBlank(), "API_TOKEN not set; skipping client tests");
@@ -113,7 +109,7 @@ public class CfClientIntegrationTest {
assertFalse(zones.isEmpty()); assertFalse(zones.isEmpty());
assertEquals(ZONE_STR, zones.get(0).getName()); assertEquals(ZONE_STR, zones.get(0).getName());
zones = client.zoneList(PagingRequest.forZones(1, 50)); zones = client.zoneList(PagingRequest.of(1, 100));
assertNotNull(zones); assertNotNull(zones);
assertFalse(zones.isEmpty()); assertFalse(zones.isEmpty());
assertEquals(ZONE_STR, zones.get(0).getName()); assertEquals(ZONE_STR, zones.get(0).getName());
@@ -474,73 +470,73 @@ public class CfClientIntegrationTest {
assertEquals(2, groupedRecords.get("example.com.").size(), "The key 'example.com.' should have 2 records."); assertEquals(2, groupedRecords.get("example.com.").size(), "The key 'example.com.' should have 2 records.");
} }
@Test @Test
void testPaging() throws Exception { void testPaging() throws Exception {
ZoneEntity zone = client.zoneGet(ZONE_STR); ZoneEntity zone = client.zoneGet(ZONE_STR);
String pagingSld = "paging-" + System.currentTimeMillis(); String pagingSld = "paging-" + System.currentTimeMillis();
List<RecordEntity> createdRecords = new ArrayList<>(); List<RecordEntity> createdRecords = new ArrayList<>();
Set<String> createdIds = new HashSet<>();
try { try {
List<RecordEntity> staleRecords = List.of(); int existingCount = 0;
try { try {
staleRecords = client.recordList(zone).stream() List<RecordEntity> allRecords = client.recordList(zone);
.filter(record -> record.getName() != null && record.getName().startsWith("paging-")) existingCount = allRecords.size();
.toList(); } catch (CloudflareApiException e) {
} catch (CloudflareNotFoundException ignored) { // ignore
// The zone is empty.
} }
deleteQuietly(zone, staleRecords);
// Each record gets its own name, so the order by name is unambiguous. // Calculate how many records we need to create to reach at least 12 total A records
for (int i = 1; i <= 12; i++) { // (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. Each record gets its own name, so the order by name
// is unambiguous (Cloudflare doesn't guarantee a stable order of records with the same name).
for (int i = 1; i <= recordsToCreate; i++) {
String name = String.format("%s-%02d.%s", pagingSld, i, ZONE_STR); String name = String.format("%s-%02d.%s", pagingSld, i, ZONE_STR);
RecordEntity record = RecordEntity.build(name, RecordType.A, TTL, "127.0.0." + i); RecordEntity record = RecordEntity.build(name, RecordType.A, TTL, "127.0.0." + i);
RecordEntity created = client.recordCreate(zone, record); RecordEntity created = client.recordCreate(zone, record);
createdRecords.add(created); createdRecords.add(created);
assertNotNull(created.getId()); assertNotNull(created.getId());
createdIds.add(created.getId());
} }
PagedResult pagedResult = pageThrough(zone, createdIds, 5); // Test paging with page size of 5
List<String> pagedIds = pagedResult.pages().stream() PagingRequest page1Request = PagingRequest.of(1, 5);
.flatMap(List::stream) List<RecordEntity> page1Records = client.recordList(zone, page1Request);
.map(RecordEntity::getId) assertEquals(5, page1Records.size(), "First page should contain 5 records");
.toList();
Set<String> pagedIdSet = new HashSet<>(pagedIds);
for (int page = 1; page <= pagedResult.pages().size(); page++) { // 2nd page should also contain 5 records (if we have at least 12 total)
int expected = Math.max(0, Math.min(5, PagingRequest page2Request = PagingRequest.of(2, 5);
pagedResult.total() - 5 * (page - 1))); List<RecordEntity> page2Records = client.recordList(zone, page2Request);
assertEquals(expected, pagedResult.pages().get(page - 1).size(), assertEquals(5, page2Records.size(), "Second page should contain at least 5 records");
"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() // 3rd page should contain 2 records
.flatMap(List::stream) PagingRequest page3Request = PagingRequest.of(3, 5);
.filter(record -> createdIds.contains(record.getId())) List<RecordEntity> page3Records = client.recordList(zone, page3Request);
.map(RecordEntity::getName) assertEquals(2, page3Records.size(), "Third page should contain 2 records");
.toList();
assertEquals(createdRecords.stream().map(RecordEntity::getName).toList(), // Verify no overlap between pages
createdNamesInPageOrder, "The test records should be sorted by name"); 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));
// Without PagingRequest all pages must be fetched, also if the page size is small // Without PagingRequest all pages must be fetched, also if the page size is small
try (CfDnsClient smallPageClient = new CfDnsClient(true, CfDnsClientBuilder.DEFAULT_BASEURL, try (CfDnsClient smallPageClient = new CfDnsClient(true, CfDnsClientBuilder.DEFAULT_BASEURL,
new CfDnsClientBuilder.ApiTokenAuth(API_TOKEN), 5)) { new CfDnsClientBuilder.ApiTokenAuth(API_TOKEN), 5)) {
List<RecordEntity> allRecords = awaitRecords(() -> smallPageClient.recordList(zone), assertEquals(allRecordIds, smallPageClient.recordList(zone).stream()
recs -> ids(recs).containsAll(createdIds)); .map(RecordEntity::getId).collect(Collectors.toSet()));
assertTrue(ids(allRecords).containsAll(createdIds)); assertEquals(createdRecords.size(), smallPageClient.recordListByType(zone, RecordType.A).size());
List<RecordEntity> aRecords = awaitRecords(
() -> smallPageClient.recordListByType(zone, RecordType.A),
recs -> ids(recs).containsAll(createdIds));
assertTrue(ids(aRecords).containsAll(createdIds));
assertEquals(1, smallPageClient.recordListBySubdomain(zone, pagingSld + "-01").size()); assertEquals(1, smallPageClient.recordListBySubdomain(zone, pagingSld + "-01").size());
} }
} finally { } finally {
@@ -548,47 +544,6 @@ public class CfClientIntegrationTest {
} }
} }
private static Set<String> ids(List<RecordEntity> records) {
return records.stream().map(RecordEntity::getId).collect(Collectors.toSet());
}
private PagedResult pageThrough(ZoneEntity zone, Set<String> createdIds, int pageSize)
throws CloudflareApiException, InterruptedException {
PagedResult result = null;
for (int attempt = 1; attempt <= 3; attempt++) {
List<RecordEntity> allRecords = awaitRecords(() -> client.recordList(zone),
records -> ids(records).containsAll(createdIds));
int total = allRecords.size();
Set<String> allIds = ids(allRecords);
List<List<RecordEntity>> pages = new ArrayList<>();
List<String> pagedIds = new ArrayList<>();
int pageCount = (total + pageSize - 1) / pageSize + 1;
boolean pageSizesMatch = true;
for (int page = 1; page <= pageCount; page++) {
int currentPage = page;
int expected = Math.max(0, Math.min(pageSize, total - pageSize * (page - 1)));
List<RecordEntity> pageRecords = awaitRecords(
() -> client.recordList(zone, PagingRequest.forRecords(currentPage, pageSize)),
records -> records.size() == expected);
pages.add(pageRecords);
pagedIds.addAll(pageRecords.stream().map(RecordEntity::getId).toList());
if (pageRecords.size() != expected) {
pageSizesMatch = false;
}
}
result = new PagedResult(total, allIds, pages);
if (pageSizesMatch && new HashSet<>(pagedIds).equals(allIds)) {
return result;
}
if (attempt < 3) {
Thread.sleep(1000);
}
}
return result;
}
@Test @Test
void testApiErrorDetails() throws Exception { void testApiErrorDetails() throws Exception {
ZoneEntity zone = client.zoneGet(ZONE_STR); ZoneEntity zone = client.zoneGet(ZONE_STR);
@@ -682,39 +637,6 @@ public class CfClientIntegrationTest {
} }
} }
@Test
void testIdnSubdomain() throws Exception {
ZoneEntity zone = client.zoneGet(ZONE_STR);
String idnSub = "bücher-" + System.currentTimeMillis();
String punycodeSub = IDN.toASCII(idnSub);
assertTrue(punycodeSub.startsWith("xn--"), punycodeSub);
try {
// the Unicode subdomain is sent as Punycode, Cloudflare returns the Punycode name
RecordEntity rec = client.recordCreateSubdomain(zone, idnSub, TTL, RecordType.A, "130.0.0.30");
assertNotNull(rec.getId());
assertEquals(punycodeSub + "." + ZONE_STR, rec.getName());
assertEquals(punycodeSub, rec.getSubdomain());
// the record is found by the Unicode and by the Punycode subdomain
List<RecordEntity> byUnicode = client.recordListBySubdomain(zone, idnSub, RecordType.A);
assertEquals(1, byUnicode.size());
assertEquals(rec.getId(), byUnicode.get(0).getId());
assertEquals("130.0.0.30", byUnicode.get(0).getContent());
List<RecordEntity> byPunycode = client.recordListBySubdomain(zone, punycodeSub, RecordType.A);
assertEquals(1, byPunycode.size());
assertEquals(rec.getId(), byPunycode.get(0).getId());
// delete by the Unicode subdomain
client.recordDeleteTypeIfExists(zone, idnSub, RecordType.A);
assertThrows(CloudflareNotFoundException.class,
() -> client.recordListBySubdomain(zone, idnSub, RecordType.A));
} finally {
try {
client.recordDeleteTypeIfExists(zone, punycodeSub, RecordType.A);
} catch (Exception e) { /* ignore */ }
}
}
@Test @Test
void testTypeFilter() throws Exception { void testTypeFilter() throws Exception {
ZoneEntity zone = client.zoneGet(ZONE_STR); ZoneEntity zone = client.zoneGet(ZONE_STR);
@@ -826,9 +748,6 @@ public class CfClientIntegrationTest {
} }
} catch (CloudflareNotFoundException e) { } catch (CloudflareNotFoundException e) {
recs = List.of(); recs = List.of();
if (condition.test(recs)) {
return recs;
}
} }
log.info("Records not yet listed (attempt {}), waiting ...", attempt); log.info("Records not yet listed (attempt {}), waiting ...", attempt);
Thread.sleep(1000); Thread.sleep(1000);
@@ -4,7 +4,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
import java.lang.reflect.Method;
import java.time.Duration; import java.time.Duration;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@@ -126,6 +125,18 @@ class CfDnsClientBuilderTest {
assertNotNull(client); assertNotNull(client);
} }
@Test
void testBuilderWithMultipleBaseUrls() {
// Test setting base URL multiple times (last one wins)
CfDnsClient client = new CfDnsClientBuilder()
.withApiTokenAuth("test-token")
.withBaseUrl("https://old-api.example.com")
.withBaseUrl("https://new-api.example.com") // This should override
.build();
assertNotNull(client);
}
@Test @Test
void testEmptyResultThrowsExceptionToggle() { void testEmptyResultThrowsExceptionToggle() {
// Test toggling the flag multiple times (last one wins) // Test toggling the flag multiple times (last one wins)
@@ -151,21 +162,13 @@ class CfDnsClientBuilderTest {
} }
@Test @Test
void testBaseUrlAllowsOnlyCloudflareHttps() { void testBaseUrlAllowsHttpForLoopbackOnly() {
assertNotNull(new CfDnsClientBuilder().withApiTokenAuth("t") assertNotNull(new CfDnsClientBuilder().withApiTokenAuth("t").withBaseUrl("http://localhost:8080").build());
.withBaseUrl("HTTPS://API.CLOUDFLARE.COM/client/v4/").build()); assertNotNull(new CfDnsClientBuilder().withApiTokenAuth("t").withBaseUrl("http://127.0.0.1:8080/v4").build());
assertNotNull(new CfDnsClientBuilder().withApiTokenAuth("t").withBaseUrl("HTTPS://API.example.com/").build());
assertNotNull(new CfDnsClientBuilder().withApiTokenAuth("t").withBaseUrl(null).build()); 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 @Test
void testInvalidTimeoutsAreRejected() { void testInvalidTimeoutsAreRejected() {
CfDnsClientBuilder builder = new CfDnsClientBuilder(); CfDnsClientBuilder builder = new CfDnsClientBuilder();
@@ -10,7 +10,6 @@ import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoExtension;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.net.IDN;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@@ -120,34 +119,6 @@ class CfDnsClientMockTest {
assertEquals("test.com", zones.get(1).getName()); assertEquals("test.com", zones.get(1).getName());
} }
@Test
void testZoneList_WithPagingEnforcesApiLimits() throws Exception {
ZoneMultipleResponse mockResponse = new ZoneMultipleResponse();
mockResponse.setResult(List.of());
mockResponse.setResponseResultInfo(createSuccessResultInfo());
CfDnsClient spyClient = spy(client);
doReturn(mockResponse).when(spyClient).getRequest(anyString(), eq(ZoneMultipleResponse.class));
spyClient.zoneList(PagingRequest.forZones(1, 5));
spyClient.zoneList(PagingRequest.forZones(1, 50));
verify(spyClient).getRequest(eq("/zones?page=1&per_page=5"), eq(ZoneMultipleResponse.class));
verify(spyClient).getRequest(eq("/zones?page=1&per_page=50"), eq(ZoneMultipleResponse.class));
}
@Test
void testZoneList_WithPagingRejectsOutOfRangePageSizes() throws Exception {
CfDnsClient spyClient = spy(client);
assertThrows(IllegalArgumentException.class,
() -> spyClient.zoneList(new PagingRequest(1, 4)));
assertThrows(IllegalArgumentException.class,
() -> spyClient.zoneList(new PagingRequest(1, 51)));
verify(spyClient, never()).getRequest(anyString(), eq(ZoneMultipleResponse.class));
}
@Test @Test
void testZoneGet() throws Exception { void testZoneGet() throws Exception {
// Create mock zone response // Create mock zone response
@@ -218,7 +189,7 @@ class CfDnsClientMockTest {
@Test @Test
void testRecordList_WithPaging() throws Exception { void testRecordList_WithPaging() throws Exception {
ZoneEntity zone = createTestZone(); ZoneEntity zone = createTestZone();
PagingRequest pagingRequest = PagingRequest.forRecords(10, 1); PagingRequest pagingRequest = PagingRequest.of(10, 1);
RecordMultipleResponse mockResponse = new RecordMultipleResponse(); RecordMultipleResponse mockResponse = new RecordMultipleResponse();
mockResponse.setResultInfo(createResultInfo(1)); mockResponse.setResultInfo(createResultInfo(1));
@@ -485,10 +456,10 @@ class CfDnsClientMockTest {
CfDnsClient spyClient = spy(client); CfDnsClient spyClient = spy(client);
doReturn(zoneResponse(List.of(zone("z1", "a.com"), zone("z2", "b.com")), doReturn(zoneResponse(List.of(zone("z1", "a.com"), zone("z2", "b.com")),
new ResultInfo(1, 2, 2, 2, 3))) new ResultInfo(1, 2, 2, 2, 3)))
.when(spyClient).getRequest(eq("/zones?page=1&per_page=" + PagingRequest.DEFAULT_PAGE_SIZE), .when(spyClient).getRequest(eq("/zones?page=1&per_page=" + CfDnsClient.ZONES_PER_PAGE),
eq(ZoneMultipleResponse.class)); eq(ZoneMultipleResponse.class));
doReturn(zoneResponse(List.of(zone("z3", "c.com")), new ResultInfo(2, 2, 2, 1, 3))) doReturn(zoneResponse(List.of(zone("z3", "c.com")), new ResultInfo(2, 2, 2, 1, 3)))
.when(spyClient).getRequest(eq("/zones?page=2&per_page=" + PagingRequest.DEFAULT_PAGE_SIZE), .when(spyClient).getRequest(eq("/zones?page=2&per_page=" + CfDnsClient.ZONES_PER_PAGE),
eq(ZoneMultipleResponse.class)); eq(ZoneMultipleResponse.class));
List<ZoneEntity> zones = spyClient.zoneList(); List<ZoneEntity> zones = spyClient.zoneList();
@@ -618,22 +589,6 @@ class CfDnsClientMockTest {
.when(spyClient).getRequest(anyString(), eq(RecordMultipleResponse.class)); .when(spyClient).getRequest(anyString(), eq(RecordMultipleResponse.class));
assertEquals(1, spyClient.recordList(createTestZone(), null).size()); assertEquals(1, spyClient.recordList(createTestZone(), null).size());
verify(spyClient).getRequest(eq("/zones/" + TEST_ZONE_ID
+ "/dns_records?order=name&direction=asc&page=1&per_page=" + CfDnsClient.RECORDS_PER_PAGE),
eq(RecordMultipleResponse.class));
}
@Test
void testRecordList_ExplicitPagingRequestIsPreserved() throws Exception {
CfDnsClient spyClient = spy(client);
doReturn(recordResponse(List.of(), new ResultInfo(0)))
.when(spyClient).getRequest(anyString(), eq(RecordMultipleResponse.class));
spyClient.recordList(createTestZone(), PagingRequest.forRecords(2, 42));
verify(spyClient).getRequest(eq("/zones/" + TEST_ZONE_ID
+ "/dns_records?order=name&direction=asc&page=2&per_page=42"),
eq(RecordMultipleResponse.class));
} }
@Test @Test
@@ -788,12 +743,6 @@ class CfDnsClientMockTest {
() -> spyClient.recordCreateSubdomain(zone, sub, 60, RecordType.A, "1.2.3.4"), sub); () -> spyClient.recordCreateSubdomain(zone, sub, 60, RecordType.A, "1.2.3.4"), sub);
} }
assertThrows(IllegalArgumentException.class, () -> spyClient.recordListBySubdomain(zone, null)); assertThrows(IllegalArgumentException.class, () -> spyClient.recordListBySubdomain(zone, null));
String tooLongIdnLabel = "ä".repeat(64);
assertThrows(IllegalArgumentException.class,
() -> spyClient.recordListBySubdomain(zone, tooLongIdnLabel));
assertThrows(IllegalArgumentException.class,
() -> spyClient.recordCreateSubdomain(zone, tooLongIdnLabel, 60, RecordType.A,
"1.2.3.4"));
assertThrows(IllegalArgumentException.class, () -> spyClient.zoneGet("example.com&account.id=1")); assertThrows(IllegalArgumentException.class, () -> spyClient.zoneGet("example.com&account.id=1"));
assertThrows(IllegalArgumentException.class, () -> spyClient.zoneGet(" ")); assertThrows(IllegalArgumentException.class, () -> spyClient.zoneGet(" "));
verify(spyClient, never()).getRequest(anyString(), any()); verify(spyClient, never()).getRequest(anyString(), any());
@@ -817,40 +766,6 @@ class CfDnsClientMockTest {
eq(RecordMultipleResponse.class)); eq(RecordMultipleResponse.class));
} }
@Test
void testIdnSubdomainIsConvertedToPunycode() throws Exception {
CfDnsClient spyClient = spy(client);
ZoneEntity zone = createTestZone();
doReturn(recordResponse(List.of(), new ResultInfo(0)))
.when(spyClient).getRequest(anyString(), eq(RecordMultipleResponse.class));
doReturn(singleResponse(RecordEntity.build(
"xn--bcher-kva.example.com", RecordType.A, 60, "1.2.3.4")))
.when(spyClient).postRequest(anyString(), any(), eq(RecordSingleResponse.class));
spyClient.recordListBySubdomain(zone, "bücher");
spyClient.recordListBySubdomain(zone, "shop.bücher");
spyClient.recordListBySubdomain(zone, "xn--bcher-kva");
// code points newer than IDNA2003 (Unicode 3.2) like emojis must not be rejected
spyClient.recordListBySubdomain(zone, "emoji-🥷-忍者");
spyClient.recordCreateSubdomain(zone, "bücher", 60, RecordType.A, "1.2.3.4");
String base = "/zones/" + TEST_ZONE_ID + "/dns_records?name=";
String suffix = "&order=name&direction=asc&page=1&per_page=" + CfDnsClient.RECORDS_PER_PAGE;
verify(spyClient, times(2)).getRequest(eq(base + "xn--bcher-kva.example.com" + suffix),
eq(RecordMultipleResponse.class));
verify(spyClient).getRequest(eq(base + "shop.xn--bcher-kva.example.com" + suffix),
eq(RecordMultipleResponse.class));
String emojiPunycode = IDN.toASCII("emoji-🥷-忍者", IDN.ALLOW_UNASSIGNED);
assertTrue(emojiPunycode.startsWith("xn--"), emojiPunycode);
verify(spyClient).getRequest(eq(base + emojiPunycode + ".example.com" + suffix),
eq(RecordMultipleResponse.class));
ArgumentCaptor<Object> payload = ArgumentCaptor.forClass(Object.class);
verify(spyClient).postRequest(eq("/zones/" + TEST_ZONE_ID + "/dns_records"),
payload.capture(), eq(RecordSingleResponse.class));
assertEquals("xn--bcher-kva.example.com", ((RecordEntity) payload.getValue()).getName());
}
@Test @Test
void testRecordIdPathTraversalIsRejected() throws Exception { void testRecordIdPathTraversalIsRejected() throws Exception {
CfDnsClient spyClient = spy(client); CfDnsClient spyClient = spy(client);
@@ -1,80 +1,43 @@
package codes.thischwa.cf.model; package codes.thischwa.cf.model;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
class PagingRequestTest { import static org.junit.jupiter.api.Assertions.*;
@Test public class PagingRequestTest {
void testBuildPath() {
String result = PagingRequest.defaultPaging().addQueryString("/zones");
assertEquals("/zones?page=1&per_page=50", result);
}
@Test @Test
void testBuildPathWithExistingQuery() { void testBuildPath() {
String result = PagingRequest.forRecords(10, 100).addQueryString("/zones?foo=bar"); String result = PagingRequest.defaultPaging().addQueryString("/zones");
assertEquals("/zones?foo=bar&page=10&per_page=100", result); assertEquals("/zones?page=1&per_page=1000", result);
} }
@Test @Test
void testPagingRequestBoundaries() { void testBuildPathAdditional() {
assertDoesNotThrow(() -> PagingRequest.forRecords(1, 1)); String result = new PagingRequest( 10, 100).addQueryString("/zones?foo=bar");
assertDoesNotThrow(() -> PagingRequest.forRecords(1, PagingRequest.MAX_RECORDS_PER_PAGE)); assertEquals("/zones?foo=bar&page=10&per_page=100", result);
assertThrows(IllegalArgumentException.class, () -> PagingRequest.forRecords(0, 1)); }
assertThrows(IllegalArgumentException.class, () -> PagingRequest.forRecords(1, 0));
assertThrows(IllegalArgumentException.class,
() -> PagingRequest.forRecords(1, PagingRequest.MAX_RECORDS_PER_PAGE + 1));
}
@Test @Test
void testZonePageSizeBoundaries() { void testGetPagingParams() {
assertDoesNotThrow(() -> PagingRequest.forZones(1, PagingRequest.MIN_ZONES_PER_PAGE)); PagingRequest request = PagingRequest.of(2, 50);
assertDoesNotThrow(() -> PagingRequest.forZones(1, PagingRequest.MAX_ZONES_PER_PAGE)); java.util.Map<String, String> params = request.getPagingParams();
assertThrows(IllegalArgumentException.class, assertEquals("2", params.get("page"));
() -> PagingRequest.forZones(1, PagingRequest.MIN_ZONES_PER_PAGE - 1)); assertEquals("50", params.get("perPage"));
assertThrows(IllegalArgumentException.class, }
() -> PagingRequest.forZones(1, PagingRequest.MAX_ZONES_PER_PAGE + 1));
}
@Test @Test
void testNextAndWithPageReturnNewRequests() { void testLombokMethods() {
PagingRequest request = PagingRequest.forRecords(2, 50); 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"));
assertEquals(PagingRequest.forRecords(3, 50), request.next()); req1.setPage(5);
assertEquals(PagingRequest.forRecords(5, 50), request.withPage(5)); assertEquals(5, req1.getPage());
assertEquals(PagingRequest.forRecords(2, 50), request); req1.setPerPage(20);
} assertEquals(20, req1.getPerPage());
}
@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));
}
} }