diff --git a/api/src/main/java/org/apache/cloudstack/dns/DnsProviderType.java b/api/src/main/java/org/apache/cloudstack/dns/DnsProviderType.java
index 23c8e936613f..36af1c505636 100644
--- a/api/src/main/java/org/apache/cloudstack/dns/DnsProviderType.java
+++ b/api/src/main/java/org/apache/cloudstack/dns/DnsProviderType.java
@@ -18,6 +18,7 @@
package org.apache.cloudstack.dns;
public enum DnsProviderType {
- PowerDNS;
+ PowerDNS,
+ BunnyDNS;
// Cloudflare
}
diff --git a/client/pom.xml b/client/pom.xml
index cc031a4912b1..cfd0ab5068d1 100644
--- a/client/pom.xml
+++ b/client/pom.xml
@@ -687,6 +687,11 @@
cloud-plugin-dns-powerdns
${project.version}
+
+ org.apache.cloudstack
+ cloud-plugin-dns-bunny
+ ${project.version}
+
diff --git a/plugins/dns/bunny/pom.xml b/plugins/dns/bunny/pom.xml
new file mode 100644
index 000000000000..17c50513caf1
--- /dev/null
+++ b/plugins/dns/bunny/pom.xml
@@ -0,0 +1,30 @@
+
+
+ 4.0.0
+ cloud-plugin-dns-bunny
+ Apache CloudStack Plugin - Bunny DNS
+
+ org.apache.cloudstack
+ cloudstack-plugins
+ 24.0.0-SNAPSHOT
+ ../../pom.xml
+
+
diff --git a/plugins/dns/bunny/src/main/java/org/apache/cloudstack/dns/bunny/BunnyDnsClient.java b/plugins/dns/bunny/src/main/java/org/apache/cloudstack/dns/bunny/BunnyDnsClient.java
new file mode 100644
index 000000000000..9006e4d49117
--- /dev/null
+++ b/plugins/dns/bunny/src/main/java/org/apache/cloudstack/dns/bunny/BunnyDnsClient.java
@@ -0,0 +1,478 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.cloudstack.dns.bunny;
+
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.cloudstack.dns.exception.DnsAuthenticationException;
+import org.apache.cloudstack.dns.exception.DnsConflictException;
+import org.apache.cloudstack.dns.exception.DnsNotFoundException;
+import org.apache.cloudstack.dns.exception.DnsOperationException;
+import org.apache.cloudstack.dns.exception.DnsProviderException;
+import org.apache.cloudstack.dns.exception.DnsTransportException;
+import org.apache.http.client.config.RequestConfig;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpDelete;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.client.methods.HttpPut;
+import org.apache.http.client.methods.HttpUriRequest;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClientBuilder;
+import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
+import org.apache.http.util.EntityUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.cloud.utils.StringUtils;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+
+/**
+ * Thin client for the Bunny.net DNS API (https://api.bunny.net).
+ *
+ * Unlike PowerDNS, Bunny has no rrset concept: every value (e.g. every A record under the same
+ * name) is its own record with its own numeric id, and zones/records are only addressable by that
+ * id. Since CloudStack's DnsZone/DnsRecord abstractions carry neither Bunny's zone id nor its
+ * record ids, this client resolves them by name on every call (mirroring how the PowerDNS plugin
+ * re-resolves its server id per call).
+ */
+public class BunnyDnsClient implements AutoCloseable {
+ public static final Logger logger = LoggerFactory.getLogger(BunnyDnsClient.class);
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+
+ private static final int CONNECT_TIMEOUT_MS = 5_000;
+ private static final int SOCKET_TIMEOUT_MS = 10_000;
+ private static final int MAX_CONNECTIONS_TOTAL = 50;
+ private static final int MAX_CONNECTIONS_PER_ROUTE = 10;
+ private static final int PAGE_SIZE = 1000;
+
+ public static final String DEFAULT_BASE_URL = "https://api.bunny.net";
+ private static final String ACCESS_KEY_HEADER = "AccessKey";
+
+ /** Bunny's integer DnsRecordTypes, limited to the types DnsRecord.RecordType models. */
+ private static final Map TYPE_TO_CODE = new HashMap<>();
+ private static final Map CODE_TO_TYPE = new HashMap<>();
+ static {
+ putType("A", 0);
+ putType("AAAA", 1);
+ putType("CNAME", 2);
+ putType("TXT", 3);
+ putType("MX", 4);
+ putType("SRV", 8);
+ putType("PTR", 10);
+ putType("NS", 12);
+ }
+
+ private static void putType(String name, int code) {
+ TYPE_TO_CODE.put(name, code);
+ CODE_TO_TYPE.put(code, name);
+ }
+
+ private final CloseableHttpClient httpClient;
+
+ public BunnyDnsClient() {
+ PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
+ connectionManager.setMaxTotal(MAX_CONNECTIONS_TOTAL);
+ connectionManager.setDefaultMaxPerRoute(MAX_CONNECTIONS_PER_ROUTE);
+
+ RequestConfig requestConfig = RequestConfig.custom()
+ .setConnectTimeout(CONNECT_TIMEOUT_MS)
+ .setConnectionRequestTimeout(CONNECT_TIMEOUT_MS)
+ .setSocketTimeout(SOCKET_TIMEOUT_MS)
+ .build();
+
+ this.httpClient = HttpClientBuilder.create()
+ .setConnectionManager(connectionManager)
+ .setDefaultRequestConfig(requestConfig)
+ .evictIdleConnections(30, TimeUnit.SECONDS)
+ .disableCookieManagement()
+ .build();
+ }
+
+ public static int typeCode(String type) {
+ Integer code = TYPE_TO_CODE.get(type.toUpperCase());
+ if (code == null) {
+ throw new IllegalArgumentException("Unsupported Bunny DNS record type: " + type);
+ }
+ return code;
+ }
+
+ public static String typeName(int code) {
+ return CODE_TO_TYPE.get(code);
+ }
+
+ public void validateAccess(String baseUrl, Integer port, String apiKey) throws DnsProviderException {
+ HttpGet request = new HttpGet(buildUrl(baseUrl, port, "/dnszone?perPage=5&page=1"));
+ execute(request, apiKey, 200);
+ }
+
+ public long resolveZoneId(String baseUrl, Integer port, String apiKey, String domain) throws DnsProviderException {
+ String normalizedDomain = normalizeDomain(domain);
+ int page = 1;
+ while (true) {
+ String urlPath = "/dnszone?search=" + URLEncoder.encode(normalizedDomain, StandardCharsets.UTF_8)
+ + "&perPage=" + PAGE_SIZE + "&page=" + page;
+ HttpGet request = new HttpGet(buildUrl(baseUrl, port, urlPath));
+ JsonNode response = execute(request, apiKey, 200);
+ JsonNode items = response != null ? response.path("Items") : null;
+ if (items != null && items.isArray()) {
+ for (JsonNode zone : items) {
+ if (normalizedDomain.equalsIgnoreCase(zone.path("Domain").asText(null))) {
+ return zone.path("Id").asLong();
+ }
+ }
+ }
+ if (response == null || !response.path("HasMoreItems").asBoolean(false)) {
+ break;
+ }
+ page++;
+ }
+ throw new DnsNotFoundException("Bunny DNS zone not found for domain: " + domain);
+ }
+
+ public boolean zoneExists(String baseUrl, Integer port, String apiKey, String domain) {
+ try {
+ resolveZoneId(baseUrl, port, apiKey, domain);
+ return true;
+ } catch (DnsProviderException | IllegalArgumentException e) {
+ return false;
+ }
+ }
+
+ /** The response body of Bunny's Add DNS Zone call is undocumented, hence the lookup when it carries no id. */
+ public long createZone(String baseUrl, Integer port, String apiKey, String domain) throws DnsProviderException {
+ String normalizedDomain = normalizeDomain(domain);
+ ObjectNode json = MAPPER.createObjectNode();
+ json.put("Domain", normalizedDomain);
+ HttpPost request = new HttpPost(buildUrl(baseUrl, port, "/dnszone"));
+ request.setEntity(new StringEntity(json.toString(), StandardCharsets.UTF_8));
+ JsonNode response = execute(request, apiKey, 201);
+ if (response != null && response.hasNonNull("Id")) {
+ return response.path("Id").asLong();
+ }
+ return resolveZoneId(baseUrl, port, apiKey, normalizedDomain);
+ }
+
+ public void deleteZone(String baseUrl, Integer port, String apiKey, String domain) throws DnsProviderException {
+ long zoneId;
+ try {
+ zoneId = resolveZoneId(baseUrl, port, apiKey, domain);
+ } catch (DnsNotFoundException e) {
+ return;
+ }
+ HttpDelete request = new HttpDelete(buildUrl(baseUrl, port, "/dnszone/" + zoneId));
+ execute(request, apiKey, 204, 404);
+ }
+
+ public String addRecord(String baseUrl, Integer port, String apiKey, long zoneId, String zoneDomain,
+ String recordName, String type, int ttl, String content) throws DnsProviderException {
+ String bunnyName = toBunnyRecordName(recordName, zoneDomain);
+ ObjectNode body = buildRecordBody(bunnyName, type, ttl, content);
+ HttpPut request = new HttpPut(buildUrl(baseUrl, port, "/dnszone/" + zoneId + "/records"));
+ request.setEntity(new StringEntity(body.toString(), StandardCharsets.UTF_8));
+ execute(request, apiKey, 201);
+ return toFqdn(bunnyName, zoneDomain);
+ }
+
+ /**
+ * Makes the records of a name and type match the given contents, like a PowerDNS rrset REPLACE.
+ * Records which already match are left untouched.
+ */
+ public String replaceRecords(String baseUrl, Integer port, String apiKey, long zoneId, String zoneDomain,
+ String recordName, String type, int ttl, List contents) throws DnsProviderException {
+ List missing = new ArrayList<>(contents);
+ for (JsonNode record : findRecordsByNameAndType(baseUrl, port, apiKey, zoneId, zoneDomain, recordName, type)) {
+ if (record.path("Ttl").asInt() != ttl || !missing.remove(formatContent(type, record))) {
+ deleteRecord(baseUrl, port, apiKey, zoneId, record.path("Id").asLong());
+ }
+ }
+ for (String content : missing) {
+ addRecord(baseUrl, port, apiKey, zoneId, zoneDomain, recordName, type, ttl, content);
+ }
+ return toFqdn(toBunnyRecordName(recordName, zoneDomain), zoneDomain);
+ }
+
+ private void deleteRecord(String baseUrl, Integer port, String apiKey, long zoneId, long recordId) throws DnsProviderException {
+ execute(new HttpDelete(buildUrl(baseUrl, port, "/dnszone/" + zoneId + "/records/" + recordId)), apiKey, 204, 404);
+ }
+
+ public List findRecordsByNameAndType(String baseUrl, Integer port, String apiKey, long zoneId,
+ String zoneDomain, String recordName, String type) throws DnsProviderException {
+ String bunnyName = toBunnyRecordName(recordName, zoneDomain);
+ List matches = new ArrayList<>();
+ for (JsonNode record : listRecordsRaw(baseUrl, port, apiKey, zoneId, typeCode(type))) {
+ if (bunnyName.equalsIgnoreCase(record.path("Name").asText(""))) {
+ matches.add(record);
+ }
+ }
+ return matches;
+ }
+
+ public String deleteRecordsByNameAndType(String baseUrl, Integer port, String apiKey, long zoneId,
+ String zoneDomain, String recordName, String type) throws DnsProviderException {
+ for (JsonNode record : findRecordsByNameAndType(baseUrl, port, apiKey, zoneId, zoneDomain, recordName, type)) {
+ deleteRecord(baseUrl, port, apiKey, zoneId, record.path("Id").asLong());
+ }
+ return toFqdn(toBunnyRecordName(recordName, zoneDomain), zoneDomain);
+ }
+
+ public List listRecords(String baseUrl, Integer port, String apiKey, long zoneId) throws DnsProviderException {
+ return listRecordsRaw(baseUrl, port, apiKey, zoneId, null);
+ }
+
+ private List listRecordsRaw(String baseUrl, Integer port, String apiKey, long zoneId, Integer typeFilter) throws DnsProviderException {
+ List results = new ArrayList<>();
+ int page = 1;
+ while (true) {
+ StringBuilder urlPath = new StringBuilder("/dnszone/" + zoneId + "/records?perPage=" + PAGE_SIZE + "&page=" + page);
+ if (typeFilter != null) {
+ urlPath.append("&type=").append(typeFilter);
+ }
+ HttpGet request = new HttpGet(buildUrl(baseUrl, port, urlPath.toString()));
+ JsonNode response = execute(request, apiKey, 200);
+ JsonNode items = response != null ? response.path("Items") : null;
+ if (items != null && items.isArray()) {
+ for (JsonNode item : items) {
+ results.add(item);
+ }
+ }
+ if (response == null || !response.path("HasMoreItems").asBoolean(false)) {
+ break;
+ }
+ page++;
+ }
+ return results;
+ }
+
+ private ObjectNode buildRecordBody(String bunnyName, String type, int ttl, String content) {
+ ObjectNode body = MAPPER.createObjectNode();
+ body.put("Name", bunnyName);
+ body.put("Type", typeCode(type));
+ body.put("Ttl", ttl);
+ ContentFields fields = parseContent(type, content);
+ body.put("Value", fields.value);
+ if (fields.priority != null) {
+ body.put("Priority", fields.priority);
+ }
+ if (fields.weight != null) {
+ body.put("Weight", fields.weight);
+ }
+ if (fields.port != null) {
+ body.put("Port", fields.port);
+ }
+ return body;
+ }
+
+ /**
+ * MX/SRV contents arrive as PowerDNS-style zonefile text (e.g. "10 mail.example.com" or
+ * "10 20 5061 sip.example.com") from DnsProviderUtil.normalizeDnsRecordValue, but Bunny's API
+ * wants priority/weight/port as discrete fields with the target alone in Value. Hostnames
+ * arrive with a trailing dot, which Bunny does not use.
+ */
+ static ContentFields parseContent(String type, String content) {
+ if (StringUtils.isBlank(content)) {
+ throw new IllegalArgumentException("DNS record content cannot be empty");
+ }
+ String trimmed = content.trim();
+ switch (type.toUpperCase()) {
+ case "MX": {
+ String[] parts = trimmed.split("\\s+", 2);
+ if (parts.length != 2) {
+ throw new IllegalArgumentException("Invalid MX content, expected ' ': " + trimmed);
+ }
+ return new ContentFields(stripTrailingDot(parts[1]), Integer.parseInt(parts[0]), null, null);
+ }
+ case "SRV": {
+ String[] parts = trimmed.split("\\s+", 4);
+ if (parts.length != 4) {
+ throw new IllegalArgumentException("Invalid SRV content, expected ' ': " + trimmed);
+ }
+ return new ContentFields(stripTrailingDot(parts[3]), Integer.parseInt(parts[0]), Integer.parseInt(parts[1]), Integer.parseInt(parts[2]));
+ }
+ case "CNAME":
+ case "NS":
+ case "PTR":
+ return new ContentFields(stripTrailingDot(trimmed), null, null, null);
+ default:
+ return new ContentFields(trimmed, null, null, null);
+ }
+ }
+
+ static String formatContent(String type, JsonNode record) {
+ String value = record.path("Value").asText("");
+ switch (type.toUpperCase()) {
+ case "MX":
+ return record.path("Priority").asInt(0) + " " + stripTrailingDot(value) + ".";
+ case "SRV":
+ return record.path("Priority").asInt(0) + " " + record.path("Weight").asInt(0) + " " + record.path("Port").asInt(0) + " " + stripTrailingDot(value) + ".";
+ case "CNAME":
+ case "NS":
+ case "PTR":
+ return stripTrailingDot(value) + ".";
+ default:
+ return value;
+ }
+ }
+
+ private static String stripTrailingDot(String value) {
+ return StringUtils.removeEnd(value, ".");
+ }
+
+ static final class ContentFields {
+ final String value;
+ final Integer priority;
+ final Integer weight;
+ final Integer port;
+
+ ContentFields(String value, Integer priority, Integer weight, Integer port) {
+ this.value = value;
+ this.priority = priority;
+ this.weight = weight;
+ this.port = port;
+ }
+ }
+
+ String normalizeDomain(String domain) {
+ if (StringUtils.isBlank(domain)) {
+ throw new IllegalArgumentException("Domain must not be null or empty");
+ }
+ String normalized = domain.trim().toLowerCase();
+ if (normalized.endsWith(".")) {
+ normalized = normalized.substring(0, normalized.length() - 1);
+ }
+ if (normalized.isEmpty()) {
+ throw new IllegalArgumentException("Domain must not be empty");
+ }
+ return normalized;
+ }
+
+ /**
+ * Bunny record names are relative to the zone (empty string for the apex), unlike PowerDNS's
+ * fully-qualified rrset names. Absolute input (trailing dot, or equal to/suffixed by the zone)
+ * has the zone suffix stripped; anything else is assumed already relative.
+ */
+ String toBunnyRecordName(String recordName, String zoneDomain) {
+ if (recordName == null) {
+ throw new IllegalArgumentException("Record name must not be null");
+ }
+ String normalizedZone = normalizeDomain(zoneDomain);
+ String name = recordName.trim().toLowerCase();
+ if (name.equals("@") || name.isEmpty()) {
+ return "";
+ }
+ if (name.endsWith(".")) {
+ name = name.substring(0, name.length() - 1);
+ }
+ if (name.equals(normalizedZone)) {
+ return "";
+ }
+ if (name.endsWith("." + normalizedZone)) {
+ return name.substring(0, name.length() - normalizedZone.length() - 1);
+ }
+ return name;
+ }
+
+ String toFqdn(String bunnyName, String zoneDomain) {
+ String normalizedZone = normalizeDomain(zoneDomain);
+ if (StringUtils.isBlank(bunnyName)) {
+ return normalizedZone;
+ }
+ return bunnyName + "." + normalizedZone;
+ }
+
+ private JsonNode execute(HttpUriRequest request, String apiKey, int... expectedStatus) throws DnsProviderException {
+ request.addHeader(ACCESS_KEY_HEADER, apiKey);
+ request.addHeader("Accept", "application/json");
+ request.addHeader("Content-Type", "application/json");
+
+ try (CloseableHttpResponse response = httpClient.execute(request)) {
+ int status = response.getStatusLine().getStatusCode();
+ String body = response.getEntity() != null ? EntityUtils.toString(response.getEntity()) : null;
+
+ for (int expected : expectedStatus) {
+ if (status == expected) {
+ if (body != null && !body.isEmpty()) {
+ return MAPPER.readTree(body);
+ } else {
+ return null;
+ }
+ }
+ }
+ if (status == 404) {
+ throw new DnsNotFoundException("Resource not found: " + body);
+ } else if (status == 401 || status == 403) {
+ throw new DnsAuthenticationException("Invalid API key");
+ } else if (status == 409) {
+ throw new DnsConflictException("Conflict: " + body);
+ }
+ throw new DnsOperationException("Unexpected Bunny DNS response: HTTP " + status + " Body: " + body);
+ } catch (IOException ex) {
+ throw new DnsTransportException("Error communicating with Bunny DNS", ex);
+ }
+ }
+
+ private String buildUrl(String baseUrl, Integer port, String path) {
+ String fullUrl = normalizeBaseUrl(baseUrl);
+ if (port != null && port > 0) {
+ try {
+ URI uri = new URI(fullUrl);
+ if (uri.getPort() == -1) {
+ fullUrl = fullUrl + ":" + port;
+ }
+ } catch (URISyntaxException e) {
+ fullUrl = fullUrl + ":" + port;
+ }
+ }
+ if (!path.startsWith("/")) {
+ path = "/" + path;
+ }
+ return fullUrl + path;
+ }
+
+ private String normalizeBaseUrl(String baseUrl) {
+ String url = StringUtils.isBlank(baseUrl) ? DEFAULT_BASE_URL : baseUrl.trim();
+ if (!url.startsWith("http://") && !url.startsWith("https://")) {
+ url = "https://" + url;
+ }
+ if (url.endsWith("/")) {
+ url = url.substring(0, url.length() - 1);
+ }
+ return url;
+ }
+
+ @Override
+ public void close() {
+ try {
+ httpClient.close();
+ } catch (IOException e) {
+ logger.warn("Failed to close Bunny DNS HTTP client", e);
+ }
+ }
+}
diff --git a/plugins/dns/bunny/src/main/java/org/apache/cloudstack/dns/bunny/BunnyDnsProvider.java b/plugins/dns/bunny/src/main/java/org/apache/cloudstack/dns/bunny/BunnyDnsProvider.java
new file mode 100644
index 000000000000..5a6834d8604f
--- /dev/null
+++ b/plugins/dns/bunny/src/main/java/org/apache/cloudstack/dns/bunny/BunnyDnsProvider.java
@@ -0,0 +1,171 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.cloudstack.dns.bunny;
+
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.cloudstack.dns.DnsProvider;
+import org.apache.cloudstack.dns.DnsProviderType;
+import org.apache.cloudstack.dns.DnsRecord;
+import org.apache.cloudstack.dns.DnsServer;
+import org.apache.cloudstack.dns.DnsZone;
+import org.apache.cloudstack.dns.exception.DnsProviderException;
+
+import com.cloud.utils.StringUtils;
+import com.cloud.utils.component.AdapterBase;
+import com.fasterxml.jackson.databind.JsonNode;
+
+public class BunnyDnsProvider extends AdapterBase implements DnsProvider {
+ private BunnyDnsClient client;
+
+ @Override
+ public DnsProviderType getProviderType() {
+ return DnsProviderType.BunnyDNS;
+ }
+
+ @Override
+ public void validate(DnsServer server) throws Exception {
+ validateRequiredServerFields(server);
+ client.validateAccess(server.getUrl(), server.getPort(), server.getDnsApiKey());
+ }
+
+ /** Bunny has no server id to resolve, the AccessKey alone identifies the account. */
+ @Override
+ public String validateAndResolveServer(DnsServer server) throws Exception {
+ validate(server);
+ return null;
+ }
+
+ @Override
+ public String provisionZone(DnsServer server, DnsZone zone) throws DnsProviderException {
+ validateRequiredServerAndZoneFields(server, zone);
+ long zoneId = client.createZone(server.getUrl(), server.getPort(), server.getDnsApiKey(), zone.getName());
+ return Long.toString(zoneId);
+ }
+
+ @Override
+ public void deleteZone(DnsServer server, DnsZone zone) throws DnsProviderException {
+ validateRequiredServerAndZoneFields(server, zone);
+ client.deleteZone(server.getUrl(), server.getPort(), server.getDnsApiKey(), zone.getName());
+ }
+
+ /** Nothing in DnsZone maps to a Bunny zone setting, so this only verifies the zone still exists. */
+ @Override
+ public void updateZone(DnsServer server, DnsZone zone) throws DnsProviderException {
+ validateRequiredServerAndZoneFields(server, zone);
+ client.resolveZoneId(server.getUrl(), server.getPort(), server.getDnsApiKey(), zone.getName());
+ }
+
+ /** The DNS framework expects add to replace all records of this name and type, as a PowerDNS rrset does. */
+ @Override
+ public String addRecord(DnsServer server, DnsZone zone, DnsRecord record) throws DnsProviderException {
+ validateRequiredServerAndZoneFields(server, zone);
+ long zoneId = client.resolveZoneId(server.getUrl(), server.getPort(), server.getDnsApiKey(), zone.getName());
+ return client.replaceRecords(server.getUrl(), server.getPort(), server.getDnsApiKey(), zoneId,
+ zone.getName(), record.getName(), record.getType().name(), record.getTtl(), record.getContents());
+ }
+
+ @Override
+ public String updateRecord(DnsServer server, DnsZone zone, DnsRecord record) throws DnsProviderException {
+ return addRecord(server, zone, record);
+ }
+
+ @Override
+ public String deleteRecord(DnsServer server, DnsZone zone, DnsRecord record) throws DnsProviderException {
+ validateRequiredServerAndZoneFields(server, zone);
+ long zoneId = client.resolveZoneId(server.getUrl(), server.getPort(), server.getDnsApiKey(), zone.getName());
+ return client.deleteRecordsByNameAndType(server.getUrl(), server.getPort(), server.getDnsApiKey(), zoneId,
+ zone.getName(), record.getName(), record.getType().name());
+ }
+
+ @Override
+ public List listRecords(DnsServer server, DnsZone zone) throws DnsProviderException {
+ validateRequiredServerAndZoneFields(server, zone);
+ long zoneId = client.resolveZoneId(server.getUrl(), server.getPort(), server.getDnsApiKey(), zone.getName());
+ List rawRecords = client.listRecords(server.getUrl(), server.getPort(), server.getDnsApiKey(), zoneId);
+
+ Map aggregated = new LinkedHashMap<>();
+ for (JsonNode raw : rawRecords) {
+ String typeName = BunnyDnsClient.typeName(raw.path("Type").asInt(-1));
+ if (typeName == null) {
+ continue;
+ }
+ DnsRecord.RecordType type = DnsRecord.RecordType.fromString(typeName);
+ String fqdn = client.toFqdn(raw.path("Name").asText(""), zone.getName());
+ String content = BunnyDnsClient.formatContent(typeName, raw);
+ int ttl = raw.path("Ttl").asInt(0);
+
+ String key = fqdn + "|" + type.name();
+ DnsRecord dnsRecord = aggregated.get(key);
+ if (dnsRecord == null) {
+ dnsRecord = new DnsRecord(fqdn, type, new ArrayList<>(), ttl);
+ aggregated.put(key, dnsRecord);
+ }
+ dnsRecord.getContents().add(content);
+ }
+ return new ArrayList<>(aggregated.values());
+ }
+
+ @Override
+ public boolean dnsRecordExists(DnsServer server, DnsZone zone, String recordName, String recordType) throws DnsProviderException {
+ validateRequiredServerAndZoneFields(server, zone);
+ long zoneId = client.resolveZoneId(server.getUrl(), server.getPort(), server.getDnsApiKey(), zone.getName());
+ return !client.findRecordsByNameAndType(server.getUrl(), server.getPort(), server.getDnsApiKey(), zoneId,
+ zone.getName(), recordName, recordType).isEmpty();
+ }
+
+ @Override
+ public boolean dnsZoneExists(DnsServer server, DnsZone zone) {
+ return client.zoneExists(server.getUrl(), server.getPort(), server.getDnsApiKey(), zone.getName());
+ }
+
+ void validateRequiredServerAndZoneFields(DnsServer server, DnsZone zone) {
+ validateRequiredServerFields(server);
+ if (StringUtils.isBlank(zone.getName())) {
+ throw new IllegalArgumentException("Zone name cannot be empty");
+ }
+ }
+
+ void validateRequiredServerFields(DnsServer server) {
+ if (StringUtils.isBlank(server.getUrl())) {
+ throw new IllegalArgumentException("Bunny DNS API URL cannot be empty");
+ }
+ if (StringUtils.isBlank(server.getDnsApiKey())) {
+ throw new IllegalArgumentException("Bunny DNS API key cannot be empty");
+ }
+ }
+
+ @Override
+ public boolean configure(String name, Map params) {
+ if (client == null) {
+ client = new BunnyDnsClient();
+ }
+ return true;
+ }
+
+ @Override
+ public boolean stop() {
+ if (client != null) {
+ client.close();
+ }
+ return true;
+ }
+}
diff --git a/plugins/dns/bunny/src/main/resources/META-INF/cloudstack/bunny/module.properties b/plugins/dns/bunny/src/main/resources/META-INF/cloudstack/bunny/module.properties
new file mode 100644
index 000000000000..39af3ea22ddc
--- /dev/null
+++ b/plugins/dns/bunny/src/main/resources/META-INF/cloudstack/bunny/module.properties
@@ -0,0 +1,18 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+name=bunny
+parent=dns
diff --git a/plugins/dns/bunny/src/main/resources/META-INF/cloudstack/bunny/spring-dns-bunny-context.xml b/plugins/dns/bunny/src/main/resources/META-INF/cloudstack/bunny/spring-dns-bunny-context.xml
new file mode 100644
index 000000000000..d37107593895
--- /dev/null
+++ b/plugins/dns/bunny/src/main/resources/META-INF/cloudstack/bunny/spring-dns-bunny-context.xml
@@ -0,0 +1,31 @@
+
+
+
+
+
diff --git a/plugins/dns/bunny/src/test/java/org/apache/cloudstack/dns/bunny/BunnyDnsClientTest.java b/plugins/dns/bunny/src/test/java/org/apache/cloudstack/dns/bunny/BunnyDnsClientTest.java
new file mode 100644
index 000000000000..d664af13f360
--- /dev/null
+++ b/plugins/dns/bunny/src/test/java/org/apache/cloudstack/dns/bunny/BunnyDnsClientTest.java
@@ -0,0 +1,410 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.cloudstack.dns.bunny;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.apache.cloudstack.dns.exception.DnsAuthenticationException;
+import org.apache.cloudstack.dns.exception.DnsConflictException;
+import org.apache.cloudstack.dns.exception.DnsNotFoundException;
+import org.apache.cloudstack.dns.exception.DnsOperationException;
+import org.apache.http.StatusLine;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpUriRequest;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.stubbing.Answer;
+import org.springframework.test.util.ReflectionTestUtils;
+
+import com.fasterxml.jackson.databind.JsonNode;
+
+@RunWith(MockitoJUnitRunner.class)
+public class BunnyDnsClientTest {
+
+ BunnyDnsClient client;
+ CloseableHttpClient httpClientMock;
+
+ @Before
+ public void setUp() {
+ client = new BunnyDnsClient();
+ httpClientMock = mock(CloseableHttpClient.class);
+ ReflectionTestUtils.setField(client, "httpClient", httpClientMock);
+ }
+
+ private CloseableHttpResponse createResponse(int statusCode, String jsonBody) {
+ CloseableHttpResponse responseMock = mock(CloseableHttpResponse.class);
+ StatusLine statusLineMock = mock(StatusLine.class);
+ when(responseMock.getStatusLine()).thenReturn(statusLineMock);
+ when(statusLineMock.getStatusCode()).thenReturn(statusCode);
+
+ if (jsonBody != null) {
+ when(responseMock.getEntity()).thenReturn(new StringEntity(jsonBody, StandardCharsets.UTF_8));
+ }
+
+ return responseMock;
+ }
+
+ private void mockHttpResponse(int statusCode, String jsonBody) throws IOException {
+ CloseableHttpResponse response = createResponse(statusCode, jsonBody);
+ when(httpClientMock.execute(any(HttpUriRequest.class))).thenReturn(response);
+ }
+
+ @Test
+ public void testTypeCodeAndName() {
+ assertEquals(0, BunnyDnsClient.typeCode("A"));
+ assertEquals(4, BunnyDnsClient.typeCode("mx"));
+ assertEquals("SRV", BunnyDnsClient.typeName(8));
+ assertEquals(null, BunnyDnsClient.typeName(9)); // CAA - not modeled by CloudStack
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testTypeCodeUnsupportedThrows() {
+ BunnyDnsClient.typeCode("CAA");
+ }
+
+ @Test
+ public void testNormalizeDomain() {
+ assertEquals("example.com", client.normalizeDomain("Example.Com."));
+ assertEquals("example.com", client.normalizeDomain(" example.com "));
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testNormalizeDomainBlankThrows() {
+ client.normalizeDomain(" ");
+ }
+
+ @Test
+ public void testToBunnyRecordNameApex() {
+ assertEquals("", client.toBunnyRecordName("@", "example.com"));
+ assertEquals("", client.toBunnyRecordName("", "example.com"));
+ assertEquals("", client.toBunnyRecordName("example.com", "example.com"));
+ assertEquals("", client.toBunnyRecordName("example.com.", "example.com"));
+ }
+
+ @Test
+ public void testToBunnyRecordNameRelative() {
+ assertEquals("www", client.toBunnyRecordName("www", "example.com"));
+ assertEquals("www", client.toBunnyRecordName("WWW", "example.com"));
+ }
+
+ @Test
+ public void testToBunnyRecordNameStripsAbsoluteSuffix() {
+ assertEquals("www", client.toBunnyRecordName("www.example.com", "example.com"));
+ assertEquals("www", client.toBunnyRecordName("www.example.com.", "example.com"));
+ }
+
+ @Test
+ public void testToBunnyRecordNameAlreadyRelativeDotted() {
+ // Not absolute (no trailing dot) and doesn't match the zone suffix -> passed through as-is.
+ assertEquals("api.internal", client.toBunnyRecordName("api.internal", "example.com"));
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testToBunnyRecordNameNullThrows() {
+ client.toBunnyRecordName(null, "example.com");
+ }
+
+ @Test
+ public void testToFqdn() {
+ assertEquals("example.com", client.toFqdn("", "example.com"));
+ assertEquals("www.example.com", client.toFqdn("www", "example.com"));
+ }
+
+ @Test
+ public void testParseContentDefault() {
+ BunnyDnsClient.ContentFields fields = BunnyDnsClient.parseContent("A", "1.2.3.4");
+ assertEquals("1.2.3.4", fields.value);
+ assertEquals(null, fields.priority);
+ }
+
+ @Test
+ public void testParseContentMx() {
+ BunnyDnsClient.ContentFields fields = BunnyDnsClient.parseContent("MX", "10 mail.example.com.");
+ assertEquals("mail.example.com", fields.value);
+ assertEquals(Integer.valueOf(10), fields.priority);
+ assertEquals(null, fields.weight);
+ assertEquals(null, fields.port);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testParseContentMxInvalidThrows() {
+ BunnyDnsClient.parseContent("MX", "mail.example.com.");
+ }
+
+ @Test
+ public void testParseContentSrv() {
+ BunnyDnsClient.ContentFields fields = BunnyDnsClient.parseContent("SRV", "10 20 5061 sip.example.com.");
+ assertEquals("sip.example.com", fields.value);
+ assertEquals(Integer.valueOf(10), fields.priority);
+ assertEquals(Integer.valueOf(20), fields.weight);
+ assertEquals(Integer.valueOf(5061), fields.port);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testParseContentSrvInvalidThrows() {
+ BunnyDnsClient.parseContent("SRV", "10 20 sip.example.com.");
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testParseContentBlankThrows() {
+ BunnyDnsClient.parseContent("A", " ");
+ }
+
+ @Test
+ public void testFormatContentMx() {
+ com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
+ com.fasterxml.jackson.databind.node.ObjectNode record = mapper.createObjectNode();
+ record.put("Value", "mail.example.com");
+ record.put("Priority", 10);
+ assertEquals("10 mail.example.com.", BunnyDnsClient.formatContent("MX", record));
+ }
+
+ @Test
+ public void testFormatContentSrv() {
+ com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
+ com.fasterxml.jackson.databind.node.ObjectNode record = mapper.createObjectNode();
+ record.put("Value", "sip.example.com");
+ record.put("Priority", 10);
+ record.put("Weight", 20);
+ record.put("Port", 5061);
+ assertEquals("10 20 5061 sip.example.com.", BunnyDnsClient.formatContent("SRV", record));
+ }
+
+ @Test
+ public void testFormatContentDefault() {
+ com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
+ com.fasterxml.jackson.databind.node.ObjectNode record = mapper.createObjectNode();
+ record.put("Value", "1.2.3.4");
+ assertEquals("1.2.3.4", BunnyDnsClient.formatContent("A", record));
+ }
+
+ @Test
+ public void testResolveZoneIdFound() throws Exception {
+ mockHttpResponse(200, "{\"Items\":[{\"Id\":42,\"Domain\":\"example.com\"}],\"HasMoreItems\":false}");
+ long zoneId = client.resolveZoneId("https://api.bunny.net", null, "key", "example.com");
+ assertEquals(42L, zoneId);
+ }
+
+ @Test(expected = DnsNotFoundException.class)
+ public void testResolveZoneIdNotFound() throws Exception {
+ mockHttpResponse(200, "{\"Items\":[{\"Id\":42,\"Domain\":\"other.com\"}],\"HasMoreItems\":false}");
+ client.resolveZoneId("https://api.bunny.net", null, "key", "example.com");
+ }
+
+ @Test
+ public void testResolveZoneIdPaginates() throws Exception {
+ when(httpClientMock.execute(any(HttpUriRequest.class))).thenAnswer(new Answer() {
+ @Override
+ public CloseableHttpResponse answer(InvocationOnMock invocation) {
+ HttpUriRequest request = invocation.getArgument(0);
+ if (request.getURI().getQuery().contains("page=1")) {
+ return createResponse(200, "{\"Items\":[{\"Id\":1,\"Domain\":\"other.com\"}],\"HasMoreItems\":true}");
+ }
+ return createResponse(200, "{\"Items\":[{\"Id\":42,\"Domain\":\"example.com\"}],\"HasMoreItems\":false}");
+ }
+ });
+ long zoneId = client.resolveZoneId("https://api.bunny.net", null, "key", "example.com");
+ assertEquals(42L, zoneId);
+ }
+
+ @Test
+ public void testZoneExistsTrue() throws Exception {
+ mockHttpResponse(200, "{\"Items\":[{\"Id\":42,\"Domain\":\"example.com\"}],\"HasMoreItems\":false}");
+ assertTrue(client.zoneExists("https://api.bunny.net", null, "key", "example.com"));
+ }
+
+ @Test
+ public void testZoneExistsFalse() throws Exception {
+ mockHttpResponse(200, "{\"Items\":[],\"HasMoreItems\":false}");
+ assertFalse(client.zoneExists("https://api.bunny.net", null, "key", "example.com"));
+ }
+
+ @Test
+ public void testCreateZoneReturnsIdFromResponse() throws Exception {
+ mockHttpResponse(201, "{\"Id\":99}");
+ long zoneId = client.createZone("https://api.bunny.net", null, "key", "example.com");
+ assertEquals(99L, zoneId);
+ }
+
+ @Test
+ public void testCreateZoneFallsBackToLookupWhenResponseHasNoId() throws Exception {
+ when(httpClientMock.execute(any(HttpUriRequest.class))).thenAnswer(new Answer() {
+ @Override
+ public CloseableHttpResponse answer(InvocationOnMock invocation) {
+ HttpUriRequest request = invocation.getArgument(0);
+ if (request.getMethod().equals("POST")) {
+ return createResponse(201, null);
+ }
+ return createResponse(200, "{\"Items\":[{\"Id\":77,\"Domain\":\"example.com\"}],\"HasMoreItems\":false}");
+ }
+ });
+ long zoneId = client.createZone("https://api.bunny.net", null, "key", "example.com");
+ assertEquals(77L, zoneId);
+ }
+
+ @Test
+ public void testDeleteZoneDeletesWhenFound() throws Exception {
+ when(httpClientMock.execute(any(HttpUriRequest.class))).thenAnswer(new Answer() {
+ @Override
+ public CloseableHttpResponse answer(InvocationOnMock invocation) {
+ HttpUriRequest request = invocation.getArgument(0);
+ if (request.getMethod().equals("GET")) {
+ return createResponse(200, "{\"Items\":[{\"Id\":42,\"Domain\":\"example.com\"}],\"HasMoreItems\":false}");
+ }
+ return createResponse(204, null);
+ }
+ });
+ client.deleteZone("https://api.bunny.net", null, "key", "example.com");
+ }
+
+ @Test
+ public void testDeleteZoneNoOpWhenAlreadyGone() throws Exception {
+ mockHttpResponse(200, "{\"Items\":[],\"HasMoreItems\":false}");
+ client.deleteZone("https://api.bunny.net", null, "key", "example.com");
+ // No exception means success; DELETE is never issued since resolveZoneId throws DnsNotFoundException.
+ }
+
+ @Test
+ public void testAddRecord() throws Exception {
+ mockHttpResponse(201, "{\"Id\":1}");
+ String fqdn = client.addRecord("https://api.bunny.net", null, "key", 42L, "example.com", "www", "A", 300, "1.2.3.4");
+ assertEquals("www.example.com", fqdn);
+ }
+
+ @Test
+ public void testFindRecordsByNameAndType() throws Exception {
+ mockHttpResponse(200, "{\"Items\":[{\"Id\":1,\"Name\":\"www\",\"Type\":0},{\"Id\":2,\"Name\":\"other\",\"Type\":0}],\"HasMoreItems\":false}");
+ List matches = client.findRecordsByNameAndType("https://api.bunny.net", null, "key", 42L, "example.com", "www", "A");
+ assertEquals(1, matches.size());
+ assertEquals(1, matches.get(0).path("Id").asInt());
+ }
+
+ @Test
+ public void testDeleteRecordsByNameAndType() throws Exception {
+ when(httpClientMock.execute(any(HttpUriRequest.class))).thenAnswer(new Answer() {
+ @Override
+ public CloseableHttpResponse answer(InvocationOnMock invocation) {
+ HttpUriRequest request = invocation.getArgument(0);
+ if (request.getMethod().equals("GET")) {
+ return createResponse(200, "{\"Items\":[{\"Id\":1,\"Name\":\"www\",\"Type\":0}],\"HasMoreItems\":false}");
+ }
+ return createResponse(204, null);
+ }
+ });
+ String fqdn = client.deleteRecordsByNameAndType("https://api.bunny.net", null, "key", 42L, "example.com", "www", "A");
+ assertEquals("www.example.com", fqdn);
+ }
+
+ @Test
+ public void testReplaceRecordsKeepsMatchingDeletesStaleAddsMissing() throws Exception {
+ List requests = new ArrayList<>();
+ when(httpClientMock.execute(any(HttpUriRequest.class))).thenAnswer(invocation -> {
+ HttpUriRequest request = invocation.getArgument(0);
+ if (request.getMethod().equals("GET")) {
+ return createResponse(200, "{\"Items\":[{\"Id\":1,\"Name\":\"www\",\"Type\":0,\"Ttl\":300,\"Value\":\"1.2.3.4\"},"
+ + "{\"Id\":2,\"Name\":\"www\",\"Type\":0,\"Ttl\":300,\"Value\":\"9.9.9.9\"}],\"HasMoreItems\":false}");
+ }
+ requests.add(request.getMethod() + " " + request.getURI().getPath());
+ return createResponse(request.getMethod().equals("PUT") ? 201 : 204, null);
+ });
+ String fqdn = client.replaceRecords("https://api.bunny.net", null, "key", 42L, "example.com", "www", "A", 300,
+ Arrays.asList("1.2.3.4", "5.6.7.8"));
+ assertEquals("www.example.com", fqdn);
+ assertEquals(Arrays.asList("DELETE /dnszone/42/records/2", "PUT /dnszone/42/records"), requests);
+ }
+
+ @Test
+ public void testHostnameContentRoundTripsTrailingDot() {
+ assertEquals("target.example.com", BunnyDnsClient.parseContent("CNAME", "target.example.com.").value);
+ com.fasterxml.jackson.databind.node.ObjectNode record = new com.fasterxml.jackson.databind.ObjectMapper().createObjectNode();
+ record.put("Value", "target.example.com");
+ assertEquals("target.example.com.", BunnyDnsClient.formatContent("CNAME", record));
+ }
+
+ @Test
+ public void testListRecordsPaginates() throws Exception {
+ when(httpClientMock.execute(any(HttpUriRequest.class))).thenAnswer(new Answer() {
+ @Override
+ public CloseableHttpResponse answer(InvocationOnMock invocation) {
+ HttpUriRequest request = invocation.getArgument(0);
+ if (request.getURI().getQuery().contains("page=1")) {
+ return createResponse(200, "{\"Items\":[{\"Id\":1,\"Name\":\"www\",\"Type\":0}],\"HasMoreItems\":true}");
+ }
+ return createResponse(200, "{\"Items\":[{\"Id\":2,\"Name\":\"mail\",\"Type\":4}],\"HasMoreItems\":false}");
+ }
+ });
+ List records = client.listRecords("https://api.bunny.net", null, "key", 42L);
+ assertEquals(2, records.size());
+ }
+
+ @Test(expected = DnsNotFoundException.class)
+ public void testExecuteThrowsNotFound() throws Exception {
+ mockHttpResponse(404, "Not Found");
+ client.resolveZoneId("https://api.bunny.net", null, "key", "example.com");
+ }
+
+ @Test(expected = DnsAuthenticationException.class)
+ public void testExecuteThrowsAuthError() throws Exception {
+ mockHttpResponse(401, "Unauthorized");
+ client.validateAccess("https://api.bunny.net", null, "key");
+ }
+
+ @Test(expected = DnsConflictException.class)
+ public void testExecuteThrowsConflictError() throws Exception {
+ mockHttpResponse(409, "Conflict");
+ client.validateAccess("https://api.bunny.net", null, "key");
+ }
+
+ @Test(expected = DnsOperationException.class)
+ public void testExecuteThrowsUnexpectedStatus() throws Exception {
+ mockHttpResponse(500, "Server Error");
+ client.validateAccess("https://api.bunny.net", null, "key");
+ }
+
+ @Test
+ public void testCloseSucceeds() throws Exception {
+ CloseableHttpClient mockClient = mock(CloseableHttpClient.class);
+ ReflectionTestUtils.setField(client, "httpClient", mockClient);
+ client.close();
+ org.mockito.Mockito.verify(mockClient).close();
+ }
+
+ @Test
+ public void testCloseSwallowsIOException() throws Exception {
+ CloseableHttpClient mockClient = mock(CloseableHttpClient.class);
+ org.mockito.Mockito.doThrow(new IOException("connection reset")).when(mockClient).close();
+ ReflectionTestUtils.setField(client, "httpClient", mockClient);
+ client.close(); // must NOT throw
+ }
+}
diff --git a/plugins/dns/bunny/src/test/java/org/apache/cloudstack/dns/bunny/BunnyDnsProviderTest.java b/plugins/dns/bunny/src/test/java/org/apache/cloudstack/dns/bunny/BunnyDnsProviderTest.java
new file mode 100644
index 000000000000..08080417778f
--- /dev/null
+++ b/plugins/dns/bunny/src/test/java/org/apache/cloudstack/dns/bunny/BunnyDnsProviderTest.java
@@ -0,0 +1,290 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.cloudstack.dns.bunny;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+
+import org.apache.cloudstack.dns.DnsProviderType;
+import org.apache.cloudstack.dns.DnsRecord;
+import org.apache.cloudstack.dns.DnsRecord.RecordType;
+import org.apache.cloudstack.dns.DnsServer;
+import org.apache.cloudstack.dns.DnsZone;
+import org.apache.cloudstack.dns.exception.DnsProviderException;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.springframework.test.util.ReflectionTestUtils;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+
+@RunWith(MockitoJUnitRunner.class)
+public class BunnyDnsProviderTest {
+
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+
+ private BunnyDnsProvider provider;
+ private BunnyDnsClient clientMock;
+ private DnsServer serverMock;
+ private DnsZone zoneMock;
+
+ @Before
+ public void setUp() {
+ provider = new BunnyDnsProvider();
+ clientMock = mock(BunnyDnsClient.class);
+ serverMock = mock(DnsServer.class);
+ zoneMock = mock(DnsZone.class);
+ ReflectionTestUtils.setField(provider, "client", clientMock);
+
+ when(serverMock.getUrl()).thenReturn("https://api.bunny.net");
+ when(serverMock.getDnsApiKey()).thenReturn("secret");
+ when(serverMock.getPort()).thenReturn(null);
+
+ when(zoneMock.getName()).thenReturn("example.com");
+ }
+
+ @Test
+ public void testGetProviderType() {
+ assertEquals(DnsProviderType.BunnyDNS, provider.getProviderType());
+ }
+
+ @Test
+ public void testConfigureCreatesClientWhenNull() {
+ BunnyDnsProvider freshProvider = new BunnyDnsProvider();
+ boolean result = freshProvider.configure("test", new HashMap<>());
+ assertTrue(result);
+ assertNotNull(ReflectionTestUtils.getField(freshProvider, "client"));
+ }
+
+ @Test
+ public void testConfigureDoesNotReplaceExistingClient() {
+ BunnyDnsClient existingClient = mock(BunnyDnsClient.class);
+ ReflectionTestUtils.setField(provider, "client", existingClient);
+
+ boolean result = provider.configure("test", new HashMap<>());
+
+ assertTrue(result);
+ assertEquals(existingClient, ReflectionTestUtils.getField(provider, "client"));
+ }
+
+ @Test
+ public void testStopClosesClient() {
+ boolean result = provider.stop();
+ assertTrue(result);
+ verify(clientMock, times(1)).close();
+ }
+
+ @Test
+ public void testStopWithNullClientSucceeds() {
+ ReflectionTestUtils.setField(provider, "client", null);
+ boolean result = provider.stop();
+ assertTrue(result);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testValidateServerFieldsNullUrl() {
+ when(serverMock.getUrl()).thenReturn(null);
+ provider.validateRequiredServerFields(serverMock);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testValidateServerFieldsNullApiKey() {
+ when(serverMock.getDnsApiKey()).thenReturn(null);
+ provider.validateRequiredServerFields(serverMock);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testValidateServerAndZoneFieldsBlankZoneName() {
+ when(zoneMock.getName()).thenReturn(" ");
+ provider.validateRequiredServerAndZoneFields(serverMock, zoneMock);
+ }
+
+ @Test
+ public void testValidateDelegatesToClient() throws Exception {
+ provider.validate(serverMock);
+ verify(clientMock).validateAccess("https://api.bunny.net", null, "secret");
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testValidateThrowsWhenServerUrlBlank() throws Exception {
+ when(serverMock.getUrl()).thenReturn("");
+ provider.validate(serverMock);
+ }
+
+ @Test
+ public void testValidateAndResolveServerReturnsNull() throws Exception {
+ String result = provider.validateAndResolveServer(serverMock);
+ assertEquals(null, result);
+ verify(clientMock).validateAccess("https://api.bunny.net", null, "secret");
+ }
+
+ @Test
+ public void testProvisionZoneDelegatesToClient() throws DnsProviderException {
+ when(clientMock.createZone("https://api.bunny.net", null, "secret", "example.com")).thenReturn(42L);
+ String zoneId = provider.provisionZone(serverMock, zoneMock);
+ assertEquals("42", zoneId);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testProvisionZoneThrowsWhenZoneNameBlank() throws DnsProviderException {
+ when(zoneMock.getName()).thenReturn(null);
+ provider.provisionZone(serverMock, zoneMock);
+ }
+
+ @Test
+ public void testDeleteZoneDelegatesToClient() throws DnsProviderException {
+ provider.deleteZone(serverMock, zoneMock);
+ verify(clientMock).deleteZone("https://api.bunny.net", null, "secret", "example.com");
+ }
+
+ @Test
+ public void testUpdateZoneResolvesZoneAsNoOp() throws DnsProviderException {
+ when(clientMock.resolveZoneId("https://api.bunny.net", null, "secret", "example.com")).thenReturn(42L);
+ provider.updateZone(serverMock, zoneMock);
+ verify(clientMock).resolveZoneId("https://api.bunny.net", null, "secret", "example.com");
+ }
+
+ @Test
+ public void testAddAndUpdateRecordReplaceRecords() throws DnsProviderException {
+ List contents = Arrays.asList("1.2.3.4", "5.6.7.8");
+ DnsRecord record = new DnsRecord("www", RecordType.A, contents, 300);
+ when(clientMock.resolveZoneId(anyString(), eq(null), anyString(), anyString())).thenReturn(42L);
+ when(clientMock.replaceRecords("https://api.bunny.net", null, "secret", 42L, "example.com", "www", "A", 300, contents))
+ .thenReturn("www.example.com");
+
+ assertEquals("www.example.com", provider.addRecord(serverMock, zoneMock, record));
+ assertEquals("www.example.com", provider.updateRecord(serverMock, zoneMock, record));
+ verify(clientMock, times(2)).replaceRecords("https://api.bunny.net", null, "secret", 42L, "example.com", "www", "A", 300, contents);
+ }
+
+ @Test
+ public void testDeleteRecordDelegatesToClient() throws DnsProviderException {
+ DnsRecord record = new DnsRecord("old", RecordType.CNAME, Arrays.asList("target.com"), 600);
+ when(clientMock.resolveZoneId(anyString(), eq(null), anyString(), anyString())).thenReturn(42L);
+ when(clientMock.deleteRecordsByNameAndType(anyString(), eq(null), anyString(), anyLong(), anyString(), anyString(), anyString()))
+ .thenReturn("old.example.com");
+
+ String result = provider.deleteRecord(serverMock, zoneMock, record);
+
+ assertEquals("old.example.com", result);
+ verify(clientMock).deleteRecordsByNameAndType("https://api.bunny.net", null, "secret", 42L, "example.com", "old", "CNAME");
+ }
+
+ @Test
+ public void testListRecordsAggregatesByNameAndType() throws DnsProviderException {
+ ObjectNode aRecord1 = MAPPER.createObjectNode();
+ aRecord1.put("Id", 1);
+ aRecord1.put("Name", "www");
+ aRecord1.put("Type", 0); // A
+ aRecord1.put("Ttl", 300);
+ aRecord1.put("Value", "1.2.3.4");
+
+ ObjectNode aRecord2 = MAPPER.createObjectNode();
+ aRecord2.put("Id", 2);
+ aRecord2.put("Name", "www");
+ aRecord2.put("Type", 0); // A
+ aRecord2.put("Ttl", 300);
+ aRecord2.put("Value", "5.6.7.8");
+
+ when(clientMock.resolveZoneId(anyString(), eq(null), anyString(), anyString())).thenReturn(42L);
+ when(clientMock.listRecords(anyString(), eq(null), anyString(), anyLong()))
+ .thenReturn(Arrays.asList(aRecord1, aRecord2));
+ when(clientMock.toFqdn("www", "example.com")).thenReturn("www.example.com");
+
+ List result = provider.listRecords(serverMock, zoneMock);
+
+ assertEquals(1, result.size());
+ DnsRecord record = result.get(0);
+ assertEquals("www.example.com", record.getName());
+ assertEquals(RecordType.A, record.getType());
+ assertEquals(300, record.getTtl());
+ assertEquals(Arrays.asList("1.2.3.4", "5.6.7.8"), record.getContents());
+ }
+
+ @Test
+ public void testListRecordsSkipsUnsupportedBunnyTypes() throws DnsProviderException {
+ ObjectNode caaRecord = MAPPER.createObjectNode();
+ caaRecord.put("Id", 1);
+ caaRecord.put("Name", "www");
+ caaRecord.put("Type", 9); // CAA - not modeled by DnsRecord.RecordType
+ caaRecord.put("Ttl", 300);
+ caaRecord.put("Value", "0 issue \"letsencrypt.org\"");
+
+ when(clientMock.resolveZoneId(anyString(), eq(null), anyString(), anyString())).thenReturn(42L);
+ when(clientMock.listRecords(anyString(), eq(null), anyString(), anyLong()))
+ .thenReturn(Collections.singletonList(caaRecord));
+
+ List result = provider.listRecords(serverMock, zoneMock);
+ assertTrue(result.isEmpty());
+ }
+
+ @Test
+ public void testListRecordsReturnsEmptyListWhenClientReturnsEmpty() throws DnsProviderException {
+ when(clientMock.resolveZoneId(anyString(), eq(null), anyString(), anyString())).thenReturn(42L);
+ when(clientMock.listRecords(anyString(), eq(null), anyString(), anyLong()))
+ .thenReturn(Collections.emptyList());
+
+ List result = provider.listRecords(serverMock, zoneMock);
+ assertNotNull(result);
+ assertTrue(result.isEmpty());
+ }
+
+ @Test
+ public void testDnsRecordExistsTrue() throws DnsProviderException {
+ ObjectNode record = MAPPER.createObjectNode();
+ record.put("Id", 1);
+ when(clientMock.resolveZoneId(anyString(), eq(null), anyString(), anyString())).thenReturn(42L);
+ when(clientMock.findRecordsByNameAndType(anyString(), eq(null), anyString(), anyLong(), anyString(), anyString(), anyString()))
+ .thenReturn(Collections.singletonList(record));
+
+ assertTrue(provider.dnsRecordExists(serverMock, zoneMock, "www", "A"));
+ }
+
+ @Test
+ public void testDnsRecordExistsFalse() throws DnsProviderException {
+ when(clientMock.resolveZoneId(anyString(), eq(null), anyString(), anyString())).thenReturn(42L);
+ when(clientMock.findRecordsByNameAndType(anyString(), eq(null), anyString(), anyLong(), anyString(), anyString(), anyString()))
+ .thenReturn(Collections.emptyList());
+
+ assertFalse(provider.dnsRecordExists(serverMock, zoneMock, "www", "A"));
+ }
+
+ @Test
+ public void testDnsZoneExistsDelegatesToClient() {
+ when(clientMock.zoneExists("https://api.bunny.net", null, "secret", "example.com")).thenReturn(true);
+ assertTrue(provider.dnsZoneExists(serverMock, zoneMock));
+ }
+}
diff --git a/plugins/pom.xml b/plugins/pom.xml
index 92768827f658..5464be124dfe 100755
--- a/plugins/pom.xml
+++ b/plugins/pom.xml
@@ -158,6 +158,7 @@
user-two-factor-authenticators/totp
user-two-factor-authenticators/static-pin
dns/powerdns
+ dns/bunny
diff --git a/ui/src/views/network/dns/AddDnsServer.vue b/ui/src/views/network/dns/AddDnsServer.vue
index 054b0e37863a..702648357b30 100644
--- a/ui/src/views/network/dns/AddDnsServer.vue
+++ b/ui/src/views/network/dns/AddDnsServer.vue
@@ -212,6 +212,14 @@ export default {
}
this.fetchProviders()
},
+ watch: {
+ 'form.provider' (provider) {
+ if (provider === 'BunnyDNS') {
+ this.form.port = 443
+ this.form.url = this.form.url || 'https://api.bunny.net'
+ }
+ }
+ },
methods: {
async handleSubmit () {
if (this.loading) return