id: dangling-cname-remediation-ticket
namespace: company.security
description: Confirm persistent NXDOMAIN CNAME targets and open a deduplicated
remediation issue. No DNS records are changed.
concurrency:
limit: 1
behavior: QUEUE
inputs:
- id: hostname
type: STRING
description: An owned hostname to inspect, without a URL scheme.
defaults: www.example.com
- id: issue_repository
type: STRING
description: Your remediation repository, in owner/repo form.
defaults: your-org/dns-operations
- id: min_observations
type: INT
defaults: 2
description: Consecutive successful observations required, minimum 2. Failed
lookups leave the baseline unchanged.
- id: dns_server
type: STRING
defaults: 1.1.1.1
description: Recursive DNS resolver IP address; use a resolver approved by your
DNS team.
- id: dry_run
type: BOOL
defaults: true
description: Inspect and show the plan without saving state or creating issues.
variables:
github_endpoint: https://api.github.com
triggers:
- id: hourly
type: io.kestra.plugin.core.trigger.Schedule
cron: 17 * * * *
disabled: true
inputs:
dry_run: false
tasks:
- id: load_state
type: io.kestra.plugin.core.kv.Get
key: 'cname-remediation-{{ inputs.hostname | lower }}-{{ inputs.issue_repository
| replace({''/'': ''-''}) }}'
errorOnMissing: false
- id: inspect_dns
type: io.kestra.plugin.scripts.python.Script
containerImage: python:3.12-slim
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
dependencies:
- dnspython==2.8.0
- kestra==2.0.0
env:
DNS_SERVER: '{{ inputs.dns_server }}'
HOSTNAME_TO_CHECK: '{{ inputs.hostname }}'
PREVIOUS_STATE: '{{ outputs.load_state.value ?? {} | toJson }}'
MIN_OBSERVATIONS: '{{ inputs.min_observations }}'
DRY_RUN: '{{ inputs.dry_run }}'
script: |
import json, os
import dns.exception
import dns.resolver
from datetime import datetime, timezone
from kestra import Kestra
hostname = os.environ["HOSTNAME_TO_CHECK"].strip().rstrip(".").lower()
# Restrict input to an owned public DNS name, never a URL or IP address.
hostname = hostname.encode("idna").decode("ascii")
if len(hostname) > 253 or "." not in hostname or any(
not label or len(label) > 63 or label.startswith("-") or label.endswith("-")
or any(c not in "abcdefghijklmnopqrstuvwxyz0123456789-" for c in label)
for label in hostname.split(".")
):
raise ValueError("hostname must be a fully qualified DNS name")
previous = json.loads(os.environ["PREVIOUS_STATE"])
if not isinstance(previous, dict):
raise ValueError("saved state must be an object")
resolver = dns.resolver.Resolver()
server = os.environ["DNS_SERVER"].strip()
if server:
import ipaddress
resolver.nameservers = [str(ipaddress.ip_address(server))]
resolver.timeout = 3
resolver.lifetime = 8
now = datetime.now(timezone.utc).isoformat()
def inspect():
try:
answer = resolver.resolve(hostname, "CNAME", search=False)
except dns.resolver.NoAnswer:
return {"status": "NO_CNAME", "target": ""}
except dns.resolver.NXDOMAIN as exc:
# Recursive resolvers can return the CNAME and the terminal NXDOMAIN
# in one response. Preserve that alias instead of calling it absent.
answers = [rr for response in exc.kwargs.get("responses", {}).values()
for rrset in response.answer
if rrset.rdtype == 5 and str(rrset.name).rstrip(".").lower() == hostname
for rr in rrset]
if not answers:
return {"status": "NO_CNAME", "target": ""}
answer = answers
target = str(answer[0].target).rstrip(".").lower()
# NXDOMAIN on an A query means the target name does not exist. A missing
# A answer does not: it may have AAAA, MX, TXT or other records instead.
try:
resolver.resolve(target, "A", search=False)
except dns.resolver.NoAnswer:
return {"status": "EXISTS", "target": target}
except dns.resolver.NXDOMAIN:
return {"status": "NXDOMAIN", "target": target}
return {"status": "EXISTS", "target": target}
# Timeouts, SERVFAIL and malformed answers raise: never count as NXDOMAIN,
# never overwrite the previous baseline and never open a speculative ticket.
observation = inspect()
count = 0
if observation["status"] == "NXDOMAIN":
count = 1
if previous.get("status") == "NXDOMAIN" and previous.get("target") == observation["target"]:
count = min(int(previous.get("consecutive", 0)) + 1, int(os.environ["MIN_OBSERVATIONS"]))
threshold = int(os.environ["MIN_OBSERVATIONS"])
if threshold < 2:
raise ValueError("at least two observations are required")
# Keep a local delivery marker as well as the GitHub search, which can lag.
reported = previous.get("reported_target", "")
eligible = observation["status"] == "NXDOMAIN" and count >= threshold and reported != observation["target"]
state = dict(observation, consecutive=count, checked_at=now, reported_target=reported)
if eligible and os.environ["DRY_RUN"].lower() == "false":
state["reported_target"] = observation["target"]
# This state is saved ONLY after the issue branch succeeds.
Kestra.outputs({
"hostname": hostname, "target": observation["target"],
"status": observation["status"], "consecutive": count, "eligible": eligible,
"title": "[dns-remediation] " + hostname,
"state": state,
})
- id: needs_ticket
type: io.kestra.plugin.core.flow.If
condition: '{{ outputs.inspect_dns.vars.eligible and not inputs.dry_run }}'
then:
- id: find_issue
type: io.kestra.plugin.github.issues.Search
oauthToken: '{{ secret(''GITHUB_TOKEN'') }}'
endpoint: '{{ vars.github_endpoint }}'
repository: '{{ inputs.issue_repository }}'
query: in:title "{{ outputs.inspect_dns.vars.title }}"
fetchType: FETCH_ONE
- id: create_if_absent
type: io.kestra.plugin.core.flow.If
condition: '{{ outputs.find_issue.size == 0 }}'
then:
- id: open_remediation
type: io.kestra.plugin.github.issues.Create
oauthToken: '{{ secret(''GITHUB_TOKEN'') }}'
endpoint: '{{ vars.github_endpoint }}'
repository: '{{ inputs.issue_repository }}'
title: '{{ outputs.inspect_dns.vars.title }}'
body: |
## Persistent missing CNAME target
`{{ outputs.inspect_dns.vars.hostname }}` points to `{{ outputs.inspect_dns.vars.target }}`, which returned NXDOMAIN on {{ outputs.inspect_dns.vars.consecutive }} consecutive observations.
This is evidence of a missing DNS target, NOT proof that the service can be claimed or that a takeover is possible. Check authoritative DNS and the provider account before changing anything.
- Confirm the hostname and target with the DNS owner.
- Restore the intended service or propose removal of the stale CNAME through your DNS change-review process.
- If the target is intentionally absent, document that decision here.
No DNS records were changed. This flow never closes issues automatically.
Kestra flow: `{{ flow.namespace }}.{{ flow.id }}`, execution: `{{ execution.id }}`.
- id: persist_live_observation
type: io.kestra.plugin.core.flow.If
condition: '{{ not inputs.dry_run }}'
then:
- id: save_state
type: io.kestra.plugin.core.kv.Set
key: 'cname-remediation-{{ inputs.hostname | lower }}-{{ inputs.issue_repository
| replace({''/'': ''-''}) }}'
kvType: JSON
value: '{{ outputs.inspect_dns.vars.state }}'
- id: summary
type: io.kestra.plugin.core.log.Log
message: '{{ outputs.inspect_dns.vars.hostname }} -> {{
outputs.inspect_dns.vars.target }}: {{ outputs.inspect_dns.vars.status }},
consecutive={{ outputs.inspect_dns.vars.consecutive }}, ticket eligible={{
outputs.inspect_dns.vars.eligible }}, dry run={{ inputs.dry_run }}'