devdoor 0.1.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,143 @@
1
+ """Windows platform adapter (zero-admin ``.localhost`` default + elevated ``.test``)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from pathlib import Path
7
+
8
+ from devdoor.platform.base import (
9
+ CommandRunner,
10
+ default_command_runner,
11
+ list_managed_hosts,
12
+ mutate_hosts_file,
13
+ render_hosts_with_added,
14
+ render_hosts_without_all_devdoor,
15
+ render_hosts_without_host,
16
+ run_checked,
17
+ )
18
+ from devdoor.proxy.certs import ROOT_CA_CN
19
+
20
+
21
+ def _default_windows_hosts_path() -> Path:
22
+ system_root = os.environ.get("SYSTEMROOT", r"C:\Windows")
23
+ return Path(system_root) / "System32" / "drivers" / "etc" / "hosts"
24
+
25
+
26
+ class WindowsAdapter:
27
+ """Windows trust, hosts, and ``netsh`` portproxy adapter."""
28
+
29
+ def __init__(
30
+ self,
31
+ *,
32
+ runner: CommandRunner = default_command_runner,
33
+ hosts_path: Path | None = None,
34
+ elevated: bool = False,
35
+ ) -> None:
36
+ self._runner = runner
37
+ self._hosts_path = hosts_path or _default_windows_hosts_path()
38
+ self._elevated = elevated
39
+ self.default_tld = ".test" if elevated else ".localhost"
40
+
41
+ def _certutil_scope(self) -> tuple[str, ...]:
42
+ return () if self._elevated else ("-user",)
43
+
44
+ def is_ca_trusted(self, cert_path: str | None = None) -> bool:
45
+ del cert_path
46
+ res = self._runner(
47
+ ("certutil", *self._certutil_scope(), "-verifystore", "Root", ROOT_CA_CN),
48
+ None,
49
+ )
50
+ return res.returncode == 0 and ROOT_CA_CN in (res.stdout or "")
51
+
52
+ def trust_ca(self, cert_path: str) -> None:
53
+ run_checked(
54
+ self._runner,
55
+ ("certutil", *self._certutil_scope(), "-addstore", "Root", cert_path),
56
+ error_prefix="Failed to trust DevDoor Root CA via certutil",
57
+ )
58
+
59
+ def untrust_ca(self, cert_path: str) -> None:
60
+ del cert_path
61
+ self._runner(
62
+ ("certutil", *self._certutil_scope(), "-delstore", "Root", ROOT_CA_CN),
63
+ None,
64
+ )
65
+
66
+ def add_host(self, hostname: str) -> None:
67
+ if not self._elevated:
68
+ return
69
+ mutate_hosts_file(
70
+ self._hosts_path,
71
+ lambda text: render_hosts_with_added(text, hostname),
72
+ runner=self._runner,
73
+ use_sudo=False,
74
+ )
75
+
76
+ def remove_host(self, hostname: str) -> None:
77
+ if not self._elevated:
78
+ return
79
+ mutate_hosts_file(
80
+ self._hosts_path,
81
+ lambda text: render_hosts_without_host(text, hostname),
82
+ runner=self._runner,
83
+ use_sudo=False,
84
+ )
85
+
86
+ def remove_all_hosts(self) -> None:
87
+ if not self._elevated:
88
+ return
89
+ mutate_hosts_file(
90
+ self._hosts_path,
91
+ render_hosts_without_all_devdoor,
92
+ runner=self._runner,
93
+ use_sudo=False,
94
+ )
95
+
96
+ def list_hosts(self) -> tuple[str, ...]:
97
+ if not self._elevated or not self._hosts_path.is_file():
98
+ return ()
99
+ return list_managed_hosts(self._hosts_path.read_text(encoding="utf-8"))
100
+
101
+ def enable_port_forwarding(self, http_port: int, https_port: int) -> None:
102
+ if not self._elevated:
103
+ return
104
+ for src_port, dst_port in ((80, http_port), (443, https_port)):
105
+ run_checked(
106
+ self._runner,
107
+ (
108
+ "netsh",
109
+ "interface",
110
+ "portproxy",
111
+ "add",
112
+ "v4tov4",
113
+ "listenaddress=127.0.0.1",
114
+ f"listenport={src_port}",
115
+ "connectaddress=127.0.0.1",
116
+ f"connectport={dst_port}",
117
+ ),
118
+ error_prefix="Failed to add netsh portproxy rule",
119
+ )
120
+
121
+ def disable_port_forwarding(self) -> None:
122
+ if not self._elevated:
123
+ return
124
+ for src_port in (80, 443):
125
+ self._runner(
126
+ (
127
+ "netsh",
128
+ "interface",
129
+ "portproxy",
130
+ "delete",
131
+ "v4tov4",
132
+ "listenaddress=127.0.0.1",
133
+ f"listenport={src_port}",
134
+ ),
135
+ None,
136
+ )
137
+
138
+ def is_port_forwarding_active(self) -> bool:
139
+ if not self._elevated:
140
+ return False
141
+ res = self._runner(("netsh", "interface", "portproxy", "show", "v4tov4"), None)
142
+ out = res.stdout or ""
143
+ return res.returncode == 0 and "127.0.0.1" in out and "443" in out
@@ -0,0 +1,7 @@
1
+ """Proxy runtime components (streaming forwarder and TLS termination)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from devdoor.proxy.forwarder import Forwarder, wait_for_upstream
6
+
7
+ __all__ = ["Forwarder", "wait_for_upstream"]
devdoor/proxy/certs.py ADDED
@@ -0,0 +1,311 @@
1
+ """Local ECDSA P-256 Root CA and dynamic SNI leaf certificate manager."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import datetime
6
+ import ipaddress
7
+ import ssl
8
+ from collections.abc import Callable, Iterable
9
+ from dataclasses import dataclass
10
+ from pathlib import Path
11
+
12
+ from cryptography import x509
13
+ from cryptography.hazmat.primitives import hashes, serialization
14
+ from cryptography.hazmat.primitives.asymmetric import ec
15
+ from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID
16
+
17
+ from devdoor.core.config import DevDoorPaths, atomic_write_text, resolve_paths
18
+ from devdoor.core.router import normalize_host
19
+
20
+ ROOT_CA_VALIDITY_DAYS = 3650
21
+ LEAF_VALIDITY_DAYS = 365
22
+ RENEWAL_WINDOW_DAYS = 30
23
+ ROOT_CA_CN = "DevDoor Root CA"
24
+
25
+
26
+ @dataclass(frozen=True, slots=True)
27
+ class CertMetadata:
28
+ """Parsed X.509 summary used by diagnostics (``devdoor doctor``)."""
29
+
30
+ path: Path
31
+ common_name: str
32
+ dns_names: tuple[str, ...]
33
+ ip_addresses: tuple[str, ...]
34
+ not_valid_after_utc: datetime.datetime
35
+ remaining_days: float
36
+ is_ca: bool
37
+
38
+
39
+ def read_cert_metadata(cert_path: Path) -> CertMetadata:
40
+ """Load an X.509 PEM certificate and extract SANs, CN, and remaining lifetime."""
41
+ cert = x509.load_pem_x509_certificate(cert_path.read_bytes())
42
+ cn_attrs = cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME)
43
+ common_name = str(cn_attrs[0].value) if cn_attrs else ""
44
+
45
+ dns_names: tuple[str, ...] = ()
46
+ ip_addrs: tuple[str, ...] = ()
47
+ try:
48
+ san = cert.extensions.get_extension_for_class(x509.SubjectAlternativeName).value
49
+ dns_names = tuple(san.get_values_for_type(x509.DNSName))
50
+ ip_addrs = tuple(str(addr) for addr in san.get_values_for_type(x509.IPAddress))
51
+ except x509.ExtensionNotFound:
52
+ pass
53
+
54
+ is_ca = False
55
+ try:
56
+ bc = cert.extensions.get_extension_for_class(x509.BasicConstraints).value
57
+ is_ca = bc.ca
58
+ except x509.ExtensionNotFound:
59
+ pass
60
+
61
+ remaining = (cert.not_valid_after_utc - datetime.datetime.now(datetime.UTC)).total_seconds()
62
+ return CertMetadata(
63
+ path=cert_path,
64
+ common_name=common_name,
65
+ dns_names=dns_names,
66
+ ip_addresses=ip_addrs,
67
+ not_valid_after_utc=cert.not_valid_after_utc,
68
+ remaining_days=remaining / 86400.0,
69
+ is_ca=is_ca,
70
+ )
71
+
72
+
73
+ def _private_key_pem(key: ec.EllipticCurvePrivateKey) -> str:
74
+ return key.private_bytes(
75
+ encoding=serialization.Encoding.PEM,
76
+ format=serialization.PrivateFormat.PKCS8,
77
+ encryption_algorithm=serialization.NoEncryption(),
78
+ ).decode("utf-8")
79
+
80
+
81
+ def _cert_pem(cert: x509.Certificate) -> str:
82
+ return cert.public_bytes(serialization.Encoding.PEM).decode("utf-8")
83
+
84
+
85
+ def _leaf_filename_stem(hostname: str) -> str:
86
+ cleaned = hostname.strip().lower().replace(":", "_")
87
+ return "".join(ch if (ch.isalnum() or ch in {".", "-", "_"}) else "_" for ch in cleaned)
88
+
89
+
90
+ class CertManager:
91
+ """Manages ``~/.devdoor/ca`` Root CA, leaf SAN certificates, and cached SSL contexts."""
92
+
93
+ def __init__(self, *, paths: DevDoorPaths | None = None) -> None:
94
+ self._paths = paths or resolve_paths()
95
+ self._contexts: dict[str, ssl.SSLContext] = {}
96
+
97
+ @property
98
+ def root_ca_cert_path(self) -> Path:
99
+ return self._paths.ca_dir / "rootCA.pem"
100
+
101
+ @property
102
+ def root_ca_key_path(self) -> Path:
103
+ return self._paths.ca_dir / "rootCA-key.pem"
104
+
105
+ @property
106
+ def leaves_dir(self) -> Path:
107
+ return self._paths.ca_dir / "leaves"
108
+
109
+ def leaf_cert_path(self, hostname: str) -> Path:
110
+ host = normalize_host(hostname)
111
+ return self.leaves_dir / f"{_leaf_filename_stem(host)}.pem"
112
+
113
+ def leaf_key_path(self, hostname: str) -> Path:
114
+ host = normalize_host(hostname)
115
+ return self.leaves_dir / f"{_leaf_filename_stem(host)}-key.pem"
116
+
117
+ def ensure_root_ca(self, *, force: bool = False) -> tuple[Path, Path]:
118
+ """Load an existing valid Root CA or mint a fresh 10-year ECDSA P-256 CA."""
119
+ cert_path = self.root_ca_cert_path
120
+ key_path = self.root_ca_key_path
121
+ if not force and cert_path.is_file() and key_path.is_file():
122
+ try:
123
+ existing = x509.load_pem_x509_certificate(cert_path.read_bytes())
124
+ serialization.load_pem_private_key(key_path.read_bytes(), password=None)
125
+ if existing.not_valid_after_utc > datetime.datetime.now(datetime.UTC):
126
+ return cert_path, key_path
127
+ except ValueError, OSError:
128
+ pass
129
+
130
+ key = ec.generate_private_key(ec.SECP256R1())
131
+ now = datetime.datetime.now(datetime.UTC)
132
+ subject = issuer = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, ROOT_CA_CN)])
133
+ ski = x509.SubjectKeyIdentifier.from_public_key(key.public_key())
134
+ cert = (
135
+ x509.CertificateBuilder()
136
+ .subject_name(subject)
137
+ .issuer_name(issuer)
138
+ .public_key(key.public_key())
139
+ .serial_number(x509.random_serial_number())
140
+ .not_valid_before(now - datetime.timedelta(minutes=5))
141
+ .not_valid_after(now + datetime.timedelta(days=ROOT_CA_VALIDITY_DAYS))
142
+ .add_extension(x509.BasicConstraints(ca=True, path_length=0), critical=True)
143
+ .add_extension(
144
+ x509.KeyUsage(
145
+ digital_signature=True,
146
+ content_commitment=False,
147
+ key_encipherment=False,
148
+ data_encipherment=False,
149
+ key_agreement=False,
150
+ key_cert_sign=True,
151
+ crl_sign=True,
152
+ encipher_only=False,
153
+ decipher_only=False,
154
+ ),
155
+ critical=True,
156
+ )
157
+ .add_extension(ski, critical=False)
158
+ .add_extension(
159
+ x509.AuthorityKeyIdentifier.from_issuer_subject_key_identifier(ski),
160
+ critical=False,
161
+ )
162
+ .sign(private_key=key, algorithm=hashes.SHA256())
163
+ )
164
+
165
+ atomic_write_text(key_path, _private_key_pem(key), mode=0o600)
166
+ atomic_write_text(cert_path, _cert_pem(cert), mode=0o644)
167
+ self._contexts.clear()
168
+ return cert_path, key_path
169
+
170
+ def _load_ca(self) -> tuple[x509.Certificate, ec.EllipticCurvePrivateKey]:
171
+ cert_path, key_path = self.ensure_root_ca()
172
+ cert = x509.load_pem_x509_certificate(cert_path.read_bytes())
173
+ key = serialization.load_pem_private_key(key_path.read_bytes(), password=None)
174
+ if not isinstance(key, ec.EllipticCurvePrivateKey):
175
+ raise TypeError("DevDoor Root CA key must use ECDSA.")
176
+ return cert, key
177
+
178
+ def _is_leaf_reusable(
179
+ self,
180
+ cert_path: Path,
181
+ key_path: Path,
182
+ *,
183
+ host: str,
184
+ ca_cert: x509.Certificate,
185
+ ) -> bool:
186
+ if not cert_path.is_file() or not key_path.is_file():
187
+ return False
188
+ try:
189
+ leaf = x509.load_pem_x509_certificate(cert_path.read_bytes())
190
+ serialization.load_pem_private_key(key_path.read_bytes(), password=None)
191
+ if leaf.issuer != ca_cert.subject:
192
+ return False
193
+ remaining = leaf.not_valid_after_utc - datetime.datetime.now(datetime.UTC)
194
+ if remaining < datetime.timedelta(days=RENEWAL_WINDOW_DAYS):
195
+ return False
196
+ san = leaf.extensions.get_extension_for_class(x509.SubjectAlternativeName).value
197
+ dns = set(san.get_values_for_type(x509.DNSName))
198
+ ips = set(san.get_values_for_type(x509.IPAddress))
199
+ return (
200
+ host in dns
201
+ and ipaddress.IPv4Address("127.0.0.1") in ips
202
+ and ipaddress.IPv6Address("::1") in ips
203
+ )
204
+ except ValueError, x509.ExtensionNotFound, OSError:
205
+ return False
206
+
207
+ def ensure_leaf_cert(self, hostname: str, *, force: bool = False) -> tuple[Path, Path]:
208
+ """Return valid ``(cert_path, key_path)`` for ``hostname``, auto-renewing <30d expiry."""
209
+ host = normalize_host(hostname)
210
+ if not host:
211
+ raise ValueError(f"Invalid hostname for leaf certificate: {hostname!r}")
212
+
213
+ ca_cert, ca_key = self._load_ca()
214
+ cert_path = self.leaf_cert_path(host)
215
+ key_path = self.leaf_key_path(host)
216
+ if not force and self._is_leaf_reusable(cert_path, key_path, host=host, ca_cert=ca_cert):
217
+ return cert_path, key_path
218
+
219
+ key = ec.generate_private_key(ec.SECP256R1())
220
+ now = datetime.datetime.now(datetime.UTC)
221
+ san = x509.SubjectAlternativeName(
222
+ [
223
+ x509.DNSName(host),
224
+ x509.IPAddress(ipaddress.IPv4Address("127.0.0.1")),
225
+ x509.IPAddress(ipaddress.IPv6Address("::1")),
226
+ ]
227
+ )
228
+ ca_ski = ca_cert.extensions.get_extension_for_class(x509.SubjectKeyIdentifier).value
229
+ cert = (
230
+ x509.CertificateBuilder()
231
+ .subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, host)]))
232
+ .issuer_name(ca_cert.subject)
233
+ .public_key(key.public_key())
234
+ .serial_number(x509.random_serial_number())
235
+ .not_valid_before(now - datetime.timedelta(minutes=5))
236
+ .not_valid_after(now + datetime.timedelta(days=LEAF_VALIDITY_DAYS))
237
+ .add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True)
238
+ .add_extension(
239
+ x509.KeyUsage(
240
+ digital_signature=True,
241
+ content_commitment=False,
242
+ key_encipherment=True,
243
+ data_encipherment=False,
244
+ key_agreement=False,
245
+ key_cert_sign=False,
246
+ crl_sign=False,
247
+ encipher_only=False,
248
+ decipher_only=False,
249
+ ),
250
+ critical=True,
251
+ )
252
+ .add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH]), critical=False)
253
+ .add_extension(san, critical=False)
254
+ .add_extension(
255
+ x509.SubjectKeyIdentifier.from_public_key(key.public_key()),
256
+ critical=False,
257
+ )
258
+ .add_extension(
259
+ x509.AuthorityKeyIdentifier.from_issuer_subject_key_identifier(ca_ski),
260
+ critical=False,
261
+ )
262
+ .sign(private_key=ca_key, algorithm=hashes.SHA256())
263
+ )
264
+
265
+ atomic_write_text(key_path, _private_key_pem(key), mode=0o600)
266
+ atomic_write_text(cert_path, _cert_pem(cert), mode=0o644)
267
+ self._contexts.pop(host, None)
268
+ return cert_path, key_path
269
+
270
+ def sync_domains(self, domains: Iterable[str]) -> None:
271
+ """Pre-mint leaf certs and warm SSL contexts for all configured ``domains``."""
272
+ self.ensure_root_ca()
273
+ for domain in domains:
274
+ self.get_ssl_context_for_host(domain)
275
+
276
+ def get_ssl_context_for_host(self, hostname: str) -> ssl.SSLContext:
277
+ """Return a cached TLS server ``SSLContext`` for ``hostname``."""
278
+ host = normalize_host(hostname)
279
+ cached = self._contexts.get(host)
280
+ if cached is not None:
281
+ return cached
282
+
283
+ cert_path, key_path = self.ensure_leaf_cert(host)
284
+ ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
285
+ ctx.minimum_version = ssl.TLSVersion.TLSv1_2
286
+ ctx.load_cert_chain(certfile=str(cert_path), keyfile=str(key_path))
287
+ ctx.set_alpn_protocols(["http/1.1"])
288
+ self._contexts[host] = ctx
289
+ return ctx
290
+
291
+ def build_base_ssl_context(self, is_allowed_host: Callable[[str], bool]) -> ssl.SSLContext:
292
+ """Build the primary TLS listener ``SSLContext`` wired with SNI selection."""
293
+ fallback_cert, fallback_key = self.ensure_leaf_cert("localhost")
294
+ base = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
295
+ base.minimum_version = ssl.TLSVersion.TLSv1_2
296
+ base.load_cert_chain(certfile=str(fallback_cert), keyfile=str(fallback_key))
297
+ base.set_alpn_protocols(["http/1.1"])
298
+
299
+ def _on_sni(
300
+ ssl_sock: ssl.SSLObject,
301
+ server_name: str,
302
+ _orig_ctx: ssl.SSLContext,
303
+ ) -> int | None:
304
+ host = normalize_host(server_name)
305
+ if not host or not is_allowed_host(host):
306
+ return ssl.ALERT_DESCRIPTION_UNRECOGNIZED_NAME
307
+ ssl_sock.context = self.get_ssl_context_for_host(host)
308
+ return None
309
+
310
+ base.sni_callback = _on_sni
311
+ return base