#!/usr/bin/env python3
# Copyright (c) 2026 mati peterson. Maintainer: mati peterson <ipsonic@mailbox.org>. Project: https://ipsonic.com/probe/. Disclaimer: Provided AS IS, without warranty of any kind. Use at your own risk; validate checks and configurations before production use.
"""YAML-driven TCP / HTTP(S) acceptance checks."""
import argparse
import difflib
import importlib.util
from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeout
import csv
import platform
import copy
import re
import math
import json
import ipaddress
import re
from http.cookies import SimpleCookie
from urllib.parse import urljoin
import os
import socket
import ssl
import sys
import time
from datetime import datetime, timezone
import hashlib
import threading
from pathlib import Path
from urllib.parse import urlsplit
from requests.adapters import HTTPAdapter
from urllib3.poolmanager import PoolManager
from urllib3.connection import HTTPSConnection, HTTPConnection

import requests
import yaml
import sys as _ip_sys
import types as _ip_types
_ip_dns = _ip_types.ModuleType("dns_probe")
exec(compile('# Copyright (c) 2026 mati peterson. Maintainer: mati peterson <ipsonic@mailbox.org>. Project: https://ipsonic.com/probe/. Disclaimer: Provided AS IS, without warranty of any kind. Use at your own risk; validate checks and configurations before production use.\n"""Small RFC 1035 DNS query client using only Python standard library.\n\nSupports UDP with TCP fallback for truncated responses and explicit resolver selection.\n"""\nimport ipaddress\nimport os\nimport random\nimport socket\nimport struct\nimport time\nimport hashlib\n\nTYPES = {\'A\': 1, \'CNAME\': 5, \'TXT\': 16, \'AAAA\': 28, \'NS\': 2, \'SOA\': 6, \'PTR\': 12, \'MX\': 15, \'SRV\': 33, \'DS\': 43, \'RRSIG\': 46, \'DNSKEY\': 48, \'CAA\': 257}\nRCODES = {0: \'NOERROR\', 1: \'FORMERR\', 2: \'SERVFAIL\', 3: \'NXDOMAIN\', 4: \'NOTIMP\', 5: \'REFUSED\'}\n\n\ndef encode_name(name):\n    labels = name.rstrip(\'.\').split(\'.\')\n    if not name or any(not label or len(label.encode(\'idna\')) > 63 for label in labels):\n        raise ValueError(\'Invalid DNS name\')\n    result = b\'\'\n    for label in labels:\n        raw = label.encode(\'idna\')\n        result += bytes([len(raw)]) + raw\n    if len(result) + 1 > 255:\n        raise ValueError(\'DNS name too long\')\n    return result + b\'\\0\'\n\n\ndef decode_name(data, offset):\n    labels, visited, end = [], set(), None\n    while True:\n        if offset >= len(data) or offset in visited:\n            raise ValueError(\'Malformed DNS name or compression loop\')\n        visited.add(offset)\n        size = data[offset]\n        if size & 0xc0 == 0xc0:\n            if offset + 1 >= len(data):\n                raise ValueError(\'Truncated DNS pointer\')\n            pointer = ((size & 0x3f) << 8) | data[offset + 1]\n            if end is None:\n                end = offset + 2\n            offset = pointer\n            continue\n        if size & 0xc0:\n            raise ValueError(\'Unsupported DNS label type\')\n        offset += 1\n        if size == 0:\n            return \'.\'.join(labels) + \'.\', end if end is not None else offset\n        if offset + size > len(data):\n            raise ValueError(\'Truncated DNS label\')\n        labels.append(data[offset:offset + size].decode(\'ascii\'))\n        offset += size\n\n\ndef system_nameserver():\n    with open(\'/etc/resolv.conf\', encoding=\'utf-8\') as handle:\n        for line in handle:\n            parts = line.split(\'#\', 1)[0].split()\n            if len(parts) >= 2 and parts[0] == \'nameserver\':\n                return parts[1]\n    raise ValueError(\'No nameserver found in /etc/resolv.conf\')\n\n\ndef query(name, record_type, nameserver=None, port=53, timeout=3.0, transport=\'auto\', dnssec=False):\n    record_type = record_type.upper()\n    if record_type not in TYPES:\n        raise ValueError(\'Unsupported DNS record type: \' + record_type)\n    if transport not in (\'auto\', \'udp\', \'tcp\'):\n        raise ValueError(\'dns.transport must be auto, udp or tcp\')\n    if not (0 < float(timeout) <= 300):\n        raise ValueError(\'DNS timeout must be between 0 and 300 seconds\')\n    if not (1 <= int(port) <= 65535):\n        raise ValueError(\'DNS port must be 1..65535\')\n    server = nameserver or system_nameserver()\n    # Resolver must be an IP literal; avoids silently using another DNS server.\n    ip = ipaddress.ip_address(server)\n    family = socket.AF_INET6 if ip.version == 6 else socket.AF_INET\n    address = (str(ip), int(port), 0, 0) if ip.version == 6 else (str(ip), int(port))\n    transaction_id = random.SystemRandom().randrange(65536)\n    question = encode_name(name) + struct.pack(\'!HH\', TYPES[record_type], 1)\n    packet = struct.pack(\'!HHHHHH\', transaction_id, 0x0100, 1, 0, 0, 1 if dnssec else 0) + question\n    if dnssec:\n        packet += struct.pack(\'!BHHIH\', 0, 41, 1232, 0x8000, 0)\n\n    def exchange(tcp):\n        with socket.socket(family, socket.SOCK_STREAM if tcp else socket.SOCK_DGRAM) as sock:\n            sock.settimeout(float(timeout))\n            if tcp:\n                sock.connect(address)\n                sock.sendall(struct.pack(\'!H\', len(packet)) + packet)\n                def recv_exact(length):\n                    data = b\'\'\n                    while len(data) < length:\n                        chunk = sock.recv(length - len(data))\n                        if not chunk:\n                            raise OSError(\'DNS TCP connection closed early\')\n                        data += chunk\n                    return data\n                length = struct.unpack(\'!H\', recv_exact(2))[0]\n                return recv_exact(length)\n            sock.sendto(packet, address)\n            data, source = sock.recvfrom(65535)\n            if source[0] != str(ip) or source[1] != int(port):\n                raise ValueError(\'Unexpected DNS response source\')\n            return data\n\n    data = exchange(transport == \'tcp\')\n    if len(data) < 12:\n        raise ValueError(\'Truncated DNS response\')\n    tid, flags, qd, an, ns, ar = struct.unpack_from(\'!HHHHHH\', data)\n    if tid != transaction_id or not flags & 0x8000 or (flags >> 11) & 15:\n        raise ValueError(\'Invalid DNS transaction response\')\n    if flags & 0x0200:\n        if transport == \'udp\':\n            raise ValueError(\'DNS UDP response truncated; enable TCP fallback\')\n        data = exchange(True)\n        tid, flags, qd, an, ns, ar = struct.unpack_from(\'!HHHHHH\', data)\n        if tid != transaction_id or not flags & 0x8000 or flags & 0x0200:\n            raise ValueError(\'Invalid or truncated DNS TCP response\')\n    offset = 12\n    for _ in range(qd):\n        _, offset = decode_name(data, offset)\n        if offset + 4 > len(data):\n            raise ValueError(\'Truncated DNS question\')\n        offset += 4\n    answers = []\n    for _ in range(an):\n        owner, offset = decode_name(data, offset)\n        if offset + 10 > len(data):\n            raise ValueError(\'Truncated DNS resource record\')\n        rtype, rclass, ttl, rdlen = struct.unpack_from(\'!HHIH\', data, offset)\n        offset += 10\n        end = offset + rdlen\n        if end > len(data):\n            raise ValueError(\'Truncated DNS record data\')\n        value = None\n        if rclass == 1:\n            if rtype == 1 and rdlen == 4:\n                value = str(ipaddress.IPv4Address(data[offset:end]))\n            elif rtype == 28 and rdlen == 16:\n                value = str(ipaddress.IPv6Address(data[offset:end]))\n            elif rtype in (2, 5, 12):\n                value, _ = decode_name(data, offset)\n            elif rtype == 15 and rdlen >= 3:\n                priority = struct.unpack_from(\'!H\', data, offset)[0]\n                host, _ = decode_name(data, offset + 2)\n                value = f\'{priority} {host}\'\n            elif rtype == 6:\n                primary, pos = decode_name(data, offset)\n                contact, pos = decode_name(data, pos)\n                if pos + 20 > end:\n                    raise ValueError(\'Malformed SOA record\')\n                serial, refresh, retry, expire, minimum = struct.unpack_from(\'!IIIII\', data, pos)\n                value = f\'{primary} {contact} {serial} {refresh} {retry} {expire} {minimum}\'\n            elif rtype == 33 and rdlen >= 7:\n                priority, weight, portnum = struct.unpack_from(\'!HHH\', data, offset)\n                host, _ = decode_name(data, offset + 6)\n                value = f\'{priority} {weight} {portnum} {host}\'\n            elif rtype == 257 and rdlen >= 2:\n                flags_caa = data[offset]\n                taglen = data[offset + 1]\n                if offset + 2 + taglen > end:\n                    raise ValueError(\'Malformed CAA record\')\n                tag = data[offset + 2:offset + 2 + taglen].decode(\'ascii\')\n                val = data[offset + 2 + taglen:end].decode(\'utf-8\', \'replace\')\n                value = f\'{flags_caa} {tag} {val}\'\n            elif rtype == 43 and rdlen >= 4:\n                keytag, algorithm, digesttype = struct.unpack_from(\'!HBB\', data, offset)\n                value = f\'{keytag} {algorithm} {digesttype} {data[offset+4:end].hex().upper()}\'\n            elif rtype == 48 and rdlen >= 4:\n                flags_key, protocol, algorithm = struct.unpack_from(\'!HBB\', data, offset)\n                import base64\n                value = f\'{flags_key} {protocol} {algorithm} {base64.b64encode(data[offset+4:end]).decode()}\'\n            elif rtype == 46 and rdlen >= 18:\n                covered, algorithm, labels, origttl, expiry, inception, keytag = struct.unpack_from(\'!HBBIIIH\', data, offset)\n                signer, pos = decode_name(data, offset + 18)\n                value = f\'{covered} {algorithm} {labels} {origttl} {expiry} {inception} {keytag} {signer} {data[pos:end].hex().upper()}\'\n            elif rtype == 16:\n                chunks, pos = [], offset\n                while pos < end:\n                    length = data[pos]\n                    pos += 1\n                    if pos + length > end:\n                        raise ValueError(\'Malformed DNS TXT record\')\n                    chunks.append(data[pos:pos + length].decode(\'utf-8\', \'replace\'))\n                    pos += length\n                value = \'\'.join(chunks)\n        if value is not None:\n            answers.append({\'name\': owner, \'type\': next(k for k, v in TYPES.items() if v == rtype), \'value\': value, \'ttl\': ttl})\n        offset = end\n    return {\'rcode\': RCODES.get(flags & 15, str(flags & 15)), \'answers\': answers, \'nameserver\': str(ip), \'authenticated_data\': bool(flags & 0x0020)}\n\n\ndef evaluate(cfg, check):\n    dns = cfg.get(\'dns\') or {}\n    if not isinstance(dns, dict):\n        raise ValueError(\'dns must be a mapping\')\n    name = dns.get(\'name\')\n    if not isinstance(name, str) or not name:\n        raise ValueError(\'dns.name is required\')\n    records = dns.get(\'records\')\n    if not isinstance(records, list) or not records:\n        raise ValueError(\'dns.records must be a non-empty list\')\n    failures = []\n    timeout = float(dns.get(\'timeout\', (cfg.get(\'timeouts\') or {}).get(\'connect\', 3)))\n    servers = dns.get(\'compare_nameservers\') or [dns.get(\'nameserver\') or system_nameserver()]\n    if not isinstance(servers, list) or not servers or len(servers) > 16:\n        raise ValueError(\'dns.compare_nameservers must be a list of 1..16 nameservers\')\n    servers = [str(ipaddress.ip_address(server)) for server in servers]\n    compare = bool(dns.get(\'compare_nameservers\'))\n    if compare and len(set(servers)) != len(servers):\n        raise ValueError(\'Duplicate compare_nameservers\')\n    for item in records:\n        if not isinstance(item, dict):\n            raise ValueError(\'Each dns.records item must be a mapping\')\n        kind = str(item.get(\'type\', \'\')).upper()\n        if kind not in TYPES:\n            raise ValueError(\'Unsupported DNS record type: \' + kind)\n        snapshots = []\n        for server in servers:\n            start = time.monotonic()\n            result = query(name, kind, server, dns.get(\'port\', 53), timeout,\n                           dns.get(\'transport\', \'auto\'), dns.get(\'dnssec\', False))\n            elapsed = time.monotonic() - start\n            values = [a[\'value\'] for a in result[\'answers\'] if a[\'type\'] == kind and a[\'name\'].rstrip(\'.\').lower() == name.rstrip(\'.\').lower()]\n            prefix = f\'DNS {kind} {name} [{server}]\'\n            expected_rcode = str(item.get(\'rcode\', \'NOERROR\')).upper()\n            check(result[\'rcode\'] == expected_rcode, f\'{prefix}: RCODE {result["rcode"]} != {expected_rcode}\', failures)\n            if \'max_response_time\' in item:\n                check(elapsed <= float(item[\'max_response_time\']), f\'{prefix}: response time {elapsed:.3f}s exceeds {item["max_response_time"]}s\', failures)\n            if \'authenticated_data\' in item:\n                check(result[\'authenticated_data\'] == item[\'authenticated_data\'], f\'{prefix}: DNSSEC AD flag mismatch\', failures)\n            if \'min_count\' in item:\n                check(len(values) >= int(item[\'min_count\']), f\'{prefix}: record count {len(values)} below {item["min_count"]}\', failures)\n            if \'max_count\' in item:\n                check(len(values) <= int(item[\'max_count\']), f\'{prefix}: record count {len(values)} above {item["max_count"]}\', failures)\n            for value in item.get(\'contains\', []):\n                check(any(str(value) in actual for actual in values), f\'{prefix}: no record contains {value!r}\', failures)\n            for value in item.get(\'not_contains\', []):\n                check(all(str(value) not in actual for actual in values), f\'{prefix}: forbidden record content {value!r}\', failures)\n            for value in item.get(\'equals\', []):\n                check(str(value).rstrip(\'.\') in [v.rstrip(\'.\') for v in values], f\'{prefix}: expected record {value!r} missing\', failures)\n            for value in item.get(\'not_equals\', []):\n                check(str(value).rstrip(\'.\') not in [v.rstrip(\'.\') for v in values], f\'{prefix}: forbidden record {value!r} present\', failures)\n            if item.get(\'exists\') is True:\n                check(bool(values), f\'{prefix}: no records found\', failures)\n            if item.get(\'exists\') is False:\n                check(not values, f\'{prefix}: unexpected records found\', failures)\n            if \'min_ttl\' in item:\n                for answer in result[\'answers\']:\n                    if answer[\'type\'] == kind and answer[\'name\'].rstrip(\'.\').lower() == name.rstrip(\'.\').lower():\n                        check(answer[\'ttl\'] >= int(item[\'min_ttl\']), f\'{prefix}: TTL {answer["ttl"]} below {item["min_ttl"]}\', failures)\n            snapshots.append((result[\'rcode\'], sorted(set(values))))\n        if compare and dns.get(\'require_identical\', True):\n            for idx in range(1, len(snapshots)):\n                check(snapshots[idx] == snapshots[0], f\'DNS {kind} {name}: nameserver mismatch {servers[0]} vs {servers[idx]}\', failures)\n    return failures\n', "<embedded dns_probe>", "exec"), _ip_dns.__dict__)
_ip_sys.modules["dns_probe"] = _ip_dns
import dns_probe


def check(condition, message, failures):
    if not condition:
        failures.append(message)




def validate_resolve(cfg, parsed):
    mapping = (cfg.get('connection') or {}).get('resolve') or {}
    if not isinstance(mapping, dict):
        raise ValueError('connection.resolve must be a mapping')
    if not mapping:
        return None
    # A single URL host is supported; DNS override is per session and does not alter system DNS.
    if len(mapping) != 1 or parsed.hostname not in mapping:
        raise ValueError('connection.resolve must contain exactly the URL hostname')
    address = str(mapping[parsed.hostname])
    try:
        ipaddress.ip_address(address)
    except ValueError:
        raise ValueError('connection.resolve must specify an IPv4 or IPv6 address')
    return address


class ResolvedHTTPSConnection(HTTPSConnection):
    target_ip = None
    def _new_conn(self):
        from urllib3.util.connection import create_connection
        return create_connection((self.target_ip, self.port), self.timeout, source_address=self.source_address, socket_options=self.socket_options)


class ResolvedHTTPConnection(HTTPConnection):
    target_ip = None
    def _new_conn(self):
        from urllib3.util.connection import create_connection
        return create_connection((self.target_ip, self.port), self.timeout, source_address=self.source_address, socket_options=self.socket_options)


class ResolveAdapter(HTTPAdapter):
    def __init__(self, target_ip, scheme, *args, **kwargs):
        self.target_ip = target_ip
        self.scheme = scheme
        super().__init__(*args, **kwargs)

    def init_poolmanager(self, connections, maxsize, block=False, **pool_kwargs):
        from urllib3.connectionpool import HTTPSConnectionPool, HTTPConnectionPool
        from urllib3.poolmanager import PoolManager
        target = self.target_ip
        base = ResolvedHTTPSConnection if self.scheme == 'https' else ResolvedHTTPConnection
        custom_conn = type('TargetConnection', (base,), {'target_ip': target})
        pool_class = type('TargetPool', (HTTPSConnectionPool if self.scheme == 'https' else HTTPConnectionPool,), {'ConnectionCls': custom_conn})
        self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize, block=block, **pool_kwargs)
        self.poolmanager.pool_classes_by_scheme = dict(self.poolmanager.pool_classes_by_scheme)
        self.poolmanager.pool_classes_by_scheme[self.scheme] = pool_class


def check_extra(response, tests, failures):
    response_tests = tests.get('response') or {}
    size = len(response.content)
    if 'min_bytes' in response_tests:
        check(size >= int(response_tests['min_bytes']), f'Response size {size} below minimum {response_tests["min_bytes"]}', failures)
    if 'max_bytes' in response_tests:
        check(size <= int(response_tests['max_bytes']), f'Response size {size} above maximum {response_tests["max_bytes"]}', failures)
    if 'content_type' in response_tests:
        actual = response.headers.get('Content-Type', '').split(';')[0].strip().lower()
        expected = str(response_tests['content_type']).lower()
        check(actual == expected, f'Content-Type {actual!r} != {expected!r}', failures)

    redirects = tests.get('redirects') or {}
    history = response.history
    if 'max_count' in redirects:
        check(len(history) <= int(redirects['max_count']), f'Redirect count {len(history)} exceeds {redirects["max_count"]}', failures)
    if redirects.get('require_https'):
        for item in list(history) + [response]:
            check(urlsplit(item.url).scheme == 'https', f'Non-HTTPS redirect chain URL: {item.url}', failures)
    if 'allowed_hosts' in redirects:
        allowed = redirects['allowed_hosts']
        for item in list(history) + [response]:
            check(urlsplit(item.url).hostname in allowed, f'Unexpected redirect host: {urlsplit(item.url).hostname}', failures)
    if 'final_url' in redirects:
        check(response.url == redirects['final_url'], f'Final URL {response.url!r} differs from expected', failures)

    jt = tests.get('json') or {}
    if jt:
        try:
            document = response.json()
        except ValueError:
            failures.append('Response body is not valid JSON')
            document = None
        if document is not None:
            for rule in jt.get('paths', []):
                path = rule['path']
                current = document
                found = True
                for segment in str(path).split('.'):
                    if isinstance(current, dict) and segment in current:
                        current = current[segment]
                    elif isinstance(current, list) and segment.isdecimal() and int(segment) < len(current):
                        current = current[int(segment)]
                    else:
                        found = False
                        break
                if 'exists' in rule:
                    check(found == rule['exists'], f'JSON path {path!r} existence mismatch', failures)
                if not found:
                    if rule.get('exists') is not False:
                        failures.append(f'Missing JSON path: {path}')
                    continue
                if 'equals' in rule:
                    check(type(current) is type(rule['equals']) and current == rule['equals'], f'JSON path {path!r} value mismatch', failures)
                if 'min_items' in rule:
                    check(isinstance(current, (list, dict)) and len(current) >= int(rule['min_items']), f'JSON path {path!r} has too few items', failures)
                if 'max_items' in rule:
                    check(isinstance(current, (list, dict)) and len(current) <= int(rule['max_items']), f'JSON path {path!r} has too many items', failures)

    cookie_rules = tests.get('cookies') or {}
    if cookie_rules:
        # requests folds duplicate Set-Cookie headers; use raw headers when available.
        raw = response.raw.headers
        values = raw.getlist('Set-Cookie') if hasattr(raw, 'getlist') else ([response.headers['Set-Cookie']] if 'Set-Cookie' in response.headers else [])
        cookies = SimpleCookie()
        for value in values:
            try:
                cookies.load(value)
            except Exception:
                failures.append('Invalid Set-Cookie header')
        for name, rule in (cookie_rules.get('require') or {}).items():
            check(name in cookies, f'Missing cookie: {name}', failures)
            if name in cookies:
                for flag in ('secure', 'httponly'):
                    if rule.get(flag):
                        check(bool(cookies[name][flag]), f'Cookie {name} missing {flag}', failures)
                if 'samesite' in rule:
                    check(cookies[name]['samesite'].lower() == str(rule['samesite']).lower(), f'Cookie {name} has wrong SameSite', failures)

    security = tests.get('security') or {}
    if 'hsts_min_age' in security:
        value = response.headers.get('Strict-Transport-Security', '')
        match = re.search(r'(?:^|;)\s*max-age\s*=\s*(\d+)', value, re.I)
        check(bool(match) and int(match.group(1)) >= int(security['hsts_min_age']), 'HSTS max-age missing or too small', failures)


def validate_tls_config(tls):
    versions = {'TLSv1.2': ssl.TLSVersion.TLSv1_2, 'TLSv1.3': ssl.TLSVersion.TLSv1_3}
    for field in ('min_version', 'max_version'):
        if field in tls and tls[field] not in versions:
            raise ValueError(f'tls.{field} must be TLSv1.2 or TLSv1.3')
    if 'min_version' in tls and 'max_version' in tls:
        if versions[tls['min_version']] > versions[tls['max_version']]:
            raise ValueError('tls.min_version exceeds tls.max_version')
    if tls.get('verify') is False and 'min_valid_days' in tls:
        raise ValueError('tls.min_valid_days requires tls.verify: true')


def inspect_tls(host, address, port, tls, timeout, failures):
    versions = {'TLSv1.2': ssl.TLSVersion.TLSv1_2, 'TLSv1.3': ssl.TLSVersion.TLSv1_3}
    verify = tls.get('verify', True)
    ctx = ssl.create_default_context() if verify else ssl._create_unverified_context()
    if 'ca_file' in tls and verify:
        ctx.load_verify_locations(cafile=tls['ca_file'])
    if 'min_version' in tls:
        ctx.minimum_version = versions[tls['min_version']]
    if 'max_version' in tls:
        ctx.maximum_version = versions[tls['max_version']]
    with socket.create_connection((address, port), timeout=timeout) as sock:
        sock.settimeout(timeout)
        with ctx.wrap_socket(sock, server_hostname=host) as secured:
            version = secured.version()
            cipher = secured.cipher()[0]
            cert = secured.getpeercert()
            der = secured.getpeercert(binary_form=True)
    cipher_rules = tls.get('cipher') or {}
    if 'allow' in cipher_rules:
        check(cipher in cipher_rules['allow'], f'TLS cipher {cipher!r} not allowed', failures)
    if 'deny' in cipher_rules:
        check(cipher not in cipher_rules['deny'], f'TLS cipher {cipher!r} denied', failures)
    cr = tls.get('certificate') or {}
    if 'fingerprint_sha256' in cr:
        expected = str(cr['fingerprint_sha256']).replace(':', '').lower()
        actual = hashlib.sha256(der).hexdigest()
        check(actual == expected, 'TLS certificate SHA256 fingerprint mismatch', failures)
    if not verify and any(k in cr for k in ('issuer_contains', 'subject_contains', 'san_contains')):
        raise ValueError('Certificate issuer/subject/SAN assertions require tls.verify: true')
    if verify:
        if 'min_valid_days' in tls:
            expiry = datetime.fromtimestamp(ssl.cert_time_to_seconds(cert['notAfter']), tz=timezone.utc)
            remaining = (expiry - datetime.now(timezone.utc)).total_seconds() / 86400
            check(remaining >= float(tls['min_valid_days']), f'TLS certificate expires in {remaining:.1f} days (minimum {tls["min_valid_days"]})', failures)
        def dn_string(field):
            return ', '.join(f'{k}={v}' for rdn in cert.get(field, ()) for k, v in rdn)
        for field, cert_field in (('issuer_contains', 'issuer'), ('subject_contains', 'subject')):
            if field in cr:
                check(str(cr[field]) in dn_string(cert_field), f'TLS certificate {cert_field} missing {cr[field]!r}', failures)
        if 'san_contains' in cr:
            names = [value for typ, value in cert.get('subjectAltName', ()) if typ == 'DNS']
            for expected in cr['san_contains']:
                check(expected in names, f'TLS certificate SAN missing {expected!r}', failures)
    return version, cipher


# Evidence is opt-in, bounded, and restricted to non-secret metadata.
_EVIDENCE = threading.local()
SAFE_HEADERS = {'content-type', 'cache-control', 'strict-transport-security', 'x-content-type-options', 'x-frame-options', 'content-encoding', 'server'}

def structured_assertions(response, rules, failures):
    """Small declarative assertion vocabulary; no eval, scripting or external libraries."""
    if not isinstance(rules, list) or len(rules) > 64:
        raise ValueError('tests.structured must be a list of at most 64 rules')
    seen = set()
    for rule in rules:
        if not isinstance(rule, dict) or set(rule) - {'id', 'type', 'path', 'header', 'expected', 'operator', 'pattern', 'severity'}:
            raise ValueError('invalid structured assertion')
        ident = rule.get('id')
        if not isinstance(ident, str) or not re.fullmatch(r'[A-Za-z0-9_.-]{1,80}', ident) or ident in seen:
            raise ValueError('structured assertion IDs must be unique and alphanumeric')
        seen.add(ident)
        kind = rule.get('type')
        if kind not in ('status', 'header', 'body_regex', 'json_value'):
            raise ValueError('unsupported structured assertion type')
        if kind == 'status':
            actual = response.status_code
        elif kind == 'header':
            header = str(rule.get('header', ''))
            if not header or any(c in header for c in '\r\n'):
                raise ValueError('invalid assertion header')
            actual = response.headers.get(header)
        elif kind == 'body_regex':
            pattern = rule.get('pattern')
            if not isinstance(pattern, str) or len(pattern) > 256 or len(response.content) > 1048576:
                raise ValueError('body_regex requires a pattern <=256 chars and body <=1 MiB')
            actual = bool(re.search(pattern, response.text))
        else:
            path = rule.get('path')
            if not isinstance(path, str) or not re.fullmatch(r'[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]+){0,15}', path):
                raise ValueError('json_value.path must be a simple dot-separated object path')
            obj = response.json()
            for part in path.split('.'):
                obj = obj.get(part) if isinstance(obj, dict) else None
            actual = obj
        operator = rule.get('operator', 'eq')
        expected = rule.get('expected', True if kind == 'body_regex' else None)
        if operator == 'eq':
            passed = actual == expected
        elif operator == 'ne':
            passed = actual != expected
        elif operator in ('gt', 'ge', 'lt', 'le') and type(actual) in (int, float) and type(expected) in (int, float):
            passed = {'gt': actual > expected, 'ge': actual >= expected, 'lt': actual < expected, 'le': actual <= expected}[operator]
        else:
            raise ValueError('invalid assertion operator or numeric operands')
        if not passed:
            # No raw actual/expected values: JSON and headers may contain secrets.
            failures.append('ASSERT[%s] %s %s failed' % (ident, kind, operator))

def capture_evidence(cfg, protocol, response=None):
    options = cfg.get('evidence') or {}
    if not options:
        return {}
    if not isinstance(options, dict) or set(options) - {'http_headers', 'tls_fingerprint', 'dns_rrset'}:
        raise ValueError('evidence supports only http_headers, tls_fingerprint, dns_rrset')
    result = {}
    if response is not None:
        result['http_status'] = response.status_code
        names = options.get('http_headers') or []
        if not isinstance(names, list) or len(names) > 12 or any(str(n).lower() not in SAFE_HEADERS for n in names):
            raise ValueError('evidence.http_headers must list up to 12 approved non-sensitive headers')
        result['http_headers'] = {str(n).lower(): response.headers.get(str(n), '')[:256] for n in names}
    if protocol == 'https' and options.get('tls_fingerprint'):
        parsed = urlsplit(cfg['url'])
        host, port = parsed.hostname, parsed.port or 443
        tls = cfg.get('tls') or {}
        context = ssl.create_default_context(cafile=tls.get('ca_file')) if tls.get('verify', True) else ssl._create_unverified_context()
        with socket.create_connection((host, port), timeout=float((cfg.get('timeouts') or {}).get('connect', 3))) as sock:
            with context.wrap_socket(sock, server_hostname=host) as wrapped:
                result['tls_sha256'] = hashlib.sha256(wrapped.getpeercert(binary_form=True)).hexdigest()
    if protocol == 'dns' and options.get('dns_rrset'):
        d = cfg['dns']
        name = d.get('name')
        typ = d.get('type', 'A')
        if not isinstance(name, str) or typ not in ('A', 'AAAA', 'CNAME', 'MX', 'NS', 'CAA'):
            raise ValueError('dns_rrset requires dns.name and a supported public record type')
        reply = dns_probe.query(name, typ, nameserver=d.get('nameserver'), timeout=float((cfg.get('timeouts') or {}).get('response', 3)))
        result['dns_rrset'] = sorted(str(a.get('value')) for a in reply.get('answers', []) if a.get('value') is not None)[:64]
    return result

def evaluate(cfg):
    failures = []
    if 'dns' in cfg:
        if 'url' in cfg:
            raise ValueError('DNS configurations must not contain url')
        start = time.monotonic()
        failures.extend(dns_probe.evaluate(cfg, check))
        _EVIDENCE.value = capture_evidence(cfg, 'dns')
        return failures, time.monotonic() - start
    url = cfg['url']
    parsed = urlsplit(url)
    if parsed.scheme not in ('tcp', 'http', 'https') or not parsed.hostname:
        raise ValueError('url must use tcp://, http:// or https:// with a host')
    timeout_cfg = cfg.get('timeouts') or {}
    connect_timeout = float(timeout_cfg.get('connect', 3))
    response_timeout = float(timeout_cfg.get('response', 10))
    if min(connect_timeout, response_timeout) <= 0:
        raise ValueError('timeouts must be positive')
    host = parsed.hostname
    port = parsed.port or {'http': 80, 'https': 443}.get(parsed.scheme)
    if port is None:
        raise ValueError('TCP URL requires an explicit port')
    if parsed.scheme == 'tcp':
        start = time.monotonic()
        with socket.create_connection((host, port), timeout=connect_timeout):
            pass
        elapsed = time.monotonic() - start
        check(elapsed <= response_timeout, f'TCP elapsed {elapsed:.3f}s > {response_timeout}s', failures)
        _EVIDENCE.value = {}
        return failures, elapsed

    target_ip = validate_resolve(cfg, parsed)
    if target_ip and (cfg.get('request') or {}).get('follow_redirects'):
        raise ValueError('connection.resolve and request.follow_redirects cannot be combined (redirect target isolation)')
    tls = cfg.get('tls') or {}
    verify = tls.get('ca_file') if tls.get('verify', True) else False
    if parsed.scheme == 'https':
        validate_tls_config(tls)
        if any(k in tls for k in ('min_valid_days', 'min_version', 'max_version', 'certificate', 'cipher')):
            inspect_tls(host, target_ip or host, port, tls, connect_timeout, failures)

    req = cfg.get('request') or {}
    method = str(req.get('method', 'GET')).upper()
    if method not in ('GET', 'POST'):
        raise ValueError('Only GET and POST are supported')
    headers = dict(req.get('headers') or {})
    if req.get('user_agent'):
        headers['User-Agent'] = str(req['user_agent'])
    auth_cfg = cfg.get('auth') or {}
    if not isinstance(auth_cfg, dict):
        raise ValueError('auth must be a mapping')
    auth_type = str(auth_cfg.get('type', 'none')).lower()
    if auth_type not in ('none', 'basic', 'bearer'):
        raise ValueError('auth.type must be none, basic or bearer')
    if auth_type != 'none' and any(k.lower() == 'authorization' for k in headers):
        raise ValueError('Do not combine auth with a manual Authorization header')

    def secret(field):
        literal, env_name = auth_cfg.get(field), auth_cfg.get(field + '_env')
        if (literal is None) == (env_name is None):
            raise ValueError(f'auth requires exactly one of {field} or {field}_env')
        if env_name is not None:
            value = os.environ.get(str(env_name))
            if not value:
                raise ValueError(f'Missing or empty environment variable for auth.{field}')
            return value
        if not isinstance(literal, str) or not literal:
            raise ValueError(f'auth.{field} must be a non-empty string')
        return literal

    request_auth = None
    if auth_type == 'basic':
        request_auth = requests.auth.HTTPBasicAuth(secret('username'), secret('password'))
    elif auth_type == 'bearer':
        token = secret('token')
        if '\r' in token or '\n' in token:
            raise ValueError('Bearer token contains invalid characters')
        headers['Authorization'] = f'Bearer {token}'
    # requests timeout=(connect, read) is an inactivity timeout, NOT a total deadline.
    # We enforce an overall deadline by running the request in a daemon thread.
    from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeout
    executor = ThreadPoolExecutor(max_workers=1)
    def send():
        with requests.Session() as session:
            session.trust_env = False
            if target_ip:
                session.mount(f"{parsed.scheme}://{parsed.netloc}", ResolveAdapter(target_ip, parsed.scheme))
            return session.request(method, url, headers=headers, auth=request_auth, data=req.get('body'),
                                   json=req.get('json'), timeout=(connect_timeout, response_timeout),
                                   verify=verify, allow_redirects=bool(req.get('follow_redirects', False)))
    start = time.monotonic()
    future = executor.submit(send)
    try:
        response = future.result(timeout=response_timeout)
    except FutureTimeout:
        future.cancel()
        raise TimeoutError(f'overall response deadline exceeded ({response_timeout}s)')
    finally:
        executor.shutdown(wait=False, cancel_futures=True)
    elapsed = time.monotonic() - start
    tests = cfg.get('tests') or {}
    status = tests.get('status') or {}
    if status.get('allow') is not None:
        check(response.status_code in status['allow'], f'HTTP {response.status_code} not in allowed statuses {status["allow"]}', failures)
    if status.get('deny') is not None:
        check(response.status_code not in status['deny'], f'HTTP {response.status_code} is denied', failures)
    htests = tests.get('headers') or {}
    for key in htests.get('exists', []):
        check(key in response.headers, f'Missing header: {key}', failures)
    for key in htests.get('absent', []):
        check(key not in response.headers, f'Forbidden header present: {key}', failures)
    for key, needles in (htests.get('contains') or {}).items():
        value = response.headers.get(key, '')
        for needle in needles:
            check(str(needle) in value, f'Header {key} does not contain {needle!r}', failures)
    for key, needles in (htests.get('not_contains') or {}).items():
        value = response.headers.get(key, '')
        for needle in needles:
            check(str(needle) not in value, f'Header {key} contains forbidden {needle!r}', failures)
    body = tests.get('body') or {}
    for needle in body.get('contains', []):
        check(str(needle) in response.text, f'Body does not contain {needle!r}', failures)
    for needle in body.get('not_contains', []):
        check(str(needle) not in response.text, f'Body contains forbidden {needle!r}', failures)
    check_extra(response, tests, failures)
    structured_assertions(response, tests.get('structured') or [], failures)
    _EVIDENCE.value = capture_evidence(cfg, parsed.scheme, response)
    return failures, elapsed


OUTPUTS = ('text', 'nagios', 'icinga2', 'checkmk', 'json')


def monitoring_config(cfg, override=None):
    """Validate monitoring settings without executing any network operations."""
    m = cfg.get('monitoring') or {}
    if not isinstance(m, dict):
        raise ValueError('monitoring must be a mapping')
    mode = override or m.get('output', 'text')
    if mode not in OUTPUTS:
        raise ValueError('monitoring.output must be one of: ' + ', '.join(OUTPUTS))
    name = m.get('service_name', cfg.get('name', 'ipsonic-probe'))
    if not isinstance(name, str) or not name.strip() or any(c in name for c in '\r\n'):
        raise ValueError('monitoring.service_name must be a non-empty single-line string')
    thresholds = (m.get('thresholds') or {}).get('response_time') or {}
    if not isinstance(thresholds, dict):
        raise ValueError('monitoring.thresholds.response_time must be a mapping')
    for k in thresholds:
        if k not in ('warning', 'critical'):
            raise ValueError('Unknown response_time threshold: ' + str(k))
    for k, value in thresholds.items():
        if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or value <= 0:
            raise ValueError('response_time.' + k + ' must be a positive finite number of seconds')
    if 'warning' in thresholds and 'critical' in thresholds and thresholds['warning'] >= thresholds['critical']:
        raise ValueError('response_time.warning must be less than critical')
    on_failure = m.get('on_failure', 'critical')
    if on_failure not in ('info', 'warning', 'critical'):
        raise ValueError('monitoring.on_failure must be info, warning, or critical')
    rules = m.get('assertions', [])
    if not isinstance(rules, list):
        raise ValueError('monitoring.assertions must be a list')
    for index, rule in enumerate(rules):
        if not isinstance(rule, dict) or 'severity' not in rule or (('contains' in rule) == ('id' in rule)) or set(rule) - {'contains', 'id', 'severity'}:
            raise ValueError('monitoring.assertions[%d] requires severity and exactly one of contains or id' % index)
        key = 'id' if 'id' in rule else 'contains'
        if not isinstance(rule[key], str) or not rule[key] or any(c in rule[key] for c in '\r\n'):
            raise ValueError('monitoring.assertions[%d].%s must be non-empty single-line text' % (index, key))
        if rule['severity'] not in ('info', 'warning', 'critical'):
            raise ValueError('monitoring.assertions[%d].severity must be info, warning, or critical' % index)
    return mode, name, thresholds


def assertion_id(message):
    # Stable category identifiers, independent of dynamic response values.
    if message.startswith('DNS '):
        match = re.match(r'^DNS (\w+) ', message)
        kind = match.group(1).lower() if match else 'unknown'
        if 'nameserver mismatch' in message:
            return 'dns.' + kind + '.comparison'
        if 'RCODE ' in message:
            return 'dns.' + kind + '.rcode'
        if 'TTL ' in message:
            return 'dns.' + kind + '.ttl'
        if 'response time ' in message:
            return 'dns.' + kind + '.response_time'
        if 'DNSSEC AD flag' in message:
            return 'dns.' + kind + '.dnssec_ad'
        return 'dns.' + kind + '.record'
    if message.startswith('ASSERT['):
        return message.split(']', 1)[0][7:]
    if message.startswith('HTTP '):
        return 'http.status'
    if message.startswith('Body '):
        return 'http.body'
    if message.startswith('Header ') or message.startswith('Missing header:'):
        return 'http.header'
    if message.startswith('Response time '):
        return 'response.time'
    return 'probe.assertion'


def severity_for_failure(message, monitoring):
    """Resolve an individual failed assertion to its monitoring severity.

    Ordered rules match literal substrings of the diagnostic message; the
    first matching rule wins. A nonmatching failure uses on_failure.
    """
    for rule in monitoring.get('assertions', []):
        if ('contains' in rule and rule['contains'] in message) or ('id' in rule and rule['id'] == assertion_id(message)):
            return rule['severity']
    return monitoring.get('on_failure', 'critical')


def evaluate_with_execution(cfg):
    if not cfg.get('execution'):
        return evaluate(cfg)
    execution = cfg.get('execution') or {}
    if not isinstance(execution, dict):
        raise ValueError('execution must be a mapping')
    retries = execution.get('retries', 0)
    delay = execution.get('retry_delay', 0)
    required = execution.get('success_required', 1)
    if any(isinstance(x, bool) or not isinstance(x, int) for x in (retries, required)) or not 0 <= retries <= 20 or not 1 <= required <= retries + 1:
        raise ValueError('execution retries/success_required out of range')
    if isinstance(delay, bool) or not isinstance(delay, (int, float)) or not math.isfinite(delay) or not 0 <= delay <= 60:
        raise ValueError('execution.retry_delay must be 0..60 seconds')
    backends = execution.get('backends')
    if backends is not None and (not isinstance(backends, list) or not backends or len(backends) > 32):
        raise ValueError('execution.backends must be a list of 1..32 mappings')
    targets = backends if backends is not None else [None]
    observations = []
    total_elapsed = 0.0
    all_failures = []
    for backend in targets:
        probe = copy.deepcopy(cfg)
        label = ''
        if backend is not None:
            if not isinstance(backend, dict) or set(backend) - {'name', 'url', 'nameserver', 'resolve'}:
                raise ValueError('Invalid execution backend')
            label = str(backend.get('name', backend.get('url', backend.get('nameserver', 'backend'))))
            if 'url' in backend:
                if 'dns' in probe:
                    raise ValueError('DNS backend cannot override url')
                probe['url'] = backend['url']
            if 'nameserver' in backend:
                if 'dns' not in probe:
                    raise ValueError('nameserver backend requires dns configuration')
                probe['dns']['nameserver'] = backend['nameserver']
            if 'resolve' in backend:
                probe.setdefault('connection', {})['resolve'] = backend['resolve']
        success = 0
        last_failures = []
        for attempt in range(retries + 1):
            if attempt and delay:
                time.sleep(delay)
                total_elapsed += delay
            try:
                failures, elapsed = evaluate(probe)
                observations.append(getattr(_EVIDENCE, 'value', {}))
            except (OSError, ValueError, KeyError, TypeError, requests.RequestException, ssl.SSLError, TimeoutError) as exc:
                failures, elapsed = [f'{type(exc).__name__}: {exc}'], 0.0
            total_elapsed += elapsed
            if not failures:
                success += 1
            else:
                last_failures = failures
        if success < required:
            prefix = ('Backend ' + label + ': ') if backend is not None else ''
            all_failures.extend(prefix + msg for msg in (last_failures or ['insufficient successful attempts']))
            all_failures.append(prefix + f'successful attempts {success}/{retries+1}, required {required}')
    _EVIDENCE.value = observations[0] if len(observations) == 1 else {'backends': observations} if observations else {}
    return all_failures, total_elapsed


def make_result(path, cfg, override=None):
    mode, name, thresholds = monitoring_config(cfg, override)
    monitoring = cfg.get('monitoring') or {}
    start = time.monotonic()
    details = []
    evidence = {}
    def run_check():
        outcome = evaluate_with_execution(cfg)
        return outcome, getattr(_EVIDENCE, 'value', {})
    try:
        total_budget = (cfg.get('timeouts') or {}).get('total')
        if total_budget is not None:
            executor = ThreadPoolExecutor(max_workers=1)
            future = executor.submit(run_check)
            try:
                (failures, elapsed), evidence = future.result(timeout=float(total_budget))
            except FutureTimeout:
                future.cancel()
                raise TimeoutError('Total check deadline exceeded (%ss)' % total_budget)
            finally:
                executor.shutdown(wait=False, cancel_futures=True)
        else:
            (failures, elapsed), evidence = run_check()
        for message in failures:
            details.append({'id': assertion_id(message), 'message': message, 'severity': severity_for_failure(message, monitoring)})
        state = max(({'info': 0, 'warning': 1, 'critical': 2}[item['severity']] for item in details), default=0)
        # Thresholds are evaluated independently, including when assertions fail.
        if 'critical' in thresholds and elapsed > thresholds['critical']:
            state = max(state, 2)
            message = 'Response time %.3fs exceeds critical threshold %ss' % (elapsed, thresholds['critical'])
            failures.append(message)
            details.append({'id': 'response.time', 'message': message, 'severity': 'critical'})
        elif 'warning' in thresholds and elapsed > thresholds['warning']:
            state = max(state, 1)
            message = 'Response time %.3fs exceeds warning threshold %ss' % (elapsed, thresholds['warning'])
            failures.append(message)
            details.append({'id': 'response.time', 'message': message, 'severity': 'warning'})
    except (OSError, ValueError, KeyError, TypeError, requests.RequestException, ssl.SSLError, TimeoutError, yaml.YAMLError) as exc:
        state, elapsed = 3, time.monotonic() - start
        failures = ['%s: %s' % (type(exc).__name__, exc)]
        details = [{'id': 'probe.error', 'message': failures[0], 'severity': 'unknown'}]
    informational = bool(failures) and state == 0
    return {'file': str(path), 'service_name': name, 'output': mode, 'status': ('OK', 'WARNING', 'CRITICAL', 'UNKNOWN')[state],
            'informational_failure': informational, 'code': state, 'elapsed_seconds': round(elapsed, 6), 'failures': failures, 'assertion_results': details, 'thresholds': thresholds, 'schema_version': 1, 'evidence': evidence}


def render(result, mode):
    code = result['code']
    status = result['status']
    name = result['service_name']
    elapsed = result['elapsed_seconds']
    issues = result['failures']
    summary = '; '.join(('[%s] %s' % (item['severity'].upper(), item['message'])).replace('\n', ' ').replace('\r', ' ') for item in result.get('assertion_results', [])) if issues and result.get('assertion_results') else ('; '.join(str(x).replace('\n', ' ').replace('\r', ' ') for x in issues) if issues else 'all assertions passed')
    if result.get('informational_failure'):
        summary = 'INFO - ' + summary
    summary = summary.replace('|', '/')
    t = result['thresholds']
    perf = 'response_time=%.3fs;%s;%s;0;' % (elapsed, t.get('warning', ''), t.get('critical', ''))
    meta = result.get('metadata') or {}
    context = ' '.join('%s=%s' % (k, str(meta[k]).replace('\n', ' ').replace('\r', ' ').replace('|', '/')) for k in ('owner', 'environment', 'runbook') if meta.get(k)) if code else ''
    if context:
        summary += ' [' + context + ']'
    if mode in ('nagios', 'icinga2'):
        return '%s - %s: %s | %s' % (status, name, summary, perf)
    if mode == 'checkmk':
        # Local check format: state "service name" perfdata description.
        safe_name = name.replace('"', "'")
        return '%d "%s" %s %s' % (code, safe_name, perf, summary)
    if mode == 'json':
        return json.dumps(result, ensure_ascii=False)
    return '%s %s (%.3fs)%s' % (status, result['file'], elapsed, (': ' + summary) if issues else '')



def validate_config(cfg, override=None):
    """Validate configuration locally; never open sockets or resolve DNS."""
    if not isinstance(cfg, dict):
        raise ValueError('YAML root must be a mapping')
    monitoring_config(cfg, override)
    # Optional explicit protocol label. Legacy YAML without `type` remains supported.
    declared = cfg.get('type')
    if declared is not None:
        if not isinstance(declared, str) or declared not in ('dns', 'tcp', 'http', 'https'):
            raise ValueError('type must be dns, tcp, http or https')
        actual = 'dns' if 'dns' in cfg and 'url' not in cfg else (
            urlsplit(cfg['url']).scheme if isinstance(cfg.get('url'), str) else None)
        if declared != actual:
            raise ValueError('type %s does not match target protocol %s' % (declared, actual))
    if 'dns' in cfg and any(k in cfg for k in ('request', 'auth', 'tls', 'connection', 'proxy')):
        raise ValueError('DNS checks cannot use HTTP/TLS/request/auth/connection/proxy settings')
    if 'url' in cfg and isinstance(cfg['url'], str) and urlsplit(cfg['url']).scheme == 'tcp' and any(k in cfg for k in ('request', 'auth', 'tls', 'proxy')):
        raise ValueError('TCP checks cannot use HTTP/TLS/request/auth/proxy settings')
    if ('dns' in cfg) == ('url' in cfg):
        raise ValueError('Specify exactly one of dns or url')
    if 'dns' in cfg:
        if not isinstance(cfg['dns'], dict) or not cfg['dns']:
            raise ValueError('dns must be a non-empty mapping')
    else:
        url = cfg['url']
        if not isinstance(url, str):
            raise ValueError('url must be a string')
        try:
            parsed = urlsplit(url)
            port = parsed.port
        except ValueError as exc:
            raise ValueError('Invalid URL: ' + str(exc)) from exc
        if parsed.scheme not in ('tcp', 'http', 'https') or not parsed.hostname:
            raise ValueError('url must use tcp://, http:// or https:// with a host')
        if parsed.username or parsed.password:
            raise ValueError('Credentials in URLs are not supported; use auth')
        if parsed.scheme == 'tcp' and port is None:
            raise ValueError('TCP URL requires an explicit port')
        if parsed.scheme == 'tcp' and (parsed.path or parsed.query or parsed.fragment):
            raise ValueError('TCP URL must contain only a host and port')
        if parsed.scheme != 'tcp':
            validate_resolve(cfg, parsed)
            req = cfg.get('request') or {}
            if not isinstance(req, dict):
                raise ValueError('request must be a mapping')
            if str(req.get('method', 'GET')).upper() not in ('GET', 'POST'):
                raise ValueError('Only GET and POST are supported')
            if (cfg.get('connection') or {}).get('resolve') and req.get('follow_redirects'):
                raise ValueError('connection.resolve and request.follow_redirects cannot be combined')
            auth = cfg.get('auth') or {}
            if not isinstance(auth, dict) or auth.get('type', 'none') not in ('none', 'basic', 'bearer'):
                raise ValueError('auth.type must be none, basic or bearer')
            for field in (('username', 'password') if auth.get('type') == 'basic' else ('token',) if auth.get('type') == 'bearer' else ()):
                if (field in auth) == (field + '_env' in auth):
                    raise ValueError('auth requires exactly one of %s or %s_env' % (field, field))
            tls = cfg.get('tls') or {}
            if not isinstance(tls, dict):
                raise ValueError('tls must be a mapping')
            if parsed.scheme == 'https':
                validate_tls_config(tls)
        # Local configuration checks apply to TCP and HTTP(S).
    timeouts = cfg.get('timeouts') or {}
    if not isinstance(timeouts, dict):
        raise ValueError('timeouts must be a mapping')
    for key in ('connect', 'response', 'total'):
        if key in timeouts:
            try:
                value = float(timeouts[key])
            except (TypeError, ValueError) as exc:
                raise ValueError('timeouts.%s must be a positive finite number' % key) from exc
            if not math.isfinite(value) or value <= 0:
                raise ValueError('timeouts.%s must be a positive finite number' % key)
    evidence = cfg.get('evidence') or {}
    if not isinstance(evidence, dict) or set(evidence) - {'http_headers', 'tls_fingerprint', 'dns_rrset'}:
        raise ValueError('invalid evidence configuration')
    headers = evidence.get('http_headers', [])
    if not isinstance(headers, list) or len(headers) > 12 or any(not isinstance(h, str) or h.lower() not in SAFE_HEADERS for h in headers):
        raise ValueError('evidence.http_headers must contain approved header names')
    for key in ('tls_fingerprint', 'dns_rrset'):
        if key in evidence and not isinstance(evidence[key], bool):
            raise ValueError('evidence.%s must be boolean' % key)
    if 'dns' in cfg and (headers or evidence.get('tls_fingerprint')):
        raise ValueError('HTTP/TLS evidence is not valid for DNS checks')
    if 'url' in cfg and evidence.get('dns_rrset'):
        raise ValueError('DNS evidence is not valid for URL checks')
    if 'url' in cfg and urlsplit(cfg['url']).scheme != 'https' and evidence.get('tls_fingerprint'):
        raise ValueError('TLS evidence requires HTTPS')
    rules = (cfg.get('tests') or {}).get('structured', [])
    if not isinstance(rules, list) or len(rules) > 64:
        raise ValueError('tests.structured must be a list of up to 64 rules')
    ids = set()
    for rule in rules:
        if not isinstance(rule, dict) or set(rule) - {'id', 'type', 'path', 'header', 'expected', 'operator', 'pattern', 'severity'}:
            raise ValueError('invalid structured assertion')
        ident = rule.get('id')
        if not isinstance(ident, str) or not re.fullmatch(r'[A-Za-z0-9_.-]{1,80}', ident) or ident in ids:
            raise ValueError('invalid or duplicate structured assertion ID')
        ids.add(ident)
        if rule.get('type') not in ('status', 'header', 'body_regex', 'json_value'):
            raise ValueError('unsupported structured assertion type')
        if rule.get('operator', 'eq') not in ('eq', 'ne', 'gt', 'ge', 'lt', 'le'):
            raise ValueError('unsupported structured assertion operator')
        if rule.get('type') == 'body_regex':
            pattern = rule.get('pattern')
            if not isinstance(pattern, str) or len(pattern) > 256:
                raise ValueError('invalid regex pattern')
            try:
                re.compile(pattern)
            except re.error as exc:
                raise ValueError('invalid regex syntax') from exc
        if rule.get('type') == 'json_value' and (not isinstance(rule.get('path'), str) or not re.fullmatch(r'[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]+){0,15}', rule['path'])):
            raise ValueError('invalid JSON object path')
        if rule.get('type') == 'header' and (not isinstance(rule.get('header'), str) or not rule['header'] or any(c in rule['header'] for c in '\r\n')):
            raise ValueError('invalid header assertion')
    execution = cfg.get('execution') or {}
    if not isinstance(execution, dict):
        raise ValueError('execution must be a mapping')
    for key in ('retries',):
        if key in execution and (type(execution[key]) is not int or execution[key] < 0):
            raise ValueError('execution.%s must be a non-negative integer' % key)
    return cfg


def explain_config(cfg, path, override=None):
    mode, name, thresholds = monitoring_config(cfg, override)
    lines = ['SERVICE: ' + name, 'Configuration: ' + str(path)]
    if 'dns' in cfg:
        dns = cfg['dns']
        lines.extend(['Protocol: DNS', 'DNS settings: ' + ', '.join(sorted(dns))])
    else:
        parsed = urlsplit(cfg['url'])
        lines.extend(['Target: ' + cfg['url'], 'Protocol: ' + parsed.scheme.upper()])
        if parsed.scheme == 'https':
            lines.append('TLS verification: ' + ('enabled' if (cfg.get('tls') or {}).get('verify', True) else 'disabled'))
        if parsed.scheme in ('http', 'https'):
            lines.append('HTTP method: ' + str((cfg.get('request') or {}).get('method', 'GET')).upper())
            lines.append('Assertions: ' + ', '.join(sorted((cfg.get('tests') or {}).keys())) if cfg.get('tests') else 'Assertions: none configured')
    t = cfg.get('timeouts') or {}
    lines.extend(['Connection timeout: %s seconds' % t.get('connect', 3),
                  'Response timeout: %s seconds' % t.get('response', 10),
                  'Failure severity: ' + str((cfg.get('monitoring') or {}).get('on_failure', 'critical')).upper(),
                  'Output: ' + mode,
                  'Response time thresholds: ' + (str(thresholds) if thresholds else 'none'),
                  'No network requests performed.'])
    return '\n'.join(lines)



VERSION = '1.5.4'



# Strict validation is opt-in to preserve compatibility with existing YAML.
STRICT_KEYS = {
    '': {'type', 'name', 'url', 'dns', 'timeouts', 'monitoring', 'execution', 'request', 'tests', 'tls', 'auth', 'connection', 'proxy', 'metadata', 'evidence'},
    'timeouts': {'connect', 'response', 'total'},
    'metadata': {'owner', 'environment', 'description', 'runbook', 'tags'},
    'execution': {'retries', 'retry_delay', 'success_required', 'backends'},
    'auth': {'type', 'username', 'username_env', 'password', 'password_env', 'token', 'token_env'},
    'connection': {'resolve'},
    'evidence': {'http_headers', 'tls_fingerprint', 'dns_rrset'},
    'request': {'method', 'headers', 'body', 'json', 'follow_redirects', 'user_agent'},
}

def strict_validate(cfg):
    for section, allowed in STRICT_KEYS.items():
        mapping = cfg if not section else cfg.get(section, {}) or {}
        if not isinstance(mapping, dict):
            continue  # normal validator reports the type error
        for key in mapping:
            if key not in allowed:
                suggestion = difflib.get_close_matches(str(key), sorted(allowed), n=1)
                hint = ('; did you mean %s?' % suggestion[0]) if suggestion else ''
                raise ValueError('Unknown configuration key %s%s%s' % (section + '.' if section else '', key, hint))
    auth = cfg.get('auth') or {}
    for key in ('password', 'token'):
        if key in auth:
            raise ValueError('auth.%s contains a literal secret; use auth.%s_env' % (key, key))
    request = cfg.get('request') or {}
    for key, value in (request.get('headers') or {}).items():
        if str(key).lower() in ('authorization', 'proxy-authorization', 'x-api-key', 'x-auth-token'):
            raise ValueError('request.headers.%s may contain a literal secret' % key)

def redaction_values(cfg):
    values = set()
    auth = cfg.get('auth') or {}
    for field in ('password', 'token'):
        value = auth.get(field)
        if isinstance(value, str) and value:
            values.add(value)
        env = auth.get(field + '_env')
        if isinstance(env, str) and os.environ.get(env):
            values.add(os.environ[env])
    for key, value in ((cfg.get('request') or {}).get('headers') or {}).items():
        if str(key).lower() in ('authorization', 'proxy-authorization', 'x-api-key', 'x-auth-token') and isinstance(value, str):
            values.add(value)
    return sorted((v for v in values if v), key=len, reverse=True)

def redact(text, cfg):
    text = str(text)
    for value in redaction_values(cfg):
        text = text.replace(value, '[REDACTED]')
    return text

def self_test():
    checks = [('Python >= 3.9', sys.version_info >= (3, 9)),
              ('PyYAML installed', importlib.util.find_spec('yaml') is not None),
              ('Requests installed', importlib.util.find_spec('requests') is not None),
              ('TLS trust store available', bool(ssl.get_default_verify_paths().cafile and os.path.isfile(ssl.get_default_verify_paths().cafile)) or bool(ssl.get_default_verify_paths().capath and os.path.isdir(ssl.get_default_verify_paths().capath)))]
    for label, good in checks:
        print('%s %s' % ('OK' if good else 'UNKNOWN', label))
    print('RESULT: ' + ('READY' if all(good for _, good in checks) else 'NOT READY'))
    return 0 if all(good for _, good in checks) else 3


def validate_metadata(cfg):
    """Optional descriptive metadata; never used as executable configuration."""
    meta = cfg.get('metadata', {})
    if not isinstance(meta, dict):
        raise ValueError('metadata must be a mapping')
    for key in ('owner', 'environment', 'description', 'runbook'):
        if key in meta and (not isinstance(meta[key], str) or not meta[key].strip() or '\n' in meta[key] or '\r' in meta[key]):
            raise ValueError('metadata.%s must be a non-empty single-line string' % key)
    if 'tags' in meta and (not isinstance(meta['tags'], list) or any(not isinstance(t, str) or not t.strip() or '\n' in t or '\r' in t for t in meta['tags'])):
        raise ValueError('metadata.tags must be a list of non-empty strings')
    return meta


def describe_check(cfg, path):
    meta = validate_metadata(cfg)
    mode, name, _ = monitoring_config(cfg)
    target = cfg.get('url', 'DNS: ' + str((cfg.get('dns') or {}).get('name', '(see dns settings)')))
    protocol = urlsplit(target).scheme.upper() if 'url' in cfg else 'DNS'
    return {'file': str(path), 'name': name, 'protocol': protocol, 'target': target,
            'owner': meta.get('owner', ''), 'environment': meta.get('environment', ''),
            'description': meta.get('description', ''), 'runbook': meta.get('runbook', ''),
            'tags': ','.join(meta.get('tags', [])), 'output': mode}


def write_inventory(rows, fmt):
    columns = ('file', 'name', 'protocol', 'target', 'owner', 'environment', 'description', 'runbook', 'tags')
    if fmt == 'json':
        print(json.dumps(rows, indent=2))
    elif fmt == 'tsv':
        writer = csv.writer(sys.stdout, delimiter='\t', lineterminator='\n')
        writer.writerow(columns)
        for row in rows:
            writer.writerow([row[k] for k in columns])
    else:
        for row in rows:
            print('%s  %s  %s  %s%s' % (row['name'], row['protocol'], row['target'], row['file'],
                                         '  owner=' + row['owner'] if row['owner'] else ''))


def collect_config_paths(args, parser):
    paths = list(args.configs)
    if args.check_dir is not None:
        folder = args.check_dir
        if not folder.is_dir():
            parser.error('--check-dir must point to an existing directory: ' + str(folder))
        paths.extend(sorted(x for x in folder.iterdir() if x.is_file() and x.suffix.lower() in ('.yaml', '.yml')))
    if args.list_checks is not None:
        folder = args.list_checks
        if not folder.is_dir():
            parser.error('--list-checks must point to an existing directory: ' + str(folder))
        paths.extend(sorted(x for x in folder.iterdir() if x.is_file() and x.suffix.lower() in ('.yaml', '.yml')))
    if not paths:
        parser.error('provide YAML files or --check-dir/--list-checks DIRECTORY')
    return list(dict.fromkeys(paths))


# Offline comparison deliberately never prints configuration values for secret-like keys.
def safe_diff(old, new):
    def flatten(obj, prefix=''):
        result = {}
        if isinstance(obj, dict):
            for key, value in obj.items():
                result.update(flatten(value, prefix + '.' + str(key) if prefix else str(key)))
        elif isinstance(obj, list):
            for i, value in enumerate(obj):
                result.update(flatten(value, '%s[%d]' % (prefix, i)))
        else:
            result[prefix] = obj
        return result
    a, b = flatten(old), flatten(new)
    sensitive = re.compile(r'password|secret|token|authorization|api.?key|cookie|credential|private.?key|body|username', re.I)
    lines = []
    for key in sorted(set(a) | set(b)):
        if key in a and key in b and a[key] == b[key]:
            continue
        hide = bool(sensitive.search(key))
        def fmt(value):
            return '[REDACTED]' if hide or (isinstance(value, str) and (value in redaction_values(old) or value in redaction_values(new))) else json.dumps(value, ensure_ascii=False, sort_keys=True)
        if key in a:
            lines.append('- %s: %s' % (key, fmt(a[key])))
        if key in b:
            lines.append('+ %s: %s' % (key, fmt(b[key])))
    return lines


def operational_context(cfg):
    meta = validate_metadata(cfg)
    return {k: meta[k] for k in ('owner', 'environment', 'description', 'runbook', 'tags') if k in meta}


def baseline_snapshot(cfg, result):
    # Stable, deliberately minimal and non-sensitive observations. Never store
    # response bodies, HTTP headers, URLs with credentials, or auth material.
    return {'schema': 2, 'status': result['status'], 'code': result['code'],
            'assertion_ids': sorted(set(x['id'] for x in result.get('assertion_results', []))),
            'evidence': result.get('evidence', {})}


def baseline_operation(path, cfg, mode, baseline_path, save):
    result = make_result(path, cfg, mode)
    result['failures'] = [redact(x, cfg) for x in result['failures']]
    for item in result.get('assertion_results', []):
        item['message'] = redact(item['message'], cfg)
    snapshot = baseline_snapshot(cfg, result)
    if save:
        if result['code'] != 0:
            print('UNKNOWN - cannot save baseline: check did not return OK', file=sys.stderr)
            return 3
        if baseline_path.exists():
            print('UNKNOWN - baseline already exists (remove explicitly to replace)', file=sys.stderr)
            return 3
        fd = os.open(str(baseline_path), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
        with os.fdopen(fd, 'w', encoding='utf-8') as handle:
            json.dump(snapshot, handle, indent=2, sort_keys=True)
            handle.write('\n')
        print('OK - baseline saved to %s' % baseline_path)
        return 0
    try:
        expected = json.loads(baseline_path.read_text(encoding='utf-8'))
        if not isinstance(expected, dict) or set(expected) != set(snapshot) or expected.get('schema') != 2:
            raise ValueError('unsupported baseline schema')
    except (OSError, ValueError, TypeError) as exc:
        print('UNKNOWN - baseline could not be loaded: %s' % type(exc).__name__, file=sys.stderr)
        return 3
    if expected != snapshot:
        print('CRITICAL - baseline changed: %s' % ', '.join(k for k in snapshot if expected[k] != snapshot[k]))
        return 2
    print('OK - baseline unchanged')
    return 0

def doctor():
    """Offline diagnostics; never contacts a monitored endpoint."""
    import shutil
    paths = ssl.get_default_verify_paths()
    checks = [
        ('Python >= 3.9', sys.version_info >= (3, 9)),
        ('PyYAML', importlib.util.find_spec('yaml') is not None),
        ('Requests', importlib.util.find_spec('requests') is not None),
        ('TLS trust store', bool((paths.cafile and os.path.isfile(paths.cafile)) or (paths.capath and os.path.isdir(paths.capath)))),
        ('Temporary directory writable', os.access(__import__('tempfile').gettempdir(), os.W_OK)),
    ]
    details = {'version': VERSION, 'python': platform.python_version(), 'platform': platform.platform(),
               'resolver': '/etc/resolv.conf' if Path('/etc/resolv.conf').is_file() else 'system default',
               'proxy_environment': sorted(k for k in os.environ if k.lower() in ('http_proxy', 'https_proxy', 'no_proxy')),
               'openssl': ssl.OPENSSL_VERSION, 'checks': [{'name': k, 'ok': v} for k,v in checks]}
    print(json.dumps(details, indent=2, sort_keys=True))
    return 0 if all(ok for _,ok in checks) else 3


def lint_config(cfg, path):
    """Static policy hints only. Does not connect to services."""
    findings = []
    def add(level, code, detail):
        findings.append({'file': str(path), 'severity': level, 'code': code, 'message': detail})
    t = cfg.get('timeouts') or {}
    if 'total' not in t:
        add('WARNING', 'TOTAL_TIMEOUT', 'Set timeouts.total to bound check duration')
    if 'url' in cfg and urlsplit(cfg['url']).scheme == 'https':
        if (cfg.get('tls') or {}).get('verify') is False:
            add('WARNING', 'TLS_VERIFY', 'Enable TLS certificate verification')
    meta = cfg.get('metadata') or {}
    if not meta.get('owner'):
        add('INFO', 'OWNER', 'Set metadata.owner for incident ownership')
    if not meta.get('runbook'):
        add('INFO', 'RUNBOOK', 'Set metadata.runbook for troubleshooting')
    return findings


def probe_target(target, output=None):
    """Ad-hoc check using the same execution engine as YAML checks."""
    parsed = urlsplit(target)
    if parsed.scheme not in ('tcp', 'http', 'https') or not parsed.hostname:
        raise ValueError('--probe expects tcp://, http:// or https:// URL with a host')
    cfg = {'name': 'ad-hoc probe', 'url': target, 'timeouts': {'connect': 3, 'response': 10, 'total': 20},
           'monitoring': {'output': output or 'text'}}
    validate_config(cfg, output)
    result = make_result(Path('<ad-hoc>'), cfg, output)
    print(render(result, result['output']))
    return result['code']


def inventory_paths(folder):
    if not folder.is_dir():
        raise ValueError('inventory directory does not exist')
    return sorted(x for x in folder.iterdir() if x.is_file() and x.suffix.lower() in ('.yaml', '.yml'))


def main(argv=None):
    parser = argparse.ArgumentParser(description='ipsonic-probe: YAML-driven DNS/TCP/HTTP(S) validation')
    parser.add_argument('--output', choices=OUTPUTS, help='override monitoring.output for checks')
    parser.add_argument('--format', choices=('text', 'tsv', 'json'), default='text', help='output format for --list-checks and --inventory')
    parser.add_argument('--strict', action='store_true', help='reject unknown keys and literal authentication secrets')
    parser.add_argument('--self-test', action='store_true', help='check local runtime dependencies without network access')
    parser.add_argument('--baseline-save', type=Path, metavar='FILE', help='save successful check status baseline (no sensitive response data)')
    parser.add_argument('--baseline-compare', type=Path, metavar='FILE', help='compare check status to saved baseline')
    parser.add_argument('--doctor', action='store_true', help='offline runtime diagnostics as JSON')
    parser.add_argument('--version', action='store_true', help='show version and Python runtime')
    action = parser.add_mutually_exclusive_group()
    action.add_argument('--probe', metavar='URL', help='run an ad-hoc TCP/HTTP(S) check without YAML')
    action.add_argument('--lint', type=Path, metavar='PATH', help='lint a YAML file or a directory offline')
    action.add_argument('--inventory', type=Path, metavar='DIRECTORY', help='export service inventory from YAML checks offline')
    action.add_argument('--diff', nargs=2, type=Path, metavar=('OLD', 'NEW'), help='compare YAML configurations offline with secret masking')
    action.add_argument('--validate', action='store_true', help='validate YAML without network access')
    action.add_argument('--explain', action='store_true', help='explain a check without network access')
    action.add_argument('--dry-run', action='store_true', help='show intended checks without network access')
    action.add_argument('--list-checks', type=Path, metavar='DIRECTORY', help='list YAML checks without network access')
    parser.add_argument('--check-dir', type=Path, metavar='DIRECTORY', help='execute all YAML checks in directory (non-recursive)')
    parser.add_argument('configs', nargs='*', type=Path, help='YAML configuration files')
    args = parser.parse_args(argv)
    if args.doctor:
        if args.configs or args.check_dir or args.list_checks or args.lint or args.inventory or args.probe:
            parser.error('--doctor does not accept checks or other actions')
        return doctor()
    if args.probe:
        if args.configs or args.check_dir or args.format != 'text' or args.baseline_save or args.baseline_compare:
            parser.error('--probe accepts only a URL and optional --output')
        try:
            return probe_target(args.probe, args.output)
        except (ValueError, OSError, TypeError) as exc:
            print('UNKNOWN - invalid probe: %s' % type(exc).__name__, file=sys.stderr)
            return 3
    if args.lint or args.inventory:
        if args.configs or args.check_dir or args.baseline_save or args.baseline_compare:
            parser.error('--lint/--inventory cannot be combined with YAML arguments or other actions')
        if args.format != 'text' and not args.inventory:
            parser.error('--format requires --inventory or --list-checks')
        target = args.lint or args.inventory
        try:
            paths = inventory_paths(target) if target.is_dir() else [target]
            if args.inventory and not target.is_dir():
                raise ValueError('--inventory requires a directory')
            if not paths:
                raise ValueError('no YAML files found')
            findings, rows, invalid = [], [], False
            for path in paths:
                try:
                    cfg = yaml.safe_load(path.read_text(encoding='utf-8'))
                    validate_config(cfg, args.output)
                    validate_metadata(cfg)
                    if args.strict:
                        strict_validate(cfg)
                    if args.inventory:
                        rows.append(describe_check(cfg, path))
                    else:
                        findings.extend(lint_config(cfg, path))
                except (OSError, ValueError, TypeError, yaml.YAMLError):
                    print('INVALID %s: configuration could not be validated' % path, file=sys.stderr)
                    invalid = True
            if args.inventory:
                write_inventory(rows, args.format)
                return 3 if invalid else 0
            for finding in findings:
                print('{severity} {file} [{code}] {message}'.format(**finding))
            print('LINT: %d warning(s), %d info, %d invalid' % (sum(f['severity']=='WARNING' for f in findings), sum(f['severity']=='INFO' for f in findings), int(invalid)))
            return 3 if invalid else (1 if any(f['severity']=='WARNING' for f in findings) else 0)
        except (OSError, ValueError, TypeError):
            print('UNKNOWN - invalid lint/inventory path', file=sys.stderr)
            return 3
    if args.self_test:
        return self_test()
    if args.version:
        print('ipsonic-probe %s | Python %s | %s' % (VERSION, platform.python_version(), platform.system()))
        return 0
    if args.diff:
        try:
            old, new = (yaml.safe_load(p.read_text(encoding='utf-8')) for p in args.diff)
            validate_config(old)
            validate_config(new)
            changes = safe_diff(old, new)
            print('\n'.join(changes) if changes else 'No configuration changes')
            return 0 if not changes else 1
        except (OSError, ValueError, TypeError, yaml.YAMLError):
            print('UNKNOWN - unable to compare YAML configurations', file=sys.stderr)
            return 3
    if args.baseline_save and args.baseline_compare:
        parser.error('choose either --baseline-save or --baseline-compare')
    if (args.baseline_save or args.baseline_compare) and (args.validate or args.explain or args.dry_run or args.list_checks or args.check_dir):
        parser.error('baseline requires one YAML file and no other action')
    if args.baseline_save or args.baseline_compare:
        if len(args.configs) != 1:
            parser.error('baseline requires exactly one YAML configuration')
        try:
            cfg = yaml.safe_load(args.configs[0].read_text(encoding='utf-8'))
            validate_config(cfg, args.output)
            validate_metadata(cfg)
            if args.strict:
                strict_validate(cfg)
            return baseline_operation(args.configs[0], cfg, args.output, args.baseline_save or args.baseline_compare, bool(args.baseline_save))
        except (OSError, ValueError, TypeError, yaml.YAMLError):
            print('UNKNOWN - invalid baseline configuration', file=sys.stderr)
            return 3
    if args.format != 'text' and args.list_checks is None:
        parser.error('--format is only supported with --list-checks')
    if args.check_dir and (args.validate or args.explain or args.dry_run or args.list_checks):
        parser.error('--check-dir cannot be combined with offline actions')
    paths = collect_config_paths(args, parser)
    results, inventory = [], []
    for path in paths:
        cfg = None
        try:
            cfg = yaml.safe_load(path.read_text(encoding='utf-8'))
            validate_config(cfg, args.output)
            validate_metadata(cfg)
            if args.strict:
                strict_validate(cfg)
            if args.validate:
                print('VALID ' + str(path))
                continue
            if args.explain:
                print(explain_config(cfg, path, args.output))
                meta = validate_metadata(cfg)
                for key in ('owner', 'environment', 'description', 'runbook', 'tags'):
                    if key in meta:
                        print('Metadata %s: %s' % (key, ', '.join(meta[key]) if key == 'tags' else meta[key]))
                continue
            if args.dry_run or args.list_checks is not None:
                row = describe_check(cfg, path)
                if args.dry_run:
                    print('DRY RUN %s | %s | %s | %s | no network requests performed' % (row['file'], row['protocol'], row['target'], row['name']))
                else:
                    inventory.append(row)
                continue
            result = make_result(path, cfg, args.output)
            result['failures'] = [redact(x, cfg) for x in result['failures']]
            for item in result.get('assertion_results', []):
                item['message'] = redact(item['message'], cfg)
            result['service_name'] = redact(result['service_name'], cfg)
            result['metadata'] = operational_context(cfg)
            result['evidence'] = {k: ({h: redact(v, cfg) for h, v in val.items()} if isinstance(val, dict) else val) for k, val in result.get('evidence', {}).items()}
        except (OSError, ValueError, TypeError, KeyError, yaml.YAMLError) as exc:
            if args.validate or args.explain or args.dry_run or args.list_checks is not None:
                print('INVALID %s: %s: %s' % (path, type(exc).__name__, redact(exc, cfg) if isinstance(cfg, dict) else '[configuration error]'), file=sys.stderr)
                results.append({'code': 3})
                continue
            mode = args.output or 'text'
            result = {'file': str(path), 'service_name': path.stem, 'output': mode,
                      'status': 'UNKNOWN', 'code': 3, 'elapsed_seconds': 0.0,
                      'failures': ['%s: %s' % (type(exc).__name__, redact(exc, cfg) if isinstance(cfg, dict) else '[configuration error]')], 'thresholds': {}}
        results.append(result)
        print(render(result, result['output']))
    if args.list_checks is not None:
        write_inventory(inventory, args.format)
    return max((r['code'] for r in results), default=0)


if __name__ == '__main__':
    sys.exit(main())
