netk-cli 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
netk/__init__.py ADDED
@@ -0,0 +1,70 @@
1
+ """netk — zero-dependency network diagnostics with a machine-readable contract.
2
+
3
+ Library use::
4
+
5
+ from netk import dns_query, probe_tls, probe_http
6
+ from netk.dns.codec import Q_TYPES
7
+
8
+ CLI use: ``netk <command> ...`` (or ``python -m netk``).
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from .cli import main
14
+ from .commands.http import probe_http
15
+ from .commands.ping import icmp_ping, summarize, tcp_ping
16
+ from .commands.tls import probe_tls
17
+ from .contract import (
18
+ RC_BUDGET,
19
+ RC_INTERNAL,
20
+ RC_INTERRUPT,
21
+ RC_NEGATIVE,
22
+ RC_OK,
23
+ RC_TIMEOUT,
24
+ RC_USAGE,
25
+ VERSION,
26
+ Console,
27
+ NetkError,
28
+ emit,
29
+ envelope,
30
+ )
31
+ from .dns.client import dns_query
32
+ from .dns.codec import Q_TYPES, build_query, decode_rdata, encode_qname, parse_response, read_name
33
+ from .dns.resolver import resolver_config, system_resolvers
34
+ from .targets import parse_host_port, resolve, tcp_connect
35
+
36
+ __version__ = VERSION
37
+
38
+ __all__ = [
39
+ "VERSION",
40
+ "__version__",
41
+ "Console",
42
+ "NetkError",
43
+ "RC_OK",
44
+ "RC_NEGATIVE",
45
+ "RC_USAGE",
46
+ "RC_BUDGET",
47
+ "RC_TIMEOUT",
48
+ "RC_INTERNAL",
49
+ "RC_INTERRUPT",
50
+ "emit",
51
+ "envelope",
52
+ "build_query",
53
+ "parse_response",
54
+ "encode_qname",
55
+ "decode_rdata",
56
+ "read_name",
57
+ "Q_TYPES",
58
+ "dns_query",
59
+ "system_resolvers",
60
+ "resolver_config",
61
+ "parse_host_port",
62
+ "resolve",
63
+ "tcp_connect",
64
+ "probe_http",
65
+ "probe_tls",
66
+ "icmp_ping",
67
+ "tcp_ping",
68
+ "summarize",
69
+ "main",
70
+ ]
netk/__main__.py ADDED
@@ -0,0 +1,10 @@
1
+ """``python -m netk`` entry point."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+
7
+ from .cli import main
8
+
9
+ if __name__ == "__main__":
10
+ sys.exit(main())
netk/cli.py ADDED
@@ -0,0 +1,229 @@
1
+ """Command line surface: one parser, one dispatch table, one place that writes stdout.
2
+
3
+ Global flags work on either side of the subcommand (``netk --json ping`` and
4
+ ``netk ping --json`` are the same), which is why they are defined on a shared
5
+ parent parser with ``SUPPRESS`` defaults.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import json
12
+ import os
13
+ import sys
14
+ import traceback
15
+
16
+ from . import render
17
+ from .commands import dns, doctor, http, ping, schema, tcp, tls
18
+ from .contract import (
19
+ RC_INTERNAL,
20
+ RC_INTERRUPT,
21
+ RC_USAGE,
22
+ VERSION,
23
+ Console,
24
+ NetkError,
25
+ emit,
26
+ error_payload,
27
+ )
28
+ from .slo import apply as apply_slo
29
+
30
+ EXAMPLES = """examples:
31
+ netk ping 1.1.1.1 latency + loss, ICMP first, TCP fallback
32
+ netk dns github.com A AAAA MX typed records, no dig required
33
+ netk dns github.com --dot DNS over TLS
34
+ netk tcp github.com 22 443 reachability + connect time
35
+ netk tls github.com:443 --days 30 certificate chain, expiry, ALPN
36
+ netk http https://github.com -L per-phase waterfall like httpstat
37
+ netk doctor resolver, egress IP, proxy, local families
38
+ netk schema --json the contract as JSON Schema
39
+ netk ping 1.1.1.1 --slo "stats.avg_ms<50" CI gate, exit 4 on violation
40
+ """
41
+
42
+ COMMANDS = {
43
+ "ping": ping.run,
44
+ "dns": dns.run,
45
+ "tcp": tcp.run,
46
+ "tls": tls.run,
47
+ "http": http.run,
48
+ "doctor": doctor.run,
49
+ }
50
+
51
+
52
+ class _Parser(argparse.ArgumentParser):
53
+ """Turn argparse's exit(2) into the same JSON usage error as everything else."""
54
+
55
+ def error(self, message: str) -> None: # noqa: D401 - argparse hook
56
+ self.print_usage(sys.stderr)
57
+ raise NetkError("usage", message, RC_USAGE)
58
+
59
+
60
+ def _common() -> argparse.ArgumentParser:
61
+ common = argparse.ArgumentParser(add_help=False)
62
+ common.add_argument(
63
+ "--json",
64
+ action="store_true",
65
+ default=argparse.SUPPRESS,
66
+ help="emit one JSON object; the exit code is the verdict",
67
+ )
68
+ common.add_argument(
69
+ "--no-color", action="store_true", default=argparse.SUPPRESS, help="disable ANSI colors"
70
+ )
71
+ common.add_argument(
72
+ "--slo",
73
+ metavar="EXPR",
74
+ default=argparse.SUPPRESS,
75
+ help='budget check, e.g. "stats.avg_ms<50"; exit 4 on violation',
76
+ )
77
+ return common
78
+
79
+
80
+ def _timed(parser: argparse.ArgumentParser) -> None:
81
+ parser.add_argument(
82
+ "--timeout", type=float, default=5.0, help="per-step timeout in seconds (default 5)"
83
+ )
84
+
85
+
86
+ def build_parser() -> argparse.ArgumentParser:
87
+ common = _common()
88
+ parser = _Parser(
89
+ prog="netk",
90
+ description="Single-file network diagnostics for humans and agents.",
91
+ epilog=EXAMPLES,
92
+ formatter_class=argparse.RawDescriptionHelpFormatter,
93
+ parents=[common],
94
+ )
95
+ parser.add_argument("--version", action="version", version=f"netk {VERSION}")
96
+ sub = parser.add_subparsers(dest="command", required=True, parser_class=_Parser)
97
+
98
+ p_ping = sub.add_parser("ping", help="latency and loss (ICMP, TCP fallback)", parents=[common])
99
+ p_ping.add_argument("host")
100
+ p_ping.add_argument("-c", "--count", type=int, default=4)
101
+ p_ping.add_argument("-i", "--interval", type=float, default=0.5)
102
+ p_ping.add_argument("-s", "--size", type=int, default=56, help="payload bytes")
103
+ p_ping.add_argument("-p", "--port", type=int, default=443, help="TCP fallback port")
104
+ p_ping.add_argument("--method", choices=["auto", "icmp", "tcp"], default="auto")
105
+ p_ping.add_argument("--ip", choices=["ipv4", "ipv6"], help="force an address family")
106
+ _timed(p_ping)
107
+
108
+ p_dns = sub.add_parser("dns", help="typed DNS queries over UDP/TCP/DoT/DoH", parents=[common])
109
+ p_dns.add_argument("name")
110
+ p_dns.add_argument(
111
+ "types", nargs="*", help="A AAAA CNAME MX TXT NS SOA SRV NAPTR CAA PTR HTTPS DS TLSA"
112
+ )
113
+ p_dns.add_argument("--server", help="resolver IP[:port]; default: OS resolver")
114
+ p_dns.add_argument("--tcp", action="store_true", help="force TCP transport")
115
+ p_dns.add_argument("--dot", action="store_true", help="DNS over TLS (port 853)")
116
+ p_dns.add_argument("--doh", help="DoH endpoint, e.g. https://dns.google/dns-query")
117
+ p_dns.add_argument("--doh-get", action="store_true", help="use RFC 8484 GET instead of POST")
118
+ p_dns.add_argument("--retries", type=int, default=1, help="attempts on timeout (default 1)")
119
+ _timed(p_dns)
120
+
121
+ p_tcp = sub.add_parser("tcp", help="port reachability with connect timing", parents=[common])
122
+ p_tcp.add_argument("host")
123
+ p_tcp.add_argument("ports", nargs="*", type=int)
124
+ p_tcp.add_argument("--banner", action="store_true", help="try to read a service banner")
125
+ p_tcp.add_argument("--banner-bytes", type=int, default=256)
126
+ _timed(p_tcp)
127
+
128
+ p_tls = sub.add_parser("tls", help="handshake, certificate and expiry", parents=[common])
129
+ p_tls.add_argument("target", help="host, host:port or URL")
130
+ p_tls.add_argument("--port", type=int, default=443)
131
+ p_tls.add_argument("--servername", help="SNI override")
132
+ p_tls.add_argument("--days", type=int, help="fail when fewer days remain than this")
133
+ p_tls.add_argument("-k", "--insecure", action="store_true", help="skip verification")
134
+ _timed(p_tls)
135
+
136
+ p_http = sub.add_parser("http", help="request with phase waterfall", parents=[common])
137
+ p_http.add_argument("url")
138
+ p_http.add_argument("-X", "--method", default="GET")
139
+ p_http.add_argument("-H", "--header", action="append", help="repeatable")
140
+ p_http.add_argument("-d", "--data")
141
+ p_http.add_argument("-L", "--follow", type=int, default=0, help="follow N redirects")
142
+ p_http.add_argument("--max-body", type=int, default=65536)
143
+ p_http.add_argument("-k", "--insecure", action="store_true")
144
+ p_http.add_argument("--headers", action="store_true", help="include response headers")
145
+ p_http.add_argument("--body", action="store_true", help="include a body preview")
146
+ p_http.add_argument(
147
+ "--no-decode", action="store_true", help="do not decompress gzip/deflate bodies"
148
+ )
149
+ _timed(p_http)
150
+
151
+ sub.add_parser(
152
+ "doctor", help="local resolver, egress IP, proxy and address facts", parents=[common]
153
+ )
154
+ sub.add_parser("schema", help="print the JSON Schema of the contract", parents=[common])
155
+ return parser
156
+
157
+
158
+ def main(argv: list[str] | None = None) -> int:
159
+ argv = list(sys.argv[1:] if argv is None else argv)
160
+ json_requested = "--json" in argv
161
+ parser = build_parser()
162
+
163
+ try:
164
+ args = parser.parse_args(argv)
165
+ except NetkError as exc:
166
+ return _report(exc, None, json_requested)
167
+ except SystemExit as exc: # --help / --version
168
+ return int(exc.code or 0)
169
+
170
+ as_json = bool(getattr(args, "json", json_requested))
171
+ no_color = bool(getattr(args, "no_color", False))
172
+ console = Console(use_color=False if no_color else None)
173
+ command = args.command
174
+
175
+ if command == "schema":
176
+ document = schema.build_schema()
177
+ json.dump(
178
+ document,
179
+ sys.stdout,
180
+ indent=None if as_json else 2,
181
+ ensure_ascii=False,
182
+ separators=(",", ":") if as_json else None,
183
+ )
184
+ sys.stdout.write("\n")
185
+ return 0
186
+
187
+ try:
188
+ payload = COMMANDS[command](args)
189
+ slo = getattr(args, "slo", None)
190
+ if slo:
191
+ payload = apply_slo(payload, slo)
192
+ if as_json:
193
+ return emit(payload, True)
194
+ if payload.get("ok"):
195
+ render.RENDERERS.get(command, lambda *_: None)(payload, console)
196
+ render.render_slo(payload, console)
197
+ else:
198
+ console.line(console.paint(f"netk: {payload['error_type']}: {payload['error']}", "31"))
199
+ return int(payload.get("rc", 0))
200
+ except NetkError as exc:
201
+ return _report(exc, command, as_json, console)
202
+ except KeyboardInterrupt:
203
+ return RC_INTERRUPT
204
+ except BrokenPipeError:
205
+ return 141
206
+ except Exception as exc: # keep the contract even for bugs
207
+ if os.environ.get("NETK_DEBUG"):
208
+ traceback.print_exc()
209
+ return _report(
210
+ NetkError("internal", f"{type(exc).__name__}: {exc}", RC_INTERNAL),
211
+ command,
212
+ as_json,
213
+ console,
214
+ )
215
+
216
+
217
+ def _report(
218
+ error: NetkError, command: str | None, as_json: bool, console: Console | None = None
219
+ ) -> int:
220
+ """Emit one failure payload and mirror it on the human path."""
221
+ payload = error_payload(command, error.error_type, error.message, error.rc)
222
+ emit(payload, as_json)
223
+ if not as_json:
224
+ console = console if console is not None else Console()
225
+ console.line(console.paint(f"netk: {error.error_type}: {error.message}", "31"))
226
+ return error.rc
227
+
228
+
229
+ __all__ = ["main", "build_parser", "COMMANDS"]
@@ -0,0 +1 @@
1
+ """Subcommand implementations. Each exposes ``run(args) -> payload dict``."""
netk/commands/dns.py ADDED
@@ -0,0 +1,121 @@
1
+ """``netk dns``: one or more typed questions, merged into one payload.
2
+
3
+ A multi-type query is N questions but one answer object. Record sections are
4
+ deduped (A + AAAA often repeat CNAMEs), while ``queries`` keeps the per-type rcode
5
+ so an agent can see which question failed without parsing error prose.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from ..contract import RC_NEGATIVE, RC_OK, NetkError, envelope
11
+ from ..dns.client import dns_query
12
+ from ..dns.codec import Q_TYPES, dedupe
13
+ from ..dns.resolver import resolver_config, split_endpoint
14
+
15
+
16
+ def run(args) -> dict:
17
+ name = args.name
18
+ types = [item.upper() for item in (args.types or ["A"])]
19
+ for qtype in types:
20
+ if qtype not in Q_TYPES:
21
+ raise NetkError(
22
+ "usage",
23
+ f"unsupported type {qtype}; try {', '.join(sorted(Q_TYPES))}",
24
+ 2,
25
+ )
26
+
27
+ config = resolver_config()
28
+ if args.server:
29
+ servers, source = [args.server], "cli"
30
+ else:
31
+ servers, source = config["servers"], config["source"]
32
+
33
+ default_port = 853 if args.dot else 53
34
+ payload = envelope("dns", name=name, types=types, resolver_source=source)
35
+ merged: dict[str, list[dict]] = {"answer": [], "authority": [], "additional": []}
36
+ queries: list[dict] = []
37
+ timings: list[float] = []
38
+ codes: list[str] = []
39
+ errors: list[dict] = []
40
+ failed_types = 0
41
+ served_by: str | None = None
42
+
43
+ for qtype in types:
44
+ last: NetkError | None = None
45
+ for server in servers:
46
+ host, port = split_endpoint(server, default_port)
47
+ try:
48
+ response = dns_query(
49
+ name,
50
+ Q_TYPES[qtype],
51
+ host,
52
+ port,
53
+ args.tcp,
54
+ args.timeout,
55
+ args.doh,
56
+ dot=args.dot,
57
+ doh_get=args.doh_get,
58
+ retries=args.retries,
59
+ )
60
+ except NetkError as exc:
61
+ last = exc
62
+ errors.append(
63
+ {
64
+ "type": qtype,
65
+ "server": server,
66
+ "error_type": exc.error_type,
67
+ "error": exc.message,
68
+ "rc": exc.rc,
69
+ }
70
+ )
71
+ continue
72
+
73
+ for section in merged:
74
+ merged[section].extend(response[section])
75
+ timings.append(response["query_time_ms"])
76
+ codes.append(response["rcode"])
77
+ served_by = response["server"]
78
+ payload.update(
79
+ {
80
+ "port": response["port"],
81
+ "transport": response["transport"],
82
+ "flags": response["flags"],
83
+ }
84
+ )
85
+ if response.get("truncated_retry_error"):
86
+ payload["truncated"] = True
87
+ payload["note"] = "UDP answer was truncated and the TCP retry failed"
88
+ queries.append(
89
+ {
90
+ "type": qtype,
91
+ "server": response["server"],
92
+ "rcode": response["rcode"],
93
+ "answer_count": len(response["answer"]),
94
+ "query_time_ms": response["query_time_ms"],
95
+ }
96
+ )
97
+ last = None
98
+ break
99
+ if last is not None:
100
+ failed_types += 1
101
+
102
+ if errors and not timings:
103
+ raise NetkError(errors[0]["error_type"], errors[0]["error"], errors[0]["rc"])
104
+
105
+ for section, records in merged.items():
106
+ merged[section] = dedupe(records)
107
+ payload.update(merged)
108
+ payload["queries"] = queries
109
+ payload["answer_count"] = len(merged["answer"])
110
+ payload["server"] = served_by
111
+ payload["query_time_ms"] = round(sum(timings) / len(timings), 3) if timings else None
112
+ bad = [code for code in codes if code != "NOERROR"]
113
+ payload["rcode"] = bad[0] if bad else (codes[0] if codes else None)
114
+ if errors:
115
+ payload["errors"] = errors
116
+ if bad or failed_types:
117
+ payload["rc"] = RC_NEGATIVE
118
+ elif not merged["answer"]:
119
+ payload["note"] = "NOERROR with an empty answer — the record may not exist for this type"
120
+ payload["rc"] = payload.get("rc", RC_OK)
121
+ return payload
@@ -0,0 +1,96 @@
1
+ """``netk doctor``: the local facts that make a probe result reproducible.
2
+
3
+ An answer like "DNS took 300 ms" is only actionable once you know which resolver
4
+ answered and whether a proxy was supposed to be in the path. This command collects
5
+ resolver config, egress address, local families and proxy variables -- passively,
6
+ without sending probe traffic -- plus a short list of warnings.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ import platform
13
+ import socket
14
+ import sys
15
+
16
+ from ..contract import NetkError, envelope
17
+ from ..dns.resolver import resolver_config
18
+ from ..targets import egress_ip, local_addresses
19
+
20
+ PROXY_VARS = (
21
+ "http_proxy",
22
+ "https_proxy",
23
+ "all_proxy",
24
+ "no_proxy",
25
+ "HTTP_PROXY",
26
+ "HTTPS_PROXY",
27
+ "ALL_PROXY",
28
+ "NO_PROXY",
29
+ )
30
+
31
+
32
+ def run(args) -> dict:
33
+ config = resolver_config()
34
+ proxies = {name: os.environ[name] for name in PROXY_VARS if os.environ.get(name)}
35
+ warnings: list[str] = []
36
+ checks: list[dict] = []
37
+
38
+ if config["source"] == "fallback":
39
+ warnings.append("no OS resolver found; DNS falls back to 1.1.1.1 / 8.8.8.8")
40
+ checks.append(
41
+ {
42
+ "check": "resolver_detected",
43
+ "ok": config["source"] != "fallback",
44
+ "detail": f"{config['source']}: {', '.join(config['servers'])}",
45
+ }
46
+ )
47
+
48
+ if config.get("stub"):
49
+ warnings.append(
50
+ "resolver is the systemd-resolved stub; per-link answers may differ from "
51
+ "a direct query — compare with --server"
52
+ )
53
+
54
+ if proxies:
55
+ warnings.append(
56
+ "proxy variables are set, but netk always connects directly: diagnostics "
57
+ "describe the real path, not the proxied one"
58
+ )
59
+ checks.append(
60
+ {
61
+ "check": "proxy_bypassed",
62
+ "ok": True,
63
+ "detail": "netk never honours http_proxy; probe results are direct",
64
+ }
65
+ )
66
+
67
+ egress = egress_ip()
68
+ if egress is None:
69
+ warnings.append("no IPv4 egress address could be determined")
70
+ checks.append({"check": "egress_ipv4", "ok": egress is not None, "detail": egress or "-"})
71
+
72
+ addresses = local_addresses()
73
+ checks.append(
74
+ {
75
+ "check": "local_ipv6",
76
+ "ok": bool(addresses["ipv6"]),
77
+ "detail": ", ".join(addresses["ipv6"]) or "none (IPv6 may still work off-link)",
78
+ }
79
+ )
80
+
81
+ payload = envelope(
82
+ "doctor",
83
+ hostname=socket.gethostname(),
84
+ platform=platform.platform(),
85
+ python=sys.version.split()[0],
86
+ resolvers=config,
87
+ resolver_count=len(config["servers"]),
88
+ proxy=proxies,
89
+ egress_ip=egress,
90
+ addresses=addresses,
91
+ checks=checks,
92
+ warnings=warnings,
93
+ )
94
+ if config["source"] == "fallback" and not config["servers"]:
95
+ raise NetkError("dns", "no resolver configured at all")
96
+ return payload