Vigiar
1
0
Derivar
Você já tinha feito uma derivação do repositório dns-update-action, anteriormente
0
dns-update-action/dns_update.py

362 linhas
15 KiB
Python
Ficheiro executável

#!/usr/bin/env python3
"""Create, update or delete DNS records of a domain through the Interweb Angola API.
Runs inside the GitHub Action (see action.yml). Only the Python standard library is used,
so nothing is downloaded on the runner. Inputs come from environment variables (INPUT_*).
"""
import json
import os
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
API_URL = "https://api.interweb.ao"
VERSION = "1.0.1"
USER_AGENT = "interweb-ao-dns-update-action/" + VERSION
KEY_ENV = "INTERWEB_API_KEY"
TYPES = ("A", "AAAA", "CNAME", "MX", "TXT", "NS", "SRV", "CAA")
ACTIONS = ("upsert", "create", "delete")
MULTI_VALUE = ("MX", "TXT", "NS", "SRV", "CAA")
class ApiError(Exception):
def __init__(self, status, code, message, details=None, correlation_id=None):
Exception.__init__(self, message)
self.status = status
self.code = code
self.message = message
self.details = details or {}
self.correlation_id = correlation_id
HINTS = {
"unauthorized": "The API key is missing or invalid. Check the secret passed in api-key.",
"insufficient_scope": "The API key needs the dns:read and dns:write permissions.",
"ip_not_allowed": "The API key only accepts some IP addresses. GitHub runners change IP: allow them or use a self-hosted runner.",
"not_found": "The domain is not on this account, is not active or does not have DNS on.",
"account_email_domain": "This record decides where the mail of the account email goes. Change it in the account dashboard.",
"rate_limited": "Too many requests. Wait a little and run the workflow again.",
"validation_failed": "The API did not accept the record. See the details below.",
}
def log(msg):
print(msg, flush=True)
def fail(msg):
print("::error::" + msg.replace("\n", "%0A"), flush=True)
sys.exit(1)
def warn(msg):
print("::warning::" + msg, flush=True)
def set_output(name, value):
path = os.environ.get("GITHUB_OUTPUT")
if isinstance(value, bool):
value = "true" if value else "false"
value = "" if value is None else str(value)
if path:
with open(path, "a", encoding="utf-8") as f:
f.write("%s=%s\n" % (name, value.replace("\n", " ")))
def env(name, default=""):
return os.environ.get("INPUT_" + name, default).strip()
class Api(object):
def __init__(self, key):
self.key = key
def request(self, method, path, body=None, attempts=3):
url = API_URL.rstrip("/") + path
data = None
headers = {
"Authorization": "Bearer " + self.key,
"Accept": "application/json",
"Accept-Language": "en",
"User-Agent": USER_AGENT,
}
if body is not None:
data = json.dumps(body).encode("utf-8")
headers["Content-Type"] = "application/json"
if method == "POST":
# The same key on every attempt, so a retry never creates the record twice.
headers["Idempotency-Key"] = "gh-dns-" + uuid.uuid4().hex
for attempt in range(1, attempts + 1):
req = urllib.request.Request(url, data=data, method=method, headers=headers)
try:
with urllib.request.urlopen(req, timeout=60) as resp:
raw = resp.read().decode("utf-8")
return json.loads(raw) if raw else {}
except urllib.error.HTTPError as e:
raw = e.read().decode("utf-8", "replace")
try:
err = json.loads(raw).get("error", {})
except ValueError:
err = {}
retry_after = e.headers.get("Retry-After") if e.headers else None
if attempt < attempts and (e.code == 429 or e.code >= 500):
wait = min(int(retry_after) if (retry_after or "").isdigit() else 5 * attempt, 60)
log("The API answered %d, trying again in %d s..." % (e.code, wait))
time.sleep(wait)
continue
raise ApiError(e.code, err.get("code", "http_%d" % e.code), err.get("message", raw[:300] or e.reason),
err.get("details"), err.get("correlation_id"))
except (urllib.error.URLError, OSError) as e:
if attempt < attempts:
time.sleep(5 * attempt)
continue
raise ApiError(0, "network_error", "Could not reach the API: %s" % e)
raise ApiError(0, "network_error", "Could not reach the API.")
def normalise_name(name, domain):
name = (name or "@").strip().rstrip(".").lower()
if name in ("", "@", domain):
return "@"
if name.endswith("." + domain):
name = name[: -len(domain) - 1]
return name
def normalise_value(rtype, value):
value = (value or "").strip()
if rtype == "TXT":
if len(value) >= 2 and value[0] == '"' and value[-1] == '"':
value = value[1:-1]
return value
if rtype in ("CNAME", "MX", "NS", "SRV"):
value = value.rstrip(".")
if rtype == "AAAA":
try:
import ipaddress
value = str(ipaddress.ip_address(value))
except ValueError:
pass
return value.lower() if rtype != "CAA" else value
def to_int(value, field, default=None):
if value in (None, ""):
return default
try:
return int(str(value).strip())
except ValueError:
fail("%s must be a whole number, got %r." % (field, value))
def read_records(domain):
"""The records asked for: the single-record inputs, or the JSON list in `records`."""
raw = env("RECORDS")
if raw:
try:
items = json.loads(raw)
except ValueError as e:
fail("records is not valid JSON: %s" % e)
if isinstance(items, dict):
items = [items]
if not isinstance(items, list) or not items:
fail("records must be a JSON list of records.")
else:
items = [{
"action": env("ACTION", "upsert"), "type": env("TYPE"), "name": env("NAME", "@"),
"value": env("VALUE"), "ttl": env("TTL"), "priority": env("PRIORITY"), "match_value": env("MATCH_VALUE"),
}]
out = []
for i, it in enumerate(items, 1):
if not isinstance(it, dict):
fail("Record %d in records is not an object." % i)
action = str(it.get("action") or env("ACTION", "upsert")).strip().lower()
rtype = str(it.get("type") or "").strip().upper()
if action not in ACTIONS:
fail("Record %d: action must be one of %s." % (i, ", ".join(ACTIONS)))
if rtype not in TYPES:
fail("Record %d: type must be one of %s." % (i, ", ".join(TYPES)))
value = str(it.get("value") or "").strip()
if action != "delete" and not value:
fail("Record %d: value is required to %s a record." % (i, action))
out.append({
"action": action,
"type": rtype,
"name": normalise_name(str(it.get("name") or "@"), domain),
"value": value,
"ttl": to_int(it.get("ttl"), "ttl"),
"priority": to_int(it.get("priority"), "priority"),
"match_value": str(it.get("match_value") or "").strip(),
})
return out
def same_value(rec, rtype, value):
return normalise_value(rtype, rec.get("value")) == normalise_value(rtype, value)
def describe(r):
return "%s %s %s" % (r["type"], r["name"], r.get("value") or "")
def apply_one(api, domain, zone, want, dry_run):
"""Applies one record and returns (changed, record_id, simulated)."""
rtype, name = want["type"], want["name"]
matches = [r for r in zone if r.get("type") == rtype and normalise_name(r.get("name"), domain) == name]
editable = [r for r in matches if not r.get("read_only")]
if len(editable) < len(matches) and want["action"] != "create":
log(" Note: %d read-only record(s) with this name and type are left alone." % (len(matches) - len(editable)))
def body():
b = {"name": name, "type": rtype, "value": want["value"]}
if want["ttl"] is not None:
b["ttl"] = want["ttl"]
if want["priority"] is not None:
b["priority"] = want["priority"]
return b
def unchanged(r):
return (same_value(r, rtype, want["value"])
and (want["ttl"] is None or r.get("ttl") == want["ttl"])
and (want["priority"] is None or r.get("priority") == want["priority"]))
if want["action"] == "delete":
targets = editable
if want["value"]:
targets = [r for r in editable if same_value(r, rtype, want["value"])]
if not targets:
log(" Nothing to delete: no record %s %s%s." % (rtype, name, " " + want["value"] if want["value"] else ""))
return False, "", False
simulated = False
for r in targets:
log(" Delete %s %s %s (id %s)%s" % (rtype, name, r.get("value"), r.get("id"), " [dry run]" if dry_run else ""))
if not dry_run:
res = api.request("DELETE", "/v1/domains/%s/dns/%s" % (q(domain), q(r["id"])))
simulated = simulated or bool((res.get("data") or {}).get("simulated"))
return True, ",".join(r["id"] for r in targets), simulated
# Already there exactly as asked: nothing to do.
for r in editable:
if unchanged(r):
log(" Already up to date: %s (id %s)" % (describe(want), r.get("id")))
return False, r.get("id", ""), False
target = None
if want["action"] == "upsert" and editable:
if want["match_value"]:
found = [r for r in editable if same_value(r, rtype, want["match_value"])]
if not found:
fail("No %s record named %s with the value %s to change." % (rtype, name, want["match_value"]))
target = found[0]
else:
same = [r for r in editable if same_value(r, rtype, want["value"])]
if same:
target = same[0] # same value, only the ttl or the priority change
elif rtype in MULTI_VALUE:
# MX, TXT, NS, SRV and CAA often have several values on one name (SPF next to a
# verification code, two MX servers): a new value is added, never put in place of another.
target = None
elif len(editable) == 1:
target = editable[0]
else:
fail("There are %d %s records named %s. Say which one to change with match-value, or use action create."
% (len(editable), rtype, name))
if target is not None:
log(" Change %s %s: %s -> %s (id %s)%s" % (rtype, name, target.get("value"), want["value"], target.get("id"),
" [dry run]" if dry_run else ""))
if dry_run:
return True, target.get("id", ""), False
b = body()
b.setdefault("ttl", target.get("ttl"))
if rtype in ("MX", "SRV", "CAA"):
b.setdefault("priority", target.get("priority"))
res = api.request("PUT", "/v1/domains/%s/dns/%s" % (q(domain), q(target["id"])), b)
data = res.get("data") or {}
return True, data.get("id", ""), bool(data.get("simulated"))
log(" Create %s%s" % (describe(want), " [dry run]" if dry_run else ""))
if dry_run:
return True, "", False
res = api.request("POST", "/v1/domains/%s/dns" % q(domain), body())
data = res.get("data") or {}
return True, data.get("id", ""), bool(data.get("simulated"))
def q(s):
return urllib.parse.quote(str(s), safe="")
def check_key(api, need):
"""Checks the key with GET /v1/token before reading the zone, and stops early when it cannot do the job."""
try:
data = api.request("GET", "/v1/token").get("data") or {}
except ApiError as e:
if e.status == 401:
fail("The API key is not valid: it was deleted, has expired or was copied wrong. "
"Check the secret passed in api-key, or create a new key in the API Center.")
if e.status == 403:
fail("The API refused the key (%s): %s%s" % (e.code, e.message, "\n" + HINTS[e.code] if e.code in HINTS else ""))
raise
perms = data.get("permissions") or []
missing = [p for p in need if p not in perms]
if missing:
fail("The API key does not have the permissions this action needs: %s. "
"Add them to the key in the API Center and run the workflow again." % ", ".join(missing))
return data
def main():
key = env("API_KEY") or os.environ.get(KEY_ENV, "").strip()
if not key:
fail("api-key is empty. Save your API key as a repository secret and pass it in api-key.")
domain = env("DOMAIN").strip().rstrip(".").lower()
if not domain or "." not in domain:
fail("domain is required, for example example.co.ao.")
dry_run = env("DRY_RUN", "false").lower() == "true"
records = read_records(domain)
api = Api(key)
try:
token = check_key(api, ["dns:read"] if dry_run else ["dns:read", "dns:write"])
if token.get("mode", "sandbox" if key.startswith("sandbox_") else "production") == "sandbox":
log("Sandbox key: changes are simulated and the zone stays as it is.")
zone = api.request("GET", "/v1/domains/%s/dns" % q(domain)).get("data") or []
log("Zone of %s: %d records." % (domain, len(zone)))
changed_any, ids, simulated_any = False, [], False
for want in records:
log("%s %s:" % (want["action"].capitalize(), describe(want)))
changed, rid, simulated = apply_one(api, domain, zone, want, dry_run)
changed_any = changed_any or changed
simulated_any = simulated_any or simulated
if rid:
ids.append(rid)
if changed and not dry_run and len(records) > 1:
# Record ids change after each change: read the zone again before the next one.
zone = api.request("GET", "/v1/domains/%s/dns" % q(domain)).get("data") or []
except ApiError as e:
msg = "%s (HTTP %s, %s)" % (e.message, e.status, e.code)
reason = (e.details or {}).get("reason")
if reason == "cname_conflict":
msg += "\nThere is already a CNAME, or other records, with this name. Delete them first or use another name."
elif e.code in HINTS:
msg += "\n" + HINTS[e.code]
if e.details:
msg += "\nDetails: " + json.dumps(e.details)
if e.correlation_id:
msg += "\nCorrelation id: " + e.correlation_id
fail(msg)
set_output("changed", changed_any)
set_output("record-ids", ",".join(ids))
set_output("simulated", simulated_any)
log("Done: %s." % ("changes made" if changed_any and not dry_run else
"dry run, nothing changed" if dry_run else "nothing to change"))
if __name__ == "__main__":
main()