"""Bounded read-only Gitea diagnostics; credentials remain in Git's configured helper.""" import datetime import json import os from pathlib import Path import socket import ssl import subprocess import urllib.error import urllib.request def main(): import argparse parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--output', required=True, type=Path) args = parser.parse_args() assert not args.output.exists(), 'Preserve earlier observations' def git(*command): result = subprocess.run(['rtk', 'proxy', 'git', *command], text=True, capture_output=True, timeout=45) return result url = git('remote', 'get-url', 'origin').stdout.strip() assert url == 'https://git.cesnimda.uk/cesnimda/jobtrackingapp.git' assert os.getenv('GIT_SSL_NO_VERIFY', '').lower() not in ('1', 'true', 'yes'), 'Git TLS verification is disabled in the environment' assert git('config', '--get-urlmatch', 'http.sslVerify', url).stdout.strip().lower() not in ('false', '0', 'no'), 'Git TLS verification is disabled for this remote' record = dict(observedUtc=datetime.datetime.now(datetime.timezone.utc).isoformat(), remote=url, localCommit=git('rev-parse', 'HEAD').stdout.strip(), tlsVerificationDisabled=False) try: addresses = sorted({item[4][0] for item in socket.getaddrinfo('git.cesnimda.uk', 443, type=socket.SOCK_STREAM)}) record['dns'] = dict(status='PASS', addresses=addresses) except OSError as error: record['dns'] = dict(status='BLOCKED', errorType=type(error).__name__) try: with socket.create_connection(('git.cesnimda.uk', 443), timeout=5): record['tcp443'] = dict(status='PASS') except OSError as error: record['tcp443'] = dict(status='BLOCKED', errorType=type(error).__name__) try: with socket.create_connection(('git.cesnimda.uk', 443), timeout=5) as connection: with ssl.create_default_context().wrap_socket(connection, server_hostname='git.cesnimda.uk') as secured: record['tls'] = dict(status='PASS', protocol=secured.version(), certificateVerified=True) except OSError as error: record['tls'] = dict(status='BLOCKED', errorType=type(error).__name__, certificateVerified=False) class NoRedirect(urllib.request.HTTPRedirectHandler): def redirect_request(self, *unused): return None try: with urllib.request.build_opener(NoRedirect()).open('https://git.cesnimda.uk/api/v1/version', timeout=6) as response: record['https'] = dict(status='PASS', httpStatus=response.status) except (OSError, urllib.error.URLError) as error: record['https'] = dict(status='BLOCKED', errorType=type(error).__name__, httpStatus=getattr(error, 'code', None)) command = ['ls-remote', '--exit-code', 'origin', 'refs/heads/test/pre-phase10-ux-acceptance', 'refs/heads/planning/int-global-jobs-00'] try: result = git(*command) refs = dict(reversed(line.split()) for line in result.stdout.splitlines() if len(line.split()) == 2) record['git'] = dict(argv=['git', *command], exitCode=result.returncode, refs=refs, authentication='REACHED' if result.returncode == 0 else 'NOT_ESTABLISHED') except subprocess.TimeoutExpired: record['git'] = dict(argv=['git', *command], exitCode=None, refs={}, authentication='NOT_ESTABLISHED', timeoutSeconds=45) record['publication'] = 'VERIFIED' if record['git']['refs'].get('refs/heads/test/pre-phase10-ux-acceptance') == record['localCommit'] else 'BLOCKED' args.output.parent.mkdir(parents=True, exist_ok=True) args.output.write_text(json.dumps(record, indent=2) + '\n', encoding='utf-8') print(json.dumps(record)) return 0 if __name__ == '__main__': raise SystemExit(main())