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.
@@ -0,0 +1,187 @@
1
+ """``netk schema``: the contract as JSON Schema, for agents that validate before trusting.
2
+
3
+ This is the one subcommand whose stdout is *not* an envelope: it is a schema
4
+ document, because that is the thing a caller wants to feed to a validator.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from ..contract import (
10
+ CONTRACT_KEYS,
11
+ ERROR_TYPES,
12
+ RC_BUDGET,
13
+ RC_INTERNAL,
14
+ RC_INTERRUPT,
15
+ RC_NEGATIVE,
16
+ RC_OK,
17
+ RC_TIMEOUT,
18
+ RC_USAGE,
19
+ VERSION,
20
+ )
21
+
22
+ RC_CODES = [RC_OK, RC_NEGATIVE, RC_USAGE, RC_BUDGET, RC_INTERNAL, RC_TIMEOUT, RC_INTERRUPT]
23
+
24
+ PAYLOAD_KEYS = {
25
+ "ping": ["target", "address", "family", "dns_ms", "count", "method", "samples", "stats"],
26
+ "dns": [
27
+ "name",
28
+ "types",
29
+ "resolver_source",
30
+ "answer",
31
+ "authority",
32
+ "additional",
33
+ "queries",
34
+ "rcode",
35
+ "query_time_ms",
36
+ ],
37
+ "tcp": ["host", "addresses", "results"],
38
+ "tls": [
39
+ "host",
40
+ "port",
41
+ "remote_ip",
42
+ "connect_ms",
43
+ "handshake_ms",
44
+ "tls_version",
45
+ "cipher",
46
+ "verified",
47
+ "certificate",
48
+ "verdict",
49
+ "days_left",
50
+ ],
51
+ "http": [
52
+ "url",
53
+ "final_url",
54
+ "status",
55
+ "reason",
56
+ "http_version",
57
+ "remote_ip",
58
+ "phases",
59
+ "size",
60
+ "wire_size",
61
+ "truncated",
62
+ "redirects",
63
+ ],
64
+ "doctor": [
65
+ "hostname",
66
+ "platform",
67
+ "python",
68
+ "resolvers",
69
+ "resolver_count",
70
+ "egress_ip",
71
+ "addresses",
72
+ "checks",
73
+ "warnings",
74
+ ],
75
+ }
76
+
77
+
78
+ def build_schema() -> dict:
79
+ return {
80
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
81
+ "$id": f"urn:netk:schema:{VERSION}",
82
+ "title": "netk payload",
83
+ "description": (
84
+ "One JSON object per invocation. `ok` reports whether the tool finished, "
85
+ "`rc` reports the verdict; they are deliberately independent."
86
+ ),
87
+ "type": "object",
88
+ "required": list(CONTRACT_KEYS),
89
+ "properties": {
90
+ "ok": {
91
+ "type": "boolean",
92
+ "description": "the tool completed its work (not 'the check passed')",
93
+ },
94
+ "cmd": {"type": ["string", "null"], "enum": sorted(PAYLOAD_KEYS) + [None]},
95
+ "rc": {
96
+ "type": "integer",
97
+ "enum": RC_CODES,
98
+ "description": "0 pass, 1 negative, 2 usage, 4 SLO budget, "
99
+ "70 internal, 124 timeout, 130 interrupted",
100
+ },
101
+ "error_type": {"type": ["string", "null"], "enum": list(ERROR_TYPES) + [None]},
102
+ "error": {"type": ["string", "null"]},
103
+ "note": {"type": "string"},
104
+ "slo": {"$ref": "#/$defs/slo"},
105
+ },
106
+ "additionalProperties": True,
107
+ "allOf": [
108
+ {
109
+ "if": {"properties": {"ok": {"const": False}}, "required": ["ok"]},
110
+ "then": {
111
+ "required": ["error_type", "error"],
112
+ "properties": {"error_type": {"type": "string"}},
113
+ },
114
+ }
115
+ ],
116
+ "$defs": {
117
+ "slo": {
118
+ "type": "object",
119
+ "required": ["expression", "passed", "checks"],
120
+ "properties": {
121
+ "expression": {"type": "string"},
122
+ "passed": {"type": "boolean"},
123
+ "checks": {
124
+ "type": "array",
125
+ "items": {
126
+ "type": "object",
127
+ "required": ["expr", "actual", "pass"],
128
+ "properties": {
129
+ "expr": {"type": "string"},
130
+ "actual": {"type": ["number", "null"]},
131
+ "pass": {"type": "boolean"},
132
+ },
133
+ },
134
+ },
135
+ },
136
+ },
137
+ "stats": {
138
+ "type": "object",
139
+ "required": ["sent", "received", "loss_pct"],
140
+ "properties": {
141
+ "sent": {"type": "integer"},
142
+ "received": {"type": "integer"},
143
+ "loss_pct": {"type": "number"},
144
+ "min_ms": {"type": ["number", "null"]},
145
+ "avg_ms": {"type": ["number", "null"]},
146
+ "max_ms": {"type": ["number", "null"]},
147
+ "mdev_ms": {"type": ["number", "null"]},
148
+ "jitter_ms": {"type": ["number", "null"]},
149
+ },
150
+ },
151
+ "record": {
152
+ "type": "object",
153
+ "required": ["name", "type", "ttl", "value"],
154
+ "properties": {
155
+ "name": {"type": "string"},
156
+ "type": {"type": "string"},
157
+ "ttl": {"type": "integer"},
158
+ "value": {"type": "string"},
159
+ },
160
+ },
161
+ "phases": {
162
+ "type": "object",
163
+ "required": [
164
+ "dns_ms",
165
+ "connect_ms",
166
+ "tls_ms",
167
+ "write_ms",
168
+ "wait_ms",
169
+ "transfer_ms",
170
+ "total_ms",
171
+ ],
172
+ "properties": {
173
+ key: {"type": "number"}
174
+ for key in (
175
+ "dns_ms",
176
+ "connect_ms",
177
+ "tls_ms",
178
+ "write_ms",
179
+ "wait_ms",
180
+ "transfer_ms",
181
+ "total_ms",
182
+ )
183
+ },
184
+ },
185
+ },
186
+ "x-netk-payload": {cmd: {"required": keys} for cmd, keys in PAYLOAD_KEYS.items()},
187
+ }
netk/commands/tcp.py ADDED
@@ -0,0 +1,67 @@
1
+ """``netk tcp``: port reachability, connect time, optional banner.
2
+
3
+ All ports share one resolution, so a five-port sweep does not count DNS five times.
4
+ "filtered" means the connect timed out (dropped packets), while "closed" means the
5
+ host answered with RST -- two different failure modes an agent should not conflate.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import socket
11
+ import time
12
+
13
+ from ..contract import RC_NEGATIVE, NetkError, envelope
14
+ from ..targets import resolve, tcp_connect
15
+
16
+
17
+ def run(args) -> dict:
18
+ host = args.host
19
+ ports = args.ports or [80]
20
+ for port in ports:
21
+ if not 0 < port < 65536:
22
+ raise NetkError("usage", f"port {port} out of range 1..65535", 2)
23
+
24
+ addrs, dns_s = resolve(host, ports[0], socket.AF_UNSPEC)
25
+ payload = envelope(
26
+ "tcp",
27
+ host=host,
28
+ addresses=[sockaddr[0] for _, sockaddr in addrs],
29
+ dns_ms=round(dns_s * 1000, 3),
30
+ )
31
+
32
+ results = []
33
+ for port in ports:
34
+ entry = {"port": port, "state": "closed", "connect_ms": None, "banner": None}
35
+ started = time.perf_counter()
36
+ try:
37
+ sock, _, sockaddr, connect_s, _ = tcp_connect(host, port, args.timeout, addrs)
38
+ entry.update(
39
+ {
40
+ "state": "open",
41
+ "connect_ms": round(connect_s * 1000, 3),
42
+ "remote_ip": sockaddr[0],
43
+ }
44
+ )
45
+ if args.banner:
46
+ try:
47
+ sock.settimeout(min(args.timeout, 2.0))
48
+ entry["banner"] = (
49
+ sock.recv(args.banner_bytes).decode("utf-8", "replace").strip()
50
+ )
51
+ except OSError:
52
+ pass
53
+ sock.close()
54
+ except NetkError as exc:
55
+ if exc.error_type == "dns":
56
+ raise
57
+ entry["detail"] = exc.message
58
+ if exc.error_type == "timeout":
59
+ entry["state"] = "filtered"
60
+ entry["elapsed_ms"] = round((time.perf_counter() - started) * 1000, 3)
61
+ results.append(entry)
62
+
63
+ payload["results"] = results
64
+ payload["open_count"] = sum(1 for item in results if item["state"] == "open")
65
+ if payload["open_count"] != len(results):
66
+ payload["rc"] = RC_NEGATIVE
67
+ return payload
netk/commands/tls.py ADDED
@@ -0,0 +1,200 @@
1
+ """TLS handshake and certificate facts: who signed it, when it expires, what ALPN won.
2
+
3
+ Verification is never silently skipped: when the chain fails we reconnect without
4
+ verification *only* to decode the certificate, and keep ``verified=false`` plus the
5
+ original error in the payload. ``-k`` is explicit and shows up as ``verify_skipped``.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import contextlib
11
+ import os
12
+ import ssl
13
+ import tempfile
14
+ import time
15
+
16
+ from ..contract import RC_NEGATIVE, NetkError, envelope
17
+ from ..targets import parse_host_port, tcp_connect
18
+
19
+ DEFAULT_ALPN = ["h2", "http/1.1"]
20
+
21
+
22
+ def _cert_epoch(date_string: str | None) -> float | None:
23
+ if not date_string:
24
+ return None
25
+ try:
26
+ return ssl.cert_time_to_seconds(date_string)
27
+ except (ValueError, AttributeError):
28
+ from email.utils import parsedate_to_datetime
29
+
30
+ try:
31
+ return parsedate_to_datetime(date_string).timestamp()
32
+ except (TypeError, ValueError, IndexError):
33
+ return None
34
+
35
+
36
+ def _name_dict(name_sequence: tuple) -> dict[str, str]:
37
+ """Flatten an X.509 name tuple into {key: value}, handling multi-valued RDNs."""
38
+ result = {}
39
+ for rdn in name_sequence or ():
40
+ for pair in rdn:
41
+ if len(pair) == 2 and pair[0]:
42
+ result[pair[0]] = pair[1]
43
+ return result
44
+
45
+
46
+ def _cert_summary(cert: dict | None) -> dict | None:
47
+ if not cert:
48
+ return None
49
+ expiry = _cert_epoch(cert.get("notAfter"))
50
+ sans = [value for key, value in cert.get("subjectAltName", ()) if key == "DNS"]
51
+ ip_sans = [value for key, value in cert.get("subjectAltName", ()) if key == "IP Address"]
52
+ return {
53
+ "subject": _name_dict(cert.get("subject", ())),
54
+ "issuer": _name_dict(cert.get("issuer", ())),
55
+ "san": sans,
56
+ "ip_san": ip_sans,
57
+ "not_before": cert.get("notBefore"),
58
+ "not_after": cert.get("notAfter"),
59
+ "days_left": None if expiry is None else int((expiry - time.time()) // 86400),
60
+ "serial": cert.get("serialNumber"),
61
+ "version": cert.get("version"),
62
+ }
63
+
64
+
65
+ def _unverified_cert(sock: ssl.SSLSocket) -> dict | None:
66
+ """Decode the DER blob via a temp PEM: stdlib has no public DER->dict API."""
67
+ path = None
68
+ try:
69
+ der = sock.getpeercert(binary_form=True)
70
+ if not der:
71
+ return None
72
+ descriptor, path = tempfile.mkstemp(suffix=".pem")
73
+ with os.fdopen(descriptor, "w", encoding="ascii") as output:
74
+ output.write(ssl.DER_cert_to_PEM_cert(der))
75
+ return ssl._ssl._test_decode_cert(path)
76
+ except Exception:
77
+ return None
78
+ finally:
79
+ if path:
80
+ with contextlib.suppress(OSError):
81
+ os.unlink(path)
82
+
83
+
84
+ def _chain_subjects(sock: ssl.SSLSocket) -> list[str]:
85
+ """Verified chain, when the interpreter exposes it (Python 3.13+)."""
86
+ try:
87
+ chain = sock.get_verified_chain()
88
+ except (AttributeError, ssl.SSLError):
89
+ return []
90
+ subjects = []
91
+ for cert in chain:
92
+ if not isinstance(cert, dict):
93
+ continue
94
+ common = _name_dict(cert.get("subject", ())).get("commonName")
95
+ subjects.append(common or "")
96
+ return [s for s in subjects if s]
97
+
98
+
99
+ def _handshake(
100
+ host: str, port: int, timeout: float, insecure: bool, server_name: str | None
101
+ ) -> dict:
102
+ sock, _, sockaddr, connect_s, _ = tcp_connect(host, port, timeout)
103
+ sock.settimeout(timeout)
104
+ context = ssl.create_default_context()
105
+ context.check_hostname = not insecure
106
+ context.verify_mode = ssl.CERT_NONE if insecure else ssl.CERT_REQUIRED
107
+ context.set_alpn_protocols(DEFAULT_ALPN)
108
+ verified, verify_error = True, None
109
+ started = time.perf_counter()
110
+ try:
111
+ tls_sock = context.wrap_socket(sock, server_hostname=server_name or host)
112
+ except ssl.SSLCertVerificationError as exc:
113
+ verified, verify_error = False, str(exc)
114
+ sock.close()
115
+ # Reconnect unverified: the certificate is still worth reporting.
116
+ sock, _, sockaddr, connect_s, _ = tcp_connect(host, port, timeout)
117
+ sock.settimeout(timeout)
118
+ context = ssl.create_default_context()
119
+ context.check_hostname = False
120
+ context.verify_mode = ssl.CERT_NONE
121
+ context.set_alpn_protocols(DEFAULT_ALPN)
122
+ started = time.perf_counter()
123
+ try:
124
+ tls_sock = context.wrap_socket(sock, server_hostname=server_name or host)
125
+ except ssl.SSLError as inner:
126
+ sock.close()
127
+ raise NetkError("tls", f"TLS handshake failed: {inner}") from inner
128
+ except ssl.SSLError as exc:
129
+ sock.close()
130
+ raise NetkError("tls", f"TLS handshake failed: {exc}") from exc
131
+
132
+ handshake_s = time.perf_counter() - started
133
+ try:
134
+ cert = tls_sock.getpeercert() or {}
135
+ if insecure or not verified:
136
+ cert = _unverified_cert(tls_sock) or cert
137
+ cipher = tls_sock.cipher() or (None, None, None)
138
+ result = {
139
+ "host": host,
140
+ "port": port,
141
+ "remote_ip": sockaddr[0],
142
+ "connect_ms": round(connect_s * 1000, 3),
143
+ "handshake_ms": round(handshake_s * 1000, 3),
144
+ "tls_version": tls_sock.version(),
145
+ "cipher": cipher[0],
146
+ "cipher_bits": cipher[2],
147
+ "alpn": tls_sock.selected_alpn_protocol(),
148
+ "verified": verified,
149
+ "verify_skipped": insecure,
150
+ "verify_error": verify_error,
151
+ "certificate": _cert_summary(cert),
152
+ }
153
+ chain = _chain_subjects(tls_sock)
154
+ if chain:
155
+ result["chain"] = chain
156
+ result["chain_length"] = len(chain)
157
+ finally:
158
+ tls_sock.close()
159
+
160
+ cert_info = result.get("certificate") or {}
161
+ days_left = cert_info.get("days_left")
162
+ result["verdict"] = {
163
+ "valid": None if insecure else (bool(verified) and (days_left is None or days_left >= 0)),
164
+ "expiring_soon": days_left is not None and 0 <= days_left < 30,
165
+ "expired": days_left is not None and days_left < 0,
166
+ }
167
+ return result
168
+
169
+
170
+ def probe_tls(
171
+ host: str,
172
+ port: int = 443,
173
+ timeout: float = 5.0,
174
+ insecure: bool = False,
175
+ server_name: str | None = None,
176
+ ) -> dict:
177
+ return _handshake(host, port, timeout, insecure, server_name)
178
+
179
+
180
+ def run(args) -> dict:
181
+ host, port = parse_host_port(args.target, args.port)
182
+ result = probe_tls(host, port, args.timeout, args.insecure, args.servername)
183
+ payload = envelope("tls", **result)
184
+ payload["days_left"] = (result.get("certificate") or {}).get("days_left")
185
+
186
+ threshold = args.days
187
+ if threshold is not None:
188
+ payload["days_threshold"] = threshold
189
+ days_left = payload["days_left"]
190
+ if days_left is None:
191
+ raise NetkError("tls", "certificate expiry could not be decoded", RC_NEGATIVE)
192
+ if days_left < threshold:
193
+ payload["rc"] = RC_NEGATIVE
194
+ payload["note"] = f"certificate expires in {days_left} days (< {threshold})"
195
+ elif result["verdict"]["valid"] is False:
196
+ payload["rc"] = RC_NEGATIVE
197
+ return payload
198
+
199
+
200
+ __all__ = ["probe_tls", "run", "DEFAULT_ALPN"]
netk/contract.py ADDED
@@ -0,0 +1,132 @@
1
+ """The process contract: exit codes, error taxonomy, console and JSON envelope.
2
+
3
+ Every subcommand is a pure-ish function that returns a ``dict``. Only ``cli.main``
4
+ writes to stdout, so ``--json`` and the human renderer always describe the exact
5
+ same object: there is no second code path that can drift.
6
+
7
+ Contract shape (stable across 0.x)::
8
+
9
+ {"ok": true, "cmd": "dns", "rc": 0, "error_type": null, "error": null, ...}
10
+
11
+ ``ok`` the tool finished its work (not the same as "the check passed")
12
+ ``rc`` 0 pass, 1 negative verdict, 2 usage, 4 budget/SLO, 70 internal,
13
+ 124 timeout, 130 interrupted -- mirrors shell semantics
14
+ ``error_type`` closed enum so an agent can branch without parsing prose
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import os
21
+ import sys
22
+ from typing import Any, TextIO
23
+
24
+ RC_OK = 0
25
+ RC_NEGATIVE = 1
26
+ RC_USAGE = 2
27
+ RC_BUDGET = 4
28
+ RC_INTERNAL = 70
29
+ RC_TIMEOUT = 124
30
+ RC_INTERRUPT = 130
31
+
32
+ ERROR_TYPES = (
33
+ "usage",
34
+ "dns",
35
+ "connection",
36
+ "timeout",
37
+ "tls",
38
+ "http",
39
+ "slo",
40
+ "internal",
41
+ )
42
+
43
+ CONTRACT_KEYS = ("ok", "cmd", "rc", "error_type", "error")
44
+
45
+ VERSION = "0.2.0"
46
+
47
+
48
+ class NetkError(Exception):
49
+ """A classified failure that still travels through the JSON contract.
50
+
51
+ Probes raise this instead of returning partial payloads; the CLI turns it into
52
+ ``ok=false`` plus the same envelope, which keeps failure paths identical to
53
+ success paths for machine consumers.
54
+ """
55
+
56
+ def __init__(self, error_type: str, message: str, rc: int = RC_NEGATIVE) -> None:
57
+ if error_type not in ERROR_TYPES:
58
+ error_type = "internal"
59
+ super().__init__(message)
60
+ self.error_type = error_type
61
+ self.message = message
62
+ self.rc = rc
63
+
64
+ def as_payload(self, cmd: str | None = None) -> dict[str, Any]:
65
+ return error_payload(cmd, self.error_type, self.message, self.rc)
66
+
67
+
68
+ def error_payload(
69
+ cmd: str | None, error_type: str, message: str, rc: int = RC_NEGATIVE
70
+ ) -> dict[str, Any]:
71
+ return {
72
+ "ok": False,
73
+ "cmd": cmd,
74
+ "rc": rc,
75
+ "error_type": error_type,
76
+ "error": message,
77
+ }
78
+
79
+
80
+ def envelope(cmd: str, rc: int = RC_OK, **payload: Any) -> dict[str, Any]:
81
+ """Start a payload with the five contract keys in a fixed order."""
82
+ base: dict[str, Any] = {
83
+ "ok": True,
84
+ "cmd": cmd,
85
+ "rc": rc,
86
+ "error_type": None,
87
+ "error": None,
88
+ }
89
+ base.update(payload)
90
+ return base
91
+
92
+
93
+ def ordered(payload: dict[str, Any]) -> dict[str, Any]:
94
+ """Keep the contract keys first even if a payload was built out of order."""
95
+ out = {key: payload[key] for key in CONTRACT_KEYS if key in payload}
96
+ out.update({key: value for key, value in payload.items() if key not in out})
97
+ return out
98
+
99
+
100
+ def emit(payload: dict[str, Any], as_json: bool, stream: TextIO | None = None) -> int:
101
+ """Write the payload (JSON one-liner only when asked) and return the exit code."""
102
+ stream = stream if stream is not None else sys.stdout
103
+ if as_json:
104
+ text = json.dumps(ordered(payload), ensure_ascii=False, separators=(",", ":"))
105
+ stream.write(text + "\n")
106
+ return int(payload.get("rc", RC_OK))
107
+
108
+
109
+ class Console:
110
+ """Color-aware writer, injectable so tests never depend on a real TTY."""
111
+
112
+ def __init__(self, stream: TextIO | None = None, use_color: bool | None = None) -> None:
113
+ self.stream = stream if stream is not None else sys.stdout
114
+ if use_color is None:
115
+ use_color = bool(_isatty(self.stream)) and os.environ.get("NO_COLOR") is None
116
+ self.use_color = use_color
117
+
118
+ def paint(self, text: str, code: str) -> str:
119
+ return f"\033[{code}m{text}\033[0m" if self.use_color else text
120
+
121
+ def line(self, text: str = "") -> None:
122
+ self.stream.write(text + "\n")
123
+
124
+ def blank(self) -> None:
125
+ self.stream.write("\n")
126
+
127
+
128
+ def _isatty(stream: TextIO) -> bool:
129
+ try:
130
+ return bool(stream.isatty())
131
+ except (AttributeError, ValueError):
132
+ return False
netk/dns/__init__.py ADDED
@@ -0,0 +1,18 @@
1
+ """DNS wire codec, resolver discovery and transport clients."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .client import dns_query
6
+ from .codec import Q_TYPES, build_query, dedupe, parse_response
7
+ from .resolver import resolver_config, split_endpoint, system_resolvers
8
+
9
+ __all__ = [
10
+ "dns_query",
11
+ "build_query",
12
+ "parse_response",
13
+ "dedupe",
14
+ "Q_TYPES",
15
+ "resolver_config",
16
+ "system_resolvers",
17
+ "split_endpoint",
18
+ ]