1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217
|
import json
import logging
from datetime import datetime
from hashlib import sha256
from pathlib import Path
from typing import List, Optional, Union
from urllib.parse import urljoin
import dns
import requests
from pkb_client.client import BindFile
from pkb_client.client.dns import (
DNS_RECORDS_WITH_PRIORITY,
DNSRecord,
DNSRecordType,
DNSRestoreMode,
)
from pkb_client.client.dnssec import DNSSECRecord
from pkb_client.client.domain import (
DomainInfo,
DomainAvailability,
DomainCheckRateLimit,
DomainPrice,
GlueRecord,
)
from pkb_client.client.forwarding import URLForwarding, URLForwardingType
from pkb_client.client.ssl_cert import SSLCertBundle
API_ENDPOINT = "https://api.porkbun.com/api/json/v3/"
logger = logging.getLogger("pkb_client")
logging.basicConfig(level=logging.INFO)
class PKBClientException(Exception):
def __init__(self, status, message):
super().__init__(f"{status}: {message}")
class PKBClient:
"""
API client for Porkbun.
"""
default_ttl: int = 300
def __init__(
self,
api_key: Optional[str] = None,
secret_api_key: Optional[str] = None,
api_endpoint: str = API_ENDPOINT,
debug: bool = False,
) -> None:
"""
Creates a new PKBClient object.
:param api_key: the API key used for Porkbun API calls
:param secret_api_key: the API secret used for Porkbun API calls
:param api_endpoint: the endpoint of the Porkbun API.
:param debug: boolean to enable debug logging
"""
self.api_key = api_key
self.secret_api_key = secret_api_key
self.api_endpoint = api_endpoint
self.debug = debug
if self.debug:
logger.setLevel(logging.DEBUG)
def _get_auth_request_json(self) -> dict:
"""
Get the request json for the authentication of the Porkbun API calls.
:return: the request json for the authentication of the Porkbun API calls
"""
if self.api_key is None or self.secret_api_key is None:
raise ValueError("api_key and secret_api_key must be set")
return {"apikey": self.api_key, "secretapikey": self.secret_api_key}
def ping(self) -> str:
"""
API ping method: get the current public ip address of the requesting system; can also be used for auth checking.
See https://api.porkbun.com/api/json/v3/documentation#Authentication for more info.
:return: the current public ip address of the requesting system
"""
url = urljoin(self.api_endpoint, "ping")
req_json = self._get_auth_request_json()
r = requests.post(url=url, json=req_json)
if r.status_code == 200:
return json.loads(r.text).get("yourIp", None)
else:
response_json = json.loads(r.text)
raise PKBClientException(
response_json.get("status", "Unknown status"),
response_json.get("message", "Unknown message"),
)
def create_dns_record(
self,
domain: str,
record_type: DNSRecordType,
content: str,
name: Optional[str] = None,
ttl: int = default_ttl,
prio: Optional[int] = None,
) -> str:
"""
API DNS create method: create a new DNS record for given domain.
See https://api.porkbun.com/api/json/v3/documentation#DNS%20Create%20Record for more info.
:param domain: the domain for which the DNS record should be created
:param record_type: the type of the new DNS record
:param content: the content of the new DNS record
:param name: the subdomain for which the new DNS record entry should apply; the * can be used for a
wildcard DNS record; if not used, then a DNS record for the root domain will be created
:param ttl: the time to live in seconds of the new DNS record; have to be between 300 and 86400
:param prio: the priority of the new DNS record (only records of type MX and SRV) otherwise None
:return: the id of the new created DNS record
"""
if ttl > 86400 or ttl < self.default_ttl:
raise ValueError(f"ttl must be between {self.default_ttl} and 86400")
if prio is not None and record_type not in DNS_RECORDS_WITH_PRIORITY:
raise ValueError(
f"Priority can only be set for {DNS_RECORDS_WITH_PRIORITY}"
)
url = urljoin(self.api_endpoint, f"dns/create/{domain}")
req_json = {
**self._get_auth_request_json(),
"name": name,
"type": record_type.value,
"content": content,
"ttl": ttl,
"prio": prio,
}
r = requests.post(url=url, json=req_json)
if r.status_code == 200:
return str(json.loads(r.text).get("id", None))
else:
response_json = json.loads(r.text)
raise PKBClientException(
response_json.get("status", "Unknown status"),
response_json.get("message", "Unknown message"),
)
def update_dns_record(
self,
domain: str,
record_id: str,
record_type: DNSRecordType,
content: str,
name: Optional[str] = None,
ttl: int = default_ttl,
prio: Optional[int] = None,
) -> bool:
"""
API DNS edit method: edit an existing DNS record specified by the id for a given domain.
See https://api.porkbun.com/api/json/v3/documentation#DNS%20Edit%20Record for more info.
:param domain: the domain for which the DNS record should be edited
:param record_id: the id of the DNS record which should be edited
:param record_type: the new type of the DNS record
:param content: the new content of the DNS record
:param name: the new value of the subdomain for which the DNS record should apply; the * can be used for a
wildcard DNS record; if not set, the record will be set for the record domain
:param ttl: the new time to live in seconds of the DNS record, have to be between 300 and 86400
:param prio: the priority of the new DNS record (only records of type MX and SRV) otherwise None
:return: True if the editing was successful
"""
if ttl > 86400 or ttl < self.default_ttl:
raise ValueError(f"ttl must be between {self.default_ttl} and 86400")
if prio is not None and record_type not in DNS_RECORDS_WITH_PRIORITY:
raise ValueError(
f"Priority can only be set for {DNS_RECORDS_WITH_PRIORITY}"
)
url = urljoin(self.api_endpoint, f"dns/edit/{domain}/{record_id}")
req_json = {
**self._get_auth_request_json(),
"name": name,
"type": record_type.value,
"content": content,
"ttl": ttl,
"prio": prio,
}
r = requests.post(url=url, json=req_json)
if r.status_code == 200:
return True
else:
response_json = json.loads(r.text)
raise PKBClientException(
response_json.get("status", "Unknown status"),
response_json.get("message", "Unknown message"),
)
def update_all_dns_records(
self,
domain: str,
record_type: DNSRecordType,
subdomain: str,
content: str,
ttl: int = default_ttl,
prio: Optional[int] = None,
) -> bool:
"""
API DNS edit method: edit all existing DNS record matching the domain, record type and subdomain.
See https://api.porkbun.com/api/json/v3/documentation#DNS%20Edit%20Record%20by%20Domain,%20Subdomain%20and%20Type for more info.
:param domain: the domain for which the DNS record should be edited
:param record_type: the type of the DNS record
:param subdomain: the subdomain of the DNS record can be empty string for root domain
:param content: the new content of the DNS record
:param ttl: the new time to live in seconds of the DNS record, have to be between 300 and 86400
:param prio: the priority of the new DNS record (only records of type MX and SRV) otherwise None
:return: True if the editing was successful
"""
if ttl > 86400 or ttl < self.default_ttl:
raise ValueError(f"ttl must be between {self.default_ttl} and 86400")
if prio is not None and record_type not in DNS_RECORDS_WITH_PRIORITY:
raise ValueError(
f"Priority can only be set for {DNS_RECORDS_WITH_PRIORITY}"
)
url = urljoin(
self.api_endpoint, f"dns/editByNameType/{domain}/{record_type}/{subdomain}"
)
req_json = {
**self._get_auth_request_json(),
"type": record_type.value,
"content": content,
"ttl": ttl,
"prio": prio,
}
r = requests.post(url=url, json=req_json)
if r.status_code == 200:
return True
else:
response_json = json.loads(r.text)
raise PKBClientException(
response_json.get("status", "Unknown status"),
response_json.get("message", "Unknown message"),
)
def delete_dns_record(self, domain: str, record_id: str) -> bool:
"""
API DNS delete method: delete an existing DNS record specified by the id for a given domain.
See https://api.porkbun.com/api/json/v3/documentation#DNS%20Delete%20Record for more info.
:param domain: the domain for which the DNS record should be deleted
:param record_id: the id of the DNS record which should be deleted
:return: True if the deletion was successful
"""
url = urljoin(self.api_endpoint, f"dns/delete/{domain}/{record_id}")
req_json = self._get_auth_request_json()
r = requests.post(url=url, json=req_json)
if r.status_code == 200:
return True
else:
response_json = json.loads(r.text)
raise PKBClientException(
response_json.get("status", "Unknown status"),
response_json.get("message", "Unknown message"),
)
def delete_all_dns_records(
self, domain: str, record_type: DNSRecordType, subdomain: str
) -> bool:
"""
API DNS delete method: delete all existing DNS record matching the domain, record type and subdomain.
See https://api.porkbun.com/api/json/v3/documentation#DNS%20Delete%20Records%20by%20Domain,%20Subdomain%20and%20Type for more info.
:param domain: the domain for which the DNS record should be deleted
:param record_type: the type of the DNS record
:param subdomain: the subdomain of the DNS record can be empty string for root domain
:return: True if the deletion was successful
"""
url = urljoin(
self.api_endpoint,
f"dns/deleteByNameType/{domain}/{record_type}/{subdomain}",
)
req_json = self._get_auth_request_json()
r = requests.post(url=url, json=req_json)
if r.status_code == 200:
return True
else:
response_json = json.loads(r.text)
raise PKBClientException(
response_json.get("status", "Unknown status"),
response_json.get("message", "Unknown message"),
)
def get_dns_records(
self, domain, record_id: Optional[str] = None
) -> List[DNSRecord]:
"""
API DNS retrieve method: retrieve all DNS records for given domain if no record id is specified.
Otherwise, retrieve the DNS record of the specified domain with the given record id.
See https://api.porkbun.com/api/json/v3/documentation#DNS%20Retrieve%20Records for more info.
:param domain: the domain for which the DNS records should be retrieved
:param record_id: the id of the DNS record which should be retrieved
:return: list of DNSRecords objects
"""
if record_id is None:
url = urljoin(self.api_endpoint, f"dns/retrieve/{domain}")
else:
url = urljoin(self.api_endpoint, f"dns/retrieve/{domain}/{record_id}")
req_json = self._get_auth_request_json()
r = requests.post(url=url, json=req_json)
if r.status_code == 200:
return [
DNSRecord.from_dict(record)
for record in json.loads(r.text).get("records", [])
]
else:
response_json = json.loads(r.text)
raise PKBClientException(
response_json.get("status", "Unknown status"),
response_json.get("message", "Unknown message"),
)
def get_all_dns_records(
self, domain: str, record_type: DNSRecordType, subdomain: str
) -> List[DNSRecord]:
"""
API DNS retrieve method: retrieve all DNS records matching the domain, record type and subdomain.
See https://api.porkbun.com/api/json/v3/documentation#DNS%20Retrieve%20Records%20by%20Domain,%20Subdomain%20and%20Type for more info.
:param domain: the domain for which the DNS records should be retrieved
:param record_type: the type of the DNS records
:param subdomain: the subdomain of the DNS records can be empty string for root domain
:return: list of DNSRecords objects
"""
url = urljoin(
self.api_endpoint,
f"dns/retrieveByNameType/{domain}/{record_type}/{subdomain}",
)
req_json = self._get_auth_request_json()
r = requests.post(url=url, json=req_json)
if r.status_code == 200:
return [
DNSRecord.from_dict(record)
for record in json.loads(r.text).get("records", [])
]
else:
response_json = json.loads(r.text)
raise PKBClientException(
response_json.get("status", "Unknown status"),
response_json.get("message", "Unknown message"),
)
def export_dns_records(self, domain: str, filepath: Union[Path, str]) -> bool:
"""
Export all DNS record from the given domain to a json file.
This method does not represent a Porkbun API method.
DNS records with all custom fields like notes are exported.
:param domain: the domain for which the DNS record should be retrieved and saved
:param filepath: the filepath where to save the exported DNS records
:return: True if everything went well
"""
filepath = Path(filepath)
logger.debug("retrieve current DNS records...")
dns_records = self.get_dns_records(domain)
logger.debug("save DNS records to {} ...".format(filepath))
# merge the single DNS records into one single dict with the record id as key
dns_records_dict = dict()
for record in dns_records:
dns_records_dict[record.id] = record
if filepath.exists():
logger.warning("file already exists, overwriting...")
with open(filepath, "w") as f:
json.dump(dns_records_dict, f, default=lambda o: o.__dict__, indent=4)
logger.info("export finished")
return True
def export_bind_dns_records(self, domain: str, filepath: Union[Path, str]) -> bool:
"""
Export all DNS record from the given domain to a BIND file.
This method does not represent a Porkbun API method.
Porkbun DNS record notes are exported as comments.
:param domain: the domain for which the DNS record should be retrieved and saved
:param filepath: the filepath where to save the exported DNS records
:return: True if everything went well
"""
filepath = Path(filepath)
logger.debug("retrieve current DNS records...")
dns_records = self.get_dns_records(domain)
logger.debug("save DNS records to {} ...".format(filepath))
# merge the single DNS records into one single dict with the record id as key
dns_records_dict = dict()
for record in dns_records:
dns_records_dict[record.id] = record
if filepath.exists():
logger.warning("file already exists, overwriting...")
# domain header
bind_file_content = f"$ORIGIN {domain}."
# SOA record
soa_records = dns.resolver.resolve(domain, "SOA")
if soa_records:
soa_record = soa_records[0]
bind_file_content += f"\n@ IN SOA {soa_record.mname} {soa_record.rname} ({soa_record.serial} {soa_record.refresh} {soa_record.retry} {soa_record.expire} {soa_record.minimum})"
# records
for record in dns_records:
# name record class ttl record type record data
# add trailing dot to the name if it is a supported record type, to make it a fully qualified domain name
if record.type in [
DNSRecordType.MX,
DNSRecordType.CNAME,
DNSRecordType.NS,
DNSRecordType.SRV,
]:
record.content += "."
if record.prio is not None:
record_content = f"{record.prio} {record.content}"
else:
record_content = record.content
bind_file_content += (
f"\n{record.name} IN {record.ttl} {record.type} {record_content}"
)
if record.notes:
bind_file_content += f" ; {record.notes}"
with open(filepath, "w") as f:
f.write(bind_file_content)
logger.info("export finished")
return True
def import_dns_records(
self, domain: str, filepath: Union[Path, str], restore_mode: DNSRestoreMode
) -> bool:
"""
Restore all DNS records from a json file to the given domain.
This method does not represent a Porkbun API method.
:param domain: the domain for which the DNS record should be restored
:param filepath: the filepath from which the DNS records are to be restored
:param restore_mode: The restore mode (DNS records are identified by the record type, name and prio if supported):
clear: remove all existing DNS records and restore all DNS records from the provided file
replace: replace only existing DNS records with the DNS records from the provided file,
but do not create any new DNS records
keep: keep the existing DNS records and only create new ones for all DNS records from
the specified file if they do not exist
:return: True if everything went well
"""
filepath = Path(filepath)
existing_dns_records = self.get_dns_records(domain)
with open(filepath, "r") as f:
exported_dns_records_dict = json.load(f)
if restore_mode is DNSRestoreMode.clear:
logger.debug("restore mode: clear")
try:
# delete all existing DNS records
for record in existing_dns_records:
self.delete_dns_record(domain, record.id)
# restore all exported records by creating new DNS records
for _, exported_record in exported_dns_records_dict.items():
name = ".".join(exported_record["name"].split(".")[:-2])
self.create_dns_record(
domain=domain,
record_type=DNSRecordType(exported_record["type"]),
content=exported_record["content"],
name=name,
ttl=exported_record["ttl"],
prio=exported_record["prio"],
)
except Exception as e:
logger.error("something went wrong: {}".format(e.__str__()))
self.__handle_error_backup__(existing_dns_records)
logger.error("import failed")
return False
elif restore_mode is DNSRestoreMode.replace:
logger.debug("restore mode: replace")
try:
existing_dns_record_hashed = {
sha256(
f"{record.type}{record.name}{record.prio}".encode()
).hexdigest(): record
for record in existing_dns_records
}
for record in exported_dns_records_dict.values():
record_hash = sha256(
f"{record['type']}{record['name']}{record['prio']}".encode()
).hexdigest()
existing_record = existing_dns_record_hashed.get(record_hash, None)
# check if the exported dns record is different to the existing record,
# so we can reduce unnecessary api calls
if existing_record is not None and (
record["content"] != existing_record.content
or record["ttl"] != existing_record.ttl
or record["prio"] != existing_record.prio
):
self.update_dns_record(
domain=domain,
record_id=existing_record.id,
record_type=DNSRecordType(record["type"]),
content=record["content"],
name=record["name"].replace(f".{domain}", ""),
ttl=record["ttl"],
prio=record["prio"],
)
except Exception as e:
logger.error("something went wrong: {}".format(e.__str__()))
self.__handle_error_backup__(existing_dns_records)
logger.error("import failed")
return False
elif restore_mode is DNSRestoreMode.keep:
logger.debug("restore mode: keep")
existing_dns_record_hashed = {
sha256(
f"{record.type}{record.name}{record.prio}".encode()
).hexdigest(): record
for record in existing_dns_records
}
try:
for record in exported_dns_records_dict.values():
record_hash = sha256(
f"{record['type']}{record['name']}{record['prio']}".encode()
).hexdigest()
existing_record = existing_dns_record_hashed.get(record_hash, None)
if existing_record is None:
self.create_dns_record(
domain=domain,
record_type=DNSRecordType(record["type"]),
content=record["content"],
name=record["name"].replace(f".{domain}", ""),
ttl=record["ttl"],
prio=record["prio"],
)
except Exception as e:
logger.error("something went wrong: {}".format(e.__str__()))
self.__handle_error_backup__(existing_dns_records)
logger.error("import failed")
return False
else:
raise Exception("restore mode not supported")
logger.info("import successfully completed")
return True
def import_bind_dns_records(
self, filepath: Union[Path, str], restore_mode: DNSRestoreMode
) -> bool:
"""
Restore all DNS records from a BIND file.
This method does not represent a Porkbun API method.
:param filepath: the bind filepath from which the DNS records are to be restored
:param restore_mode: The restore mode:
clear: remove all existing DNS records and restore all DNS records from the provided file
:return: True if everything went well
"""
bind_file = BindFile.from_file(filepath)
existing_dns_records = self.get_dns_records(bind_file.origin[:-1])
if restore_mode is DNSRestoreMode.clear:
logger.debug("restore mode: clear")
try:
# delete all existing DNS records
for record in existing_dns_records:
self.delete_dns_record(bind_file.origin[:-1], record.id)
nameserver_records = []
# restore all records from BIND file by creating new DNS records
for record in bind_file.records:
if record.record_type == DNSRecordType.NS:
# collect nameserver records to update them later in bulk
nameserver_records.append(record)
continue
if record.name.endswith("."):
# extract subdomain from record name, by removing the domain and TLD
subdomain = record.name.removesuffix(bind_file.origin)
subdomain = subdomain.removesuffix(".")
else:
subdomain = record.name
self.create_dns_record(
domain=bind_file.origin[:-1],
record_type=record.record_type,
content=record.data,
name=subdomain,
ttl=record.ttl,
prio=record.prio,
)
# update nameservers in bulk
if nameserver_records:
name_servers = []
# remove trailing dot from nameserver records
for nameserver in nameserver_records:
if nameserver.data.endswith("."):
name_servers.append(nameserver.data[:-1])
else:
name_servers.append(nameserver.data)
self.update_dns_servers(bind_file.origin[:-1], name_servers)
except Exception as e:
logger.error("something went wrong: {}".format(e.__str__()))
self.__handle_error_backup__(existing_dns_records)
logger.error("import failed")
return False
else:
raise Exception(f"restore mode '{restore_mode.value}' not supported")
logger.info("import successfully completed")
return True
def update_dns_servers(self, domain: str, name_servers: List[str]) -> bool:
"""
Update the name servers of the specified domain.
See https://api.porkbun.com/api/json/v3/documentation#Domain%20Update%20Name%20Servers for more info.
:return: True if everything went well
"""
url = urljoin(self.api_endpoint, f"domain/updateNs/{domain}")
req_json = {**self._get_auth_request_json(), "ns": name_servers}
r = requests.post(url=url, json=req_json)
if r.status_code == 200 and json.loads(r.text).get("status", None) == "SUCCESS":
return True
else:
response_json = json.loads(r.text)
raise PKBClientException(
response_json.get("status", "Unknown status"),
response_json.get("message", "Unknown message"),
)
def get_dns_servers(self, domain: str) -> List[str]:
"""
Get the name servers for the given domain.
See https://api.porkbun.com/api/json/v3/documentation#Domain%20Get%20Name%20Servers for more info.
:return: list of name servers
"""
url = urljoin(self.api_endpoint, f"domain/getNs/{domain}")
req_json = self._get_auth_request_json()
r = requests.post(url=url, json=req_json)
if r.status_code == 200:
return json.loads(r.text).get("ns", [])
else:
response_json = json.loads(r.text)
raise PKBClientException(
response_json.get("status", "Unknown status"),
response_json.get("message", "Unknown message"),
)
def get_domains(self, start: int = 0) -> List[DomainInfo]:
"""
Get all domains for the account in chunks of 1000. If you reach the end of all domains, the list will be empty.
See https://api.porkbun.com/api/json/v3/documentation#Domain%20List%20All for more info.
:param start: the index of the first domain to retrieve
:return: list of DomainInfo objects
"""
url = urljoin(self.api_endpoint, "domain/listAll")
req_json = {**self._get_auth_request_json(), "start": start}
r = requests.post(url=url, json=req_json)
if r.status_code == 200:
return [
DomainInfo(
domain=d["domain"],
status=d["status"],
tld=d["tld"],
create_date=datetime.fromisoformat(d["createDate"]),
expire_date=datetime.fromisoformat(d["expireDate"]),
security_lock=bool(d["securityLock"]),
whois_privacy=bool(d["whoisPrivacy"]),
auto_renew=bool(d["autoRenew"]),
not_local=bool(d["notLocal"]),
)
for d in json.loads(r.text).get("domains", [])
]
else:
response_json = json.loads(r.text)
raise PKBClientException(
response_json.get("status", "Unknown status"),
response_json.get("message", "Unknown message"),
)
def get_url_forwards(self, domain: str) -> List[URLForwarding]:
"""
Get the url forwarding for the given domain.
See https://api.porkbun.com/api/json/v3/documentation#Domain%20Get%20URL%20Forwarding for more info.
:return: list of URLForwarding objects
"""
url = urljoin(self.api_endpoint, f"domain/getUrlForwarding/{domain}")
req_json = self._get_auth_request_json()
r = requests.post(url=url, json=req_json)
if r.status_code == 200:
return [
URLForwarding(
id=f["id"],
subdomain=f["subdomain"],
location=f["location"],
type=URLForwardingType[f["type"]],
include_path=f["includePath"] == "yes",
wildcard=f["wildcard"] == "yes",
)
for f in json.loads(r.text).get("forwards", [])
]
else:
response_json = json.loads(r.text)
raise PKBClientException(
response_json.get("status", "Unknown status"),
response_json.get("message", "Unknown message"),
)
def create_url_forward(
self,
domain: str,
subdomain: str,
location: str,
type: URLForwardingType,
include_path: bool,
wildcard: bool,
) -> bool:
"""
Add a url forward for the given domain.
See https://api.porkbun.com/api/json/v3/documentation#Domain%20Add%20URL%20Forward for more info.
:param domain: the domain for which the url forwarding should be added
:param subdomain: the subdomain for which the url forwarding should be added, can be empty for root domain
:param location: the location to which the url forwarding should redirect
:param type: the type of the url forwarding
:param include_path: if the path should be included in the url forwarding
:param wildcard: if the url forwarding should also be applied to all subdomains
:return: True if the forwarding was added successfully
"""
url = urljoin(self.api_endpoint, f"domain/addUrlForward/{domain}")
req_json = {
**self._get_auth_request_json(),
"subdomain": subdomain,
"location": location,
"type": type.value,
"includePath": include_path,
"wildcard": wildcard,
}
r = requests.post(url=url, json=req_json)
if r.status_code == 200:
return True
else:
response_json = json.loads(r.text)
raise PKBClientException(
response_json.get("status", "Unknown status"),
response_json.get("message", "Unknown message"),
)
def delete_url_forward(self, domain: str, id: str) -> bool:
"""
Delete an url forward for the given domain.
See https://api.porkbun.com/api/json/v3/documentation#Domain%20Delete%20URL%20Forward for more info.
:param domain: the domain for which the url forwarding should be deleted
:param id: the id of the url forwarding which should be deleted
:return: True if the deletion was successful
"""
url = urljoin(self.api_endpoint, f"domain/deleteUrlForward/{domain}/{id}")
req_json = self._get_auth_request_json()
r = requests.post(url=url, json=req_json)
if r.status_code == 200:
return True
else:
response_json = json.loads(r.text)
raise PKBClientException(
response_json.get("status", "Unknown status"),
response_json.get("message", "Unknown message"),
)
def get_domain_pricing(self) -> dict:
"""
Get the pricing for all Porkbun domains.
See https://api.porkbun.com/api/json/v3/documentation#Domain%20Pricing for more info.
:return: dict with pricing
"""
url = urljoin(self.api_endpoint, "pricing/get")
r = requests.post(url=url)
if r.status_code == 200:
return json.loads(r.text)["pricing"]
else:
response_json = json.loads(r.text)
raise PKBClientException(
response_json.get("status", "Unknown status"),
response_json.get("message", "Unknown message"),
)
def get_ssl_bundle(self, domain) -> SSLCertBundle:
"""
API SSL bundle retrieve method: retrieve an SSL bundle for the given domain.
See https://api.porkbun.com/api/json/v3/documentation#SSL%20Retrieve%20Bundle%20by%20Domain for more info.
:param domain: the domain for which the SSL bundle should be retrieved
:return: tuple of intermediate certificate, certificate chain, private key, public key
"""
url = urljoin(self.api_endpoint, f"ssl/retrieve/{domain}")
req_json = self._get_auth_request_json()
r = requests.post(url=url, json=req_json)
if r.status_code == 200:
ssl_bundle = json.loads(r.text)
return SSLCertBundle(
certificate_chain=ssl_bundle["certificatechain"],
private_key=ssl_bundle["privatekey"],
public_key=ssl_bundle["publickey"],
)
else:
response_json = json.loads(r.text)
raise PKBClientException(
response_json.get("status", "Unknown status"),
response_json.get("message", "Unknown message"),
)
def get_dnssec_records(self, domain: str) -> List[DNSSECRecord]:
"""
API DNSSEC retrieve method: retrieve all DNSSEC records for the given domain.
See https://porkbun.com/api/json/v3/documentation#DNSSEC%20Get%20Records for more info.
:param domain: the domain for which the DNSSEC records should be retrieved
:return: list of :class:`DNSSECRecord` objects
"""
url = urljoin(self.api_endpoint, f"dns/getDnssecRecords/{domain}")
req_json = self._get_auth_request_json()
r = requests.post(url=url, json=req_json)
if r.status_code == 200:
return [
DNSSECRecord(
key_tag=int(record["keyTag"]),
alg=int(record["alg"]),
digest_type=int(record["digestType"]),
digest=record["digest"],
max_sig_life=int(record["maxSigLife"])
if "maxSigLife" in record
else None,
key_data_flags=int(record["keyDataFlags"])
if "keyDataFlags" in record
else None,
key_data_protocol=int(record["keyDataProtocol"])
if "keyDataProtocol" in record
else None,
key_data_algo=int(record["keyDataAlgo"])
if "keyDataAlgo" in record
else None,
key_data_pub_key=record["keyDataPubKey"]
if "keyDataPubKey" in record
else None,
)
for record in json.loads(r.text).get("records", {}).values()
]
else:
response_json = json.loads(r.text)
raise PKBClientException(
response_json.get("status", "Unknown status"),
response_json.get("message", "Unknown message"),
)
def create_dnssec_record(
self,
domain: str,
key_tag: int,
alg: int,
digest_type: int,
digest: str,
max_sig_life: Optional[int] = None,
key_data_flags: Optional[int] = None,
key_data_protocol: Optional[int] = None,
key_data_algo: Optional[int] = None,
key_data_pub_key: Optional[str] = None,
) -> bool:
"""
API DNSSEC create method: create a new DNSSEC record for the given domain.
See https://porkbun.com/api/json/v3/documentation#DNSSEC%20Create%20Record for more info.
:param domain: the domain for which the DNSSEC record should be created
:param key_tag: the key tag of the DNSSEC record
:param alg: algorithm of the DNSSEC record
:param digest_type: digest type of the DNSSEC record
:param digest: digest of the DNSSEC record
:param max_sig_life: maximum signature life of the DNSSEC record in seconds
:param key_data_flags: key data flags of the DNSSEC record
:param key_data_protocol: key data protocol of the DNSSEC record
:param key_data_algo: key data algorithm of the DNSSEC record
:param key_data_pub_key: key data public key of the DNSSEC record
:return: True if everything went well
"""
if max_sig_life is not None and max_sig_life < 0:
raise ValueError("max_sig_life must be greater than 0")
url = urljoin(self.api_endpoint, f"dns/createDnssecRecord/{domain}")
req_json = {
**self._get_auth_request_json(),
"keyTag": key_tag,
"alg": alg,
"digestType": digest_type,
"digest": digest,
"maxSigLife": max_sig_life,
"keyDataFlags": key_data_flags,
"keyDataProtocol": key_data_protocol,
"keyDataAlgo": key_data_algo,
"keyDataPubKey": key_data_pub_key,
}
r = requests.post(url=url, json=req_json)
if r.status_code == 200:
return True
else:
response_json = json.loads(r.text)
raise PKBClientException(
response_json.get("status", "Unknown status"),
response_json.get("message", "Unknown message"),
)
def delete_dnssec_record(self, domain: str, key_tag: int) -> bool:
"""
API DNSSEC delete method: delete an existing DNSSEC record for the given domain.
See https://porkbun.com/api/json/v3/documentation#DNSSEC%20Delete%20Record for more info.
:param domain: the domain for which the DNSSEC record should be deleted
:param key_tag: the key tag of the DNSSEC record
:return: True if everything went well
"""
url = urljoin(self.api_endpoint, f"dns/deleteDnssecRecord/{domain}/{key_tag}")
req_json = self._get_auth_request_json()
r = requests.post(url=url, json=req_json)
if r.status_code == 200:
return True
else:
response_json = json.loads(r.text)
raise PKBClientException(
response_json.get("status", "Unknown status"),
response_json.get("message", "Unknown message"),
)
def get_domain_availability(
self, domain: str
) -> tuple[DomainAvailability, DomainCheckRateLimit]:
"""
Check if a domain is available for registration and provide additional information about the domain like price
and if it is a premium domain.
Implements the API endpoint https://porkbun.com/api/json/v3/documentation#Domain%20Check
:param domain: the domain to check for availability
:return: DomainAvailability object and DomainCheckRateLimit object
:raises PKBClientException: if the API call was not successful
"""
url = urljoin(self.api_endpoint, f"domain/checkDomain/{domain}")
r = requests.post(url=url, json=self._get_auth_request_json())
if r.status_code == 200:
data = json.loads(r.text)
response = data["response"]
limits = data["limits"]
return DomainAvailability(
available=response["avail"] == "yes",
type=response["type"],
price=float(response["price"]),
first_year_promo=response["firstYearPromo"] == "yes",
regular_price=float(response["regularPrice"]),
premium=response["premium"] == "yes",
additional_prices=[
DomainPrice(
type=ap["type"],
price=float(ap["price"]),
regular_price=float(ap["regularPrice"]),
)
for ap in response.get("additional", {}).values()
],
), DomainCheckRateLimit(
ttl=int(limits["TTL"]),
limit=int(limits["limit"]),
used=limits["used"],
natural_language=limits["naturalLanguage"],
)
else:
response_json = json.loads(r.text)
raise PKBClientException(
response_json.get("status", "Unknown status"),
response_json.get("message", "Unknown message"),
)
def get_glue_records(self, domain: str) -> list[GlueRecord]:
"""Get all glue records for a specified domain.
Implements the API endpoint https://porkbun.com/api/json/v3/documentation#Domain%20Get%20Glue%20Records
:param domain: the domain for which the glue records should be retrieved
:return: list of GlueRecord objects
:raises PKBClientException: if the API call was not successful
"""
url = urljoin(self.api_endpoint, f"domain/getGlue/{domain}")
req_json = self._get_auth_request_json()
r = requests.post(url=url, json=req_json)
if r.status_code == 200:
records = []
for host in json.loads(r.text).get("hosts", []):
v4 = host[1].get("v4")
v6 = host[1].get("v6")
record = GlueRecord(
host=host[0],
v4=v4[0] if v4 else None,
v6=v6[0] if v6 else None,
)
records.append(record)
return records
response_json = json.loads(r.text)
raise PKBClientException(
response_json.get("status", "Unknown status"),
response_json.get("message", "Unknown message"),
)
def create_glue_record(
self, domain: str, glue_host_subdomain: str, ips: list[str]
) -> bool:
"""
Create a glue record for a specified domain and host.
Implements the API endpoint https://porkbun.com/api/json/v3/documentation#Domain%20Create%20Glue%20Record.
:param domain: the domain for which the glue record should be created
:param glue_host_subdomain: the subdomain of the glue record host, e.g. "ns1" for "ns1.example.com"
:param ips: list of IP addresses to create the glue record with
:return: True if everything went well
:raises PKBClientException: if the API call was not successful
"""
url = urljoin(
self.api_endpoint,
f"domain/createGlue/{domain}/{glue_host_subdomain}",
)
req_json = {**self._get_auth_request_json(), "ips": ips}
r = requests.post(url=url, json=req_json)
if r.status_code == 200:
return True
response_json = json.loads(r.text)
raise PKBClientException(
response_json.get("status", "Unknown status"),
response_json.get("message", "Unknown message"),
)
def delete_glue_record(self, domain: str, glue_host_subdomain: str) -> bool:
"""Delete a glue record for a specified domain and host specified by the subdomain of the glue record host.
Implements the API endpoint https://porkbun.com/api/json/v3/documentation#Domain%20Delete%20Glue%20Record.
:param domain: the domain for which the glue record should be deleted
:param glue_host_subdomain: the subdomain of the glue record host, e.g. "ns1" for "ns1.example.com"
:return: True if everything went well
:raises PKBClientException: if the API call was not successful
"""
url = urljoin(
self.api_endpoint,
f"domain/deleteGlue/{domain}/{glue_host_subdomain}",
)
req_json = self._get_auth_request_json()
r = requests.post(url=url, json=req_json)
if r.status_code == 200:
return True
response_json = json.loads(r.text)
raise PKBClientException(
response_json.get("status", "Unknown status"),
response_json.get("message", "Unknown message"),
)
def update_glue_record(
self, domain: str, glue_host_subdomain: str, ips: list[str]
) -> bool:
"""Update a glue record for a specified domain and host.
Implements the API endpoint https://porkbun.com/api/json/v3/documentation#Domain%20Update%20Glue%20Record.
:param domain: the domain for which the glue record should be updated
:param glue_host_subdomain: the subdomain of the glue record host, e.g. "ns1" for "ns1.example.com"
:param ips: list of IP addresses to update the glue record with. Current IP addresses will be removed and replaced with these ones.
:return: True if everything went well
:raises PKBClientException: if the API call was not successful
"""
url = urljoin(
self.api_endpoint,
f"domain/updateGlue/{domain}/{glue_host_subdomain}",
)
req_json = {**self._get_auth_request_json(), "ips": ips}
r = requests.post(url=url, json=req_json)
if r.status_code == 200:
return True
response_json = json.loads(r.text)
raise PKBClientException(
response_json.get("status", "Unknown status"),
response_json.get("message", "Unknown message"),
)
@staticmethod
def __handle_error_backup__(dns_records: list[DNSRecord]) -> None:
"""
Handle errors when working with dns records by creating a backup of the given DNS records.
Crates a backup file in the current working directory with an incremental suffix.
:param dns_records: the DNS records to backup
"""
# merge the single DNS records into one single dict with the record id as key
dns_records_dict = dict()
for record in dns_records:
dns_records_dict[record.id] = record.to_dict()
# generate filename with incremental suffix
base_backup_filename = "pkb_client_dns_records_backup"
suffix = 0
backup_file_path = Path("{}_{}.json".format(base_backup_filename, suffix))
while backup_file_path.exists():
suffix += 1
backup_file_path = Path("{}_{}.json".format(base_backup_filename, suffix))
with open(backup_file_path, "w") as f:
json.dump(dns_records_dict, f)
logger.warning(
"a backup of your existing dns records was saved to {}".format(
str(backup_file_path)
)
)
|