test_tls_kontrol.py
import http.server
import json
from pathlib import Path
import ssl
import subprocess
import sys
import tempfile
import threading
import unittest
class Readiness(http.server.BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200 if self.path == '/healthz/readiness' else 502)
self.send_header('Content-Length', '0')
self.end_headers()
def log_message(self, *_):
pass
class FixtureServer(http.server.ThreadingHTTPServer):
def handle_error(self, request, client_address):
if not isinstance(sys.exception(), ConnectionResetError):
super().handle_error(request, client_address)
class TLSTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
tmp = tempfile.TemporaryDirectory()
cls.addClassCleanup(tmp.cleanup)
cls.cert = Path(tmp.name) / 'local.pem'
key = Path(tmp.name) / 'local.key'
subprocess.run(['openssl', 'req', '-x509', '-newkey', 'rsa:2048', '-nodes', '-days', '1',
'-subj', '/CN=localhost',
'-addext', 'subjectAltName=DNS:localhost,DNS:n8n.example.net',
'-keyout', str(key), '-out', str(cls.cert)], check=True, capture_output=True)
cls.sni = []
server = FixtureServer(('127.0.0.1', 0), Readiness)
cls.addClassCleanup(server.server_close)
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain(cls.cert, key)
context.sni_callback = lambda _sock, name, _context: cls.sni.append(name)
server.socket = context.wrap_socket(server.socket, server_side=True)
cls.port = server.server_port
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
cls.addClassCleanup(thread.join, 5)
cls.addClassCleanup(server.shutdown)
def run_cli(self, host='n8n.example.net', *, pin=True, trust=True, extra=()):
args = [sys.executable, str(Path(__file__).with_name('tls_kontrol.py')), host,
'--port', str(self.port)]
if pin:
args += ['--ip', '127.0.0.1']
if trust:
args += ['--ca-file', str(self.cert)]
out = subprocess.run(args + list(extra), capture_output=True, text=True, timeout=10)
return out.returncode, json.loads(out.stdout) if out.stdout else out.stderr
def test_fixed_ip_preserves_sni_and_hostname(self):
code, report = self.run_cli()
self.assertEqual(code, 0, report)
self.assertEqual(self.sni[-1], 'n8n.example.net')
self.assertEqual((report['yol'], report['ip'], report['http']), ('sabit-ip', '127.0.0.1', 200))
def test_system_resolver(self):
code, report = self.run_cli('localhost', pin=False)
self.assertEqual(code, 0, report)
self.assertEqual(report['yol'], 'sistem-dns')
def test_wrong_expected_ip(self):
code, report = self.run_cli(extra=('--beklenen-ip', '127.0.0.2'))
self.assertEqual(code, 1, report)
self.assertFalse(report['beklenen_ip_eslesti'])
def test_https_502_is_not_a_tls_failure(self):
code, report = self.run_cli(extra=('--path', '/backend-hatasi'))
self.assertEqual(code, 1, report)
self.assertEqual((report['tls'], report['http']), ('doğrulandı', 502))
def test_wrong_certificate_name(self):
code, report = self.run_cli('yanlis.example.net')
self.assertEqual(code, 2, report)
self.assertEqual((report['curl_kodu'], report['http']), (60, None))
def test_untrusted_certificate(self):
code, report = self.run_cli(trust=False)
self.assertEqual(code, 2, report)
self.assertEqual(report['tls'], 'sertifika hatası')
def test_invalid_host_never_probed(self):
code, report = self.run_cli('n8n.example.net/yonlendir')
self.assertEqual(code, 2, report)
self.assertIn('Örnek uygulama adı', report)
def test_openssl_strict_verification(self):
command = ['openssl', 's_client', '-connect', f'127.0.0.1:{self.port}',
'-servername', 'n8n.example.net', '-verify_return_error', '-brief',
'-CAfile', str(self.cert), '-verify_hostname']
ok = subprocess.run(command + ['n8n.example.net'], input='', capture_output=True, text=True, timeout=10)
wrong = subprocess.run(command + ['yanlis.example.net'], input='', capture_output=True, text=True, timeout=10)
self.assertEqual(ok.returncode, 0, ok.stderr)
self.assertIn('Verification: OK', ok.stderr)
self.assertNotEqual(wrong.returncode, 0)
self.assertIn('hostname mismatch', wrong.stderr)
if __name__ == '__main__':
unittest.main()
tls_kontrol.py
#!/usr/bin/env python3
"""Tek bir n8n HTTPS ucunda DNS yolu, TLS ve HTTP sonucunu ayır."""
import argparse
import ipaddress
import json
import re
import subprocess
import sys
DNS_ADI = re.compile(r'(?=.{1,253}$)(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)*[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?')
def denetle(a):
url = f'https://{a.host}:{a.port}{a.path}'
command = [
'curl', '--disable', '--silent', '--show-error', '--noproxy', '*',
'--proto', '=https', '--globoff', '--max-time', str(a.timeout),
'--output', '/dev/null', '--write-out', '%{remote_ip}\n%{http_code}\n',
]
if a.ca_file:
command.extend(['--cacert', a.ca_file])
if a.ip:
address = f'[{a.ip}]' if a.ip.version == 6 else str(a.ip)
command.extend(['--resolve', f'{a.host}:{a.port}:{address}'])
result = subprocess.run(command + ['--url', url], capture_output=True, text=True)
remote, status, *_ = (result.stdout.splitlines() + ['', ''])
code = int(status) if re.fullmatch(r'[1-5][0-9]{2}', status) else None
# Bir HTTP yanıtı ancak HTTPS el sıkışması ve doğrulaması tamamlanınca gelir.
report = {'yol': 'sabit-ip' if a.ip else 'sistem-dns', 'ip': remote or None,
'http': code, 'curl_kodu': result.returncode,
'tls': 'doğrulandı' if code else
'sertifika hatası' if result.returncode == 60 else 'başarı doğrulanamadı'}
if result.returncode or code is None:
return report, 2
expected = a.beklenen_ip or a.ip
ip_ok = not expected or (bool(remote) and ipaddress.ip_address(remote) == expected)
report['beklenen_ip_eslesti'] = ip_ok if expected else None
return report, 0 if code == a.status and ip_ok else 1
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument('host', help='Sertifikada yer alan uygulama adı (ASCII/Punycode)')
p.add_argument('--ip', type=ipaddress.ip_address, help='Yalnızca bu istekte DNS yerine kullanılacak IP')
p.add_argument('--beklenen-ip', type=ipaddress.ip_address, help='Bağlanılan IP bu değer olmalı')
p.add_argument('--port', type=int, default=443)
p.add_argument('--path', default='/healthz/readiness')
p.add_argument('--status', type=int, default=200)
p.add_argument('--timeout', type=int, default=6)
p.add_argument('--ca-file', help='Güvenilir CA dosyası (PEM); curl sistem ayarı varsayılandır')
a = p.parse_args()
if not DNS_ADI.fullmatch(a.host):
p.error('Örnek uygulama adı: n8n.example.net')
if (not a.path.startswith('/') or any(char in '?#' or not 33 <= ord(char) <= 126 for char in a.path)):
p.error('Yol / ile başlamalı; boşluk, sorgu ve fragment içermemeli.')
if not (1 <= a.port <= 65535 and 1 <= a.timeout <= 60 and 200 <= a.status <= 599):
p.error('Port, süre veya HTTP durumu aralık dışında.')
try:
report, code = denetle(a)
except (OSError, ValueError) as exc:
print(f'Kontrol çalıştırılamadı: {exc}', file=sys.stderr)
return 2
print(json.dumps(report, ensure_ascii=False))
return code
if __name__ == '__main__':
sys.exit(main())