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/render.py ADDED
@@ -0,0 +1,221 @@
1
+ """Human renderers. One function per command, all taking the same payload as ``--json``.
2
+
3
+ Nothing here computes: if a number is missing from the payload the human view shows
4
+ "-". That rule is what keeps the two output modes from disagreeing.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Callable
10
+
11
+ from .contract import Console
12
+
13
+ BAR_WIDTH = 28
14
+
15
+
16
+ def fmt_ms(value: float | None) -> str:
17
+ if value is None:
18
+ return "-"
19
+ if value >= 1000:
20
+ return f"{value / 1000:.2f} s"
21
+ return f"{value:.1f} ms"
22
+
23
+
24
+ def bar(share: float, width: int = BAR_WIDTH) -> str:
25
+ filled = max(0, min(width, int(round(share * width))))
26
+ return "█" * filled + "·" * (width - filled)
27
+
28
+
29
+ def render_ping(payload: dict, console: Console) -> None:
30
+ target = payload["target"]
31
+ suffix = f" port {payload['port']}" if payload.get("method") == "tcp" else ""
32
+ console.line(
33
+ console.paint(f"PING {target} ({payload['address']}) [{payload['method']}]{suffix}", "1")
34
+ )
35
+ for sample in payload["samples"]:
36
+ rtt = sample.get("rtt_ms")
37
+ text = f"{rtt:.2f} ms" if rtt is not None else "timeout"
38
+ line = f" seq={sample['seq']:<3} " + (
39
+ console.paint(text, "32") if rtt is not None else console.paint(text, "31")
40
+ )
41
+ if sample.get("ttl"):
42
+ line += f" ttl={sample['ttl']}"
43
+ console.line(line)
44
+ stats = payload["stats"]
45
+ console.blank()
46
+ console.line(console.paint(f"--- {target} statistics ---", "1"))
47
+ console.line(f" {stats['sent']} sent, {stats['received']} received, {stats['loss_pct']}% loss")
48
+ if stats["received"]:
49
+ console.line(
50
+ f" rtt min/avg/max/mdev/jitter = {stats['min_ms']:.2f}/"
51
+ f"{stats['avg_ms']:.2f}/{stats['max_ms']:.2f}/"
52
+ f"{stats['mdev_ms']:.2f}/{stats['jitter_ms']:.2f} ms"
53
+ )
54
+ if payload.get("note"):
55
+ console.line(console.paint(f" note: {payload['note']}", "33"))
56
+
57
+
58
+ def render_dns(payload: dict, console: Console) -> None:
59
+ console.line(
60
+ console.paint(
61
+ f";; {payload['name']} @ {payload['server']}#{payload['port']} "
62
+ f"({payload.get('transport')}) {payload['rcode']} [{payload['resolver_source']}]",
63
+ "1",
64
+ )
65
+ )
66
+ flags = payload.get("flags") or {}
67
+ console.line(
68
+ f";; query_time {payload['query_time_ms']} ms"
69
+ + (f" flags {' '.join(k for k, v in flags.items() if v)}" if any(flags.values()) else "")
70
+ )
71
+ for query in payload.get("queries") or []:
72
+ if query["type"] != (payload["types"][0] if payload["types"] else None):
73
+ console.line(
74
+ f";; {query['type']:<6} {query['rcode']} "
75
+ f"{query['answer_count']} answer(s) {query['query_time_ms']} ms"
76
+ )
77
+ answers = payload["answer"]
78
+ if answers:
79
+ widths = [
80
+ max(len(str(record[key])) for record in answers) for key in ("name", "type", "ttl")
81
+ ]
82
+ for record in answers:
83
+ console.line(
84
+ f" {str(record['name']):<{widths[0]}} {record['type']:<{widths[1]}}"
85
+ f" {str(record['ttl']):>{widths[2]}} {record['value']}"
86
+ )
87
+ else:
88
+ console.line(console.paint(" (no answer)", "33"))
89
+ for error in payload.get("errors") or []:
90
+ console.line(console.paint(f" {error['type']}: {error['error']}", "31"))
91
+ if payload.get("note"):
92
+ console.line(console.paint(f" note: {payload['note']}", "33"))
93
+
94
+
95
+ def render_tcp(payload: dict, console: Console) -> None:
96
+ console.line(console.paint(f"TCP {payload['host']}", "1"))
97
+ for result in payload["results"]:
98
+ state = result["state"]
99
+ color = "32" if state == "open" else "31" if state == "closed" else "33"
100
+ label = state.ljust(20)
101
+ line = f" {result['port']:<6} {console.paint(label, color)} {fmt_ms(result['connect_ms'])}"
102
+ if result.get("banner"):
103
+ line += f" {result['banner'][:80]!r}"
104
+ elif result.get("detail") and state == "filtered":
105
+ line += f" {result['detail']}"
106
+ console.line(line)
107
+
108
+
109
+ def render_tls(payload: dict, console: Console) -> None:
110
+ cert = payload.get("certificate") or {}
111
+ verdict = payload["verdict"]
112
+ console.line(
113
+ console.paint(f"TLS {payload['host']}:{payload['port']} -> {payload['remote_ip']}", "1")
114
+ )
115
+ console.line(
116
+ f" version {payload['tls_version']} cipher {payload['cipher']}"
117
+ f" ({payload.get('cipher_bits')} bits) alpn {payload['alpn'] or '-'}"
118
+ )
119
+ if payload.get("verify_skipped"):
120
+ verified_text = "skipped (-k)"
121
+ else:
122
+ verified_text = "yes" if payload["verified"] else console.paint("NO", "31")
123
+ console.line(
124
+ f" verified {verified_text}"
125
+ + (f" ({payload['verify_error']})" if payload.get("verify_error") else "")
126
+ )
127
+ console.line(f" subject {cert.get('subject', {}).get('commonName', '-')}")
128
+ console.line(f" issuer {cert.get('issuer', {}).get('commonName', '-')}")
129
+ validity = f" valid {cert.get('not_before')} -> {cert.get('not_after')}"
130
+ if cert.get("days_left") is not None:
131
+ validity += f" ({cert['days_left']} days left)"
132
+ console.line(validity)
133
+ if cert.get("san"):
134
+ console.line(f" san {', '.join(cert['san'][:8])}")
135
+ if payload.get("chain"):
136
+ console.line(f" chain {' <- '.join(payload['chain'])}")
137
+ console.line(
138
+ f" timing connect {fmt_ms(payload['connect_ms'])}"
139
+ f" handshake {fmt_ms(payload.get('handshake_ms'))}"
140
+ )
141
+ if verdict["expired"]:
142
+ console.line(console.paint(" ! certificate expired", "31"))
143
+ elif verdict["expiring_soon"]:
144
+ console.line(console.paint(" ! certificate expires within 30 days", "33"))
145
+ if payload.get("note"):
146
+ console.line(console.paint(f" note: {payload['note']}", "33"))
147
+
148
+
149
+ def render_http(payload: dict, console: Console) -> None:
150
+ phases = payload["phases"]
151
+ console.line(console.paint(f"{payload['status']} {payload['reason']} {payload['url']}", "1"))
152
+ size_text = f"{payload['size']} B"
153
+ if payload.get("wire_size") and payload["wire_size"] != payload["size"]:
154
+ size_text += f" ({payload['wire_size']} B on the wire, {payload.get('content_encoding')})"
155
+ console.line(
156
+ f" HTTP/{payload['http_version']} {payload['remote_ip']}:{payload['remote_port']}"
157
+ f" {size_text}" + (" (truncated)" if payload["truncated"] else "")
158
+ )
159
+ if payload.get("tls"):
160
+ console.line(f" tls {payload['tls']['version']} {payload['tls']['cipher']}")
161
+ total = max(phases["total_ms"], 0.001)
162
+ for label, key, color in (
163
+ ("DNS", "dns_ms", "36"),
164
+ ("TCP", "connect_ms", "36"),
165
+ ("TLS", "tls_ms", "35"),
166
+ ("Send", "write_ms", "34"),
167
+ ("Wait", "wait_ms", "33"),
168
+ ("Read", "transfer_ms", "32"),
169
+ ):
170
+ value = phases[key]
171
+ if key == "tls_ms" and not value:
172
+ continue
173
+ console.line(f" {label:<6} {fmt_ms(value):>9} {console.paint(bar(value / total), color)}")
174
+ console.line(f" {'Total':<6} {fmt_ms(phases['total_ms']):>9}")
175
+ for hop in payload["redirects"]:
176
+ console.line(f" -> {hop['status']} {hop['location']}")
177
+ if payload.get("decode_error"):
178
+ console.line(console.paint(f" note: body not decoded ({payload['decode_error']})", "33"))
179
+
180
+
181
+ def render_doctor(payload: dict, console: Console) -> None:
182
+ console.line(console.paint(f"host {payload['hostname']} ({payload['platform']})", "1"))
183
+ resolvers = payload["resolvers"]
184
+ console.line(
185
+ f"resolvers {', '.join(resolvers['servers'])} [{resolvers['source']}]"
186
+ + (" (stub)" if resolvers.get("stub") else "")
187
+ )
188
+ console.line(f"egress {payload['egress_ip'] or '-'}")
189
+ addresses = payload["addresses"]
190
+ console.line(f"ipv4 {', '.join(addresses['ipv4']) or '-'}")
191
+ console.line(f"ipv6 {', '.join(addresses['ipv6']) or '-'}")
192
+ if payload["proxy"]:
193
+ console.line(f"proxy {', '.join(f'{k}={v}' for k, v in payload['proxy'].items())}")
194
+ console.line("checks")
195
+ for check in payload["checks"]:
196
+ mark = console.paint("ok", "32") if check["ok"] else console.paint("..", "33")
197
+ console.line(f" [{mark}] {check['check']:<20} {check['detail']}")
198
+ for warning in payload["warnings"]:
199
+ console.line(console.paint(f" ! {warning}", "33"))
200
+
201
+
202
+ def render_slo(payload: dict, console: Console) -> None:
203
+ slo = payload.get("slo")
204
+ if not slo:
205
+ return
206
+ verdict = console.paint("PASS", "32") if slo["passed"] else console.paint("FAIL", "31")
207
+ console.blank()
208
+ console.line(f" slo {slo['expression']} {verdict}")
209
+ for check in slo["checks"]:
210
+ actual = "-" if check["actual"] is None else check["actual"]
211
+ console.line(f" {check['expr']:<28} actual {actual}")
212
+
213
+
214
+ RENDERERS: dict[str, Callable[[dict, Console], None]] = {
215
+ "ping": render_ping,
216
+ "dns": render_dns,
217
+ "tcp": render_tcp,
218
+ "tls": render_tls,
219
+ "http": render_http,
220
+ "doctor": render_doctor,
221
+ }
netk/slo.py ADDED
@@ -0,0 +1,74 @@
1
+ """``--slo``: turn an observation into a pass/fail gate for CI.
2
+
3
+ Syntax is deliberately boring: comma-separated comparisons against numeric fields
4
+ of the payload, using dotted paths.
5
+
6
+ --slo "stats.avg_ms<50,stats.loss_pct<=1" netk ping
7
+ --slo "phases.total_ms<500,status<400" netk http
8
+ --slo "days_left>=30" netk tls
9
+
10
+ A violated budget exits 4 and never overwrites a more specific negative verdict
11
+ (1) or timeout (124); ``payload["slo"]`` always records what was checked.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import operator
17
+ import re
18
+
19
+ from .contract import RC_BUDGET, NetkError
20
+
21
+ _OPS = {
22
+ "<": operator.lt,
23
+ "<=": operator.le,
24
+ ">": operator.gt,
25
+ ">=": operator.ge,
26
+ "==": operator.eq,
27
+ "=": operator.eq,
28
+ "!=": operator.ne,
29
+ }
30
+ _TERM = re.compile(
31
+ r"^(?P<path>[A-Za-z_][A-Za-z0-9_.]*)\s*(?P<op><=|>=|==|!=|<|>|=)\s*"
32
+ r"(?P<value>-?\d+(?:\.\d+)?)$"
33
+ )
34
+
35
+
36
+ def evaluate(expression: str, payload: dict) -> dict:
37
+ checks = []
38
+ for term in expression.split(","):
39
+ term = term.strip()
40
+ if not term:
41
+ continue
42
+ match = _TERM.match(term)
43
+ if not match:
44
+ raise NetkError(
45
+ "usage", f"bad --slo term {term!r}; want field<number, e.g. stats.avg_ms<50", 2
46
+ )
47
+ actual = lookup(payload, match["path"])
48
+ passed = (
49
+ isinstance(actual, (int, float))
50
+ and not isinstance(actual, bool)
51
+ and _OPS[match["op"]](actual, float(match["value"]))
52
+ )
53
+ checks.append({"expr": term, "actual": actual, "pass": passed})
54
+ if not checks:
55
+ raise NetkError("usage", "--slo needs at least one comparison", 2)
56
+ return {"expression": expression, "passed": all(c["pass"] for c in checks), "checks": checks}
57
+
58
+
59
+ def lookup(payload: dict, path: str):
60
+ value = payload
61
+ for part in path.split("."):
62
+ if isinstance(value, dict) and part in value:
63
+ value = value[part]
64
+ else:
65
+ return None
66
+ return value
67
+
68
+
69
+ def apply(payload: dict, expression: str) -> dict:
70
+ result = evaluate(expression, payload)
71
+ payload["slo"] = result
72
+ if not result["passed"] and payload.get("rc", 0) == 0:
73
+ payload["rc"] = RC_BUDGET
74
+ return payload
netk/targets.py ADDED
@@ -0,0 +1,196 @@
1
+ """Target parsing, name resolution and TCP connect helpers shared by every probe.
2
+
3
+ Keeping these in one place is what makes ``netk tcp``, ``netk tls`` and ``netk http``
4
+ agree on the same ``host:port`` grammar and the same IPv4/IPv6 happy-eyeballs-lite
5
+ policy: first address that accepts the connection wins, DNS time counted separately.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import contextlib
11
+ import socket
12
+ import time
13
+ from collections.abc import Iterable, Sequence
14
+ from typing import NamedTuple
15
+
16
+ from .contract import RC_TIMEOUT, NetkError
17
+
18
+ Addr = tuple[int, tuple]
19
+
20
+
21
+ class ConnectResult(NamedTuple):
22
+ sock: socket.socket
23
+ family: int
24
+ sockaddr: tuple
25
+ connect_s: float
26
+ dns_s: float
27
+
28
+
29
+ def parse_host_port(target: str, default_port: int) -> tuple[str, int]:
30
+ """Accept ``host``, ``host:port``, ``[v6]:port`` and full URLs."""
31
+ if "://" in target:
32
+ from urllib.parse import urlsplit
33
+
34
+ parts = urlsplit(target)
35
+ port = parts.port or (443 if parts.scheme == "https" else 80)
36
+ if not parts.hostname:
37
+ raise NetkError("usage", f"bad URL {target!r}", 2)
38
+ return parts.hostname, port
39
+ if target.startswith("["):
40
+ host, _, rest = target[1:].partition("]")
41
+ text = rest.lstrip(":")
42
+ return host, int(text) if text.isdigit() else default_port
43
+ if target.count(":") == 1:
44
+ host, port_text = target.split(":")
45
+ if port_text.isdigit():
46
+ return host, int(port_text)
47
+ return target, default_port
48
+
49
+
50
+ def resolve(host: str, port: int, family: int = socket.AF_UNSPEC) -> tuple[list[Addr], float]:
51
+ """Return unique ``(family, sockaddr)`` pairs plus how long the lookup took."""
52
+ started = time.perf_counter()
53
+ try:
54
+ infos = socket.getaddrinfo(host, port, family, type=socket.SOCK_STREAM)
55
+ except socket.gaierror as exc:
56
+ raise NetkError("dns", f"cannot resolve {host}: {exc}") from exc
57
+ elapsed = time.perf_counter() - started
58
+ seen, out = set(), []
59
+ for fam, _, _, _, sockaddr in infos:
60
+ key = (fam, sockaddr)
61
+ if key in seen:
62
+ continue
63
+ seen.add(key)
64
+ out.append((fam, sockaddr))
65
+ if not out:
66
+ raise NetkError("dns", f"no address for {host} in the requested family")
67
+ return out, elapsed
68
+
69
+
70
+ def with_port(sockaddr: tuple, port: int) -> tuple:
71
+ """Replace the port inside an IPv4/IPv6 sockaddr without losing scope ids."""
72
+ return (sockaddr[0], port, *sockaddr[2:])
73
+
74
+
75
+ def connect_addresses(
76
+ addrs: Sequence[Addr], host: str, port: int, timeout: float
77
+ ) -> tuple[socket.socket, tuple, float]:
78
+ """Try each resolved address in order; the first TCP handshake wins."""
79
+ last_error: OSError | None = None
80
+ for family, sockaddr in addrs:
81
+ sockaddr = with_port(sockaddr, port)
82
+ candidate = socket.socket(family, socket.SOCK_STREAM)
83
+ candidate.settimeout(timeout)
84
+ started = time.perf_counter()
85
+ try:
86
+ candidate.connect(sockaddr)
87
+ return candidate, sockaddr, time.perf_counter() - started
88
+ except socket.timeout:
89
+ candidate.close()
90
+ raise NetkError(
91
+ "timeout", f"connect to {host}:{port} timed out after {timeout}s", RC_TIMEOUT
92
+ ) from None
93
+ except OSError as exc:
94
+ candidate.close()
95
+ last_error = exc
96
+ raise NetkError("connection", f"connect to {host}:{port} failed: {last_error}")
97
+
98
+
99
+ def tcp_connect(
100
+ host: str, port: int, timeout: float, addrs: Sequence[Addr] | None = None
101
+ ) -> ConnectResult:
102
+ """Resolve (unless already resolved) and connect, with phase timing."""
103
+ if addrs is None:
104
+ addrs, dns_s = resolve(host, port)
105
+ else:
106
+ dns_s = 0.0
107
+ sock, sockaddr, connect_s = connect_addresses(addrs, host, port, timeout)
108
+ return ConnectResult(sock, _family_of(addrs, sockaddr), sockaddr, connect_s, dns_s)
109
+
110
+
111
+ def _family_of(addrs: Sequence[Addr], sockaddr: tuple) -> int:
112
+ for family, candidate in addrs:
113
+ if candidate == sockaddr:
114
+ return family
115
+ return socket.AF_INET
116
+
117
+
118
+ # ------------------------------------------------------------------- system bits
119
+
120
+
121
+ def split_servers(value: str) -> list[str]:
122
+ return [s for s in str(value).replace(",", " ").replace(";", " ").split() if s]
123
+
124
+
125
+ def windows_resolvers() -> list[str]:
126
+ """Static + DHCP DNS servers, read per interface (global NameServer is often empty)."""
127
+ import winreg
128
+
129
+ base = r"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters"
130
+ found: list[str] = []
131
+ try:
132
+ with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, base) as key:
133
+ with contextlib.suppress(OSError):
134
+ found += split_servers(winreg.QueryValueEx(key, "NameServer")[0])
135
+ with winreg.OpenKey(key, "Interfaces") as interfaces:
136
+ index = 0
137
+ while True:
138
+ try:
139
+ guid = winreg.EnumKey(interfaces, index)
140
+ except OSError:
141
+ break
142
+ index += 1
143
+ try:
144
+ with winreg.OpenKey(interfaces, guid) as iface:
145
+ for name in ("DhcpNameServer", "NameServer"):
146
+ with contextlib.suppress(OSError):
147
+ found += split_servers(winreg.QueryValueEx(iface, name)[0])
148
+ except OSError:
149
+ continue
150
+ except OSError:
151
+ pass
152
+ return found
153
+
154
+
155
+ def local_addresses() -> dict[str, list[str]]:
156
+ """Best-effort set of addresses bound to this host, split by family."""
157
+ out: dict[str, list[str]] = {"ipv4": [], "ipv6": []}
158
+ try:
159
+ infos = socket.getaddrinfo(socket.gethostname(), None)
160
+ except socket.gaierror:
161
+ infos = []
162
+ for family, _, _, _, sockaddr in infos:
163
+ value = sockaddr[0].split("%", 1)[0]
164
+ bucket = "ipv6" if family == socket.AF_INET6 else "ipv4"
165
+ if value not in out[bucket]:
166
+ out[bucket].append(value)
167
+ if not out["ipv4"]:
168
+ egress = egress_ip()
169
+ if egress:
170
+ out["ipv4"].append(egress)
171
+ return out
172
+
173
+
174
+ def egress_ip() -> str | None:
175
+ """The address the kernel would pick for an outbound IPv4 connection.
176
+
177
+ ``connect()`` on UDP sends no packet, so this stays a local, passive check.
178
+ """
179
+ for probe in ("1.1.1.1", "8.8.8.8"):
180
+ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
181
+ try:
182
+ sock.connect((probe, 53))
183
+ return sock.getsockname()[0]
184
+ except OSError:
185
+ continue
186
+ finally:
187
+ sock.close()
188
+ return None
189
+
190
+
191
+ def unique(values: Iterable[str]) -> list[str]:
192
+ out: list[str] = []
193
+ for value in values:
194
+ if value not in out:
195
+ out.append(value)
196
+ return out