django-hostmap 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.
- django_hostmap-0.1.0.dist-info/METADATA +163 -0
- django_hostmap-0.1.0.dist-info/RECORD +20 -0
- django_hostmap-0.1.0.dist-info/WHEEL +5 -0
- django_hostmap-0.1.0.dist-info/licenses/LICENSE +21 -0
- django_hostmap-0.1.0.dist-info/top_level.txt +1 -0
- hostmap/__init__.py +4 -0
- hostmap/apps.py +61 -0
- hostmap/checks.py +252 -0
- hostmap/conf.py +60 -0
- hostmap/context.py +68 -0
- hostmap/management/__init__.py +0 -0
- hostmap/management/commands/__init__.py +0 -0
- hostmap/management/commands/hostmap.py +31 -0
- hostmap/map.py +194 -0
- hostmap/middleware.py +79 -0
- hostmap/resolvers.py +159 -0
- hostmap/testing/__init__.py +10 -0
- hostmap/testing/fixtures.py +18 -0
- hostmap/testing/helpers.py +33 -0
- hostmap/urls.py +196 -0
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: django-hostmap
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Host-based URL routing and host-aware reversing for Django, with zero call-site changes
|
|
5
|
+
Author-email: ICV <dev@icv.dev>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/icvoss/django-hostmap
|
|
8
|
+
Project-URL: Source Code, https://github.com/icvoss/django-hostmap
|
|
9
|
+
Project-URL: Changelog, https://github.com/icvoss/django-hostmap/blob/main/CHANGELOG.md
|
|
10
|
+
Project-URL: Issue Tracker, https://github.com/icvoss/django-hostmap/issues
|
|
11
|
+
Project-URL: Documentation, https://github.com/icvoss/django-hostmap/tree/main/docs
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Framework :: Django
|
|
14
|
+
Classifier: Framework :: Django :: 5.2
|
|
15
|
+
Classifier: Framework :: Django :: 6.0
|
|
16
|
+
Classifier: Intended Audience :: Developers
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
20
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
21
|
+
Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
|
|
22
|
+
Requires-Python: >=3.12
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
License-File: LICENSE
|
|
25
|
+
Requires-Dist: Django>=5.2
|
|
26
|
+
Provides-Extra: dev
|
|
27
|
+
Requires-Dist: pytest>=8.0; extra == "dev"
|
|
28
|
+
Requires-Dist: pytest-django>=4.8; extra == "dev"
|
|
29
|
+
Requires-Dist: pytest-cov>=5.0; extra == "dev"
|
|
30
|
+
Requires-Dist: ruff>=0.5.0; extra == "dev"
|
|
31
|
+
Requires-Dist: mypy>=1.10; extra == "dev"
|
|
32
|
+
Requires-Dist: django-stubs>=5.0; extra == "dev"
|
|
33
|
+
Dynamic: license-file
|
|
34
|
+
|
|
35
|
+
# django-hostmap
|
|
36
|
+
|
|
37
|
+
Host-based URL routing and host-aware reversing for Django, with zero
|
|
38
|
+
call-site changes.
|
|
39
|
+
|
|
40
|
+
`django-hostmap` routes requests to different URLconfs by host (subdomain or
|
|
41
|
+
full domain) and makes URL reversing host-aware without changing a single
|
|
42
|
+
call site: the stock `reverse()`, `reverse_lazy()` and `{% url %}` keep
|
|
43
|
+
working everywhere, including inside third-party apps. Links within the
|
|
44
|
+
current host stay path-relative, exactly as Django produces them; links to
|
|
45
|
+
views on another host come back as absolute URLs. Configuration is one
|
|
46
|
+
declarative host map in settings plus one middleware.
|
|
47
|
+
|
|
48
|
+
It is the ecosystem's replacement for django-hosts, whose parallel reverse
|
|
49
|
+
API forces invasive changes across templates and Python code and cannot fix
|
|
50
|
+
third-party apps that call `django.urls.reverse()`.
|
|
51
|
+
|
|
52
|
+
## Installation
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
pip install django-hostmap
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
INSTALLED_APPS = [
|
|
60
|
+
# ...
|
|
61
|
+
"hostmap",
|
|
62
|
+
]
|
|
63
|
+
|
|
64
|
+
MIDDLEWARE = [
|
|
65
|
+
"django.middleware.security.SecurityMiddleware",
|
|
66
|
+
"hostmap.middleware.HostmapMiddleware", # before CommonMiddleware
|
|
67
|
+
"django.middleware.common.CommonMiddleware",
|
|
68
|
+
# ...
|
|
69
|
+
]
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
`ROOT_URLCONF` remains required (Django needs it at startup) and should point
|
|
73
|
+
at the default entry's URLconf (`hostmap.W003` warns on mismatch).
|
|
74
|
+
|
|
75
|
+
## The host map
|
|
76
|
+
|
|
77
|
+
```python
|
|
78
|
+
HOSTMAP = {
|
|
79
|
+
"www": {"subdomain": "www", "urlconf": "config.urls.www"},
|
|
80
|
+
"api": {"subdomain": "api", "urlconf": "config.urls.api"},
|
|
81
|
+
"apex": {"host": "example.com", "redirect_to": "www"},
|
|
82
|
+
}
|
|
83
|
+
HOSTMAP_PARENT_DOMAIN = "example.com"
|
|
84
|
+
HOSTMAP_DEFAULT = "www"
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
With `www` active:
|
|
88
|
+
|
|
89
|
+
| Call | Returns |
|
|
90
|
+
|------|---------|
|
|
91
|
+
| `reverse("blog:index")` | `/blog/` (byte-identical to stock Django) |
|
|
92
|
+
| `reverse("api:user-detail", args=[7])` | `https://api.example.com/users/7/` |
|
|
93
|
+
| `{% url "api:user-detail" 7 %}` | the absolute URL, no template changes |
|
|
94
|
+
|
|
95
|
+
Same-host links stay relative; cross-host links come back absolute. Nothing
|
|
96
|
+
at the call site changes.
|
|
97
|
+
|
|
98
|
+
## Settings
|
|
99
|
+
|
|
100
|
+
| Setting | Default | Description |
|
|
101
|
+
|---------|---------|-------------|
|
|
102
|
+
| `HOSTMAP` | `{}` | The host map. Empty map disables all behaviour |
|
|
103
|
+
| `HOSTMAP_PARENT_DOMAIN` | `""` | Domain joined to `subdomain` entries |
|
|
104
|
+
| `HOSTMAP_DEFAULT` | `""` | Entry for unmatched hosts and out-of-request reversing |
|
|
105
|
+
| `HOSTMAP_PATCH_REVERSE` | `True` | Make stock `reverse()` / `{% url %}` host-aware |
|
|
106
|
+
| `HOSTMAP_SCHEME` | `"https"` | Scheme for cross-host absolute URLs |
|
|
107
|
+
| `HOSTMAP_PORT` | `""` | Port appended to all generated hosts |
|
|
108
|
+
| `HOSTMAP_UNMATCHED` | `"default"` | `"default"` routes unmatched hosts to the default entry; `"reject"` returns 404 |
|
|
109
|
+
| `HOSTMAP_REDIRECT_PERMANENT` | `True` | `redirect_to` entries use 301, else 302 |
|
|
110
|
+
|
|
111
|
+
## Explicit API
|
|
112
|
+
|
|
113
|
+
For code that needs an absolute URL regardless of the active host (emails,
|
|
114
|
+
Celery tasks, API payloads, webhooks):
|
|
115
|
+
|
|
116
|
+
```python
|
|
117
|
+
from hostmap.urls import reverse, build_absolute_uri, use_host
|
|
118
|
+
|
|
119
|
+
build_absolute_uri("api:user-detail", args=[7]) # always absolute
|
|
120
|
+
with use_host("api"):
|
|
121
|
+
reverse("user-detail", args=[7]) # api active
|
|
122
|
+
|
|
123
|
+
with use_host(host="acme.example.com"): # a wildcard host
|
|
124
|
+
reverse("dashboard")
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
## Development story
|
|
128
|
+
|
|
129
|
+
Modern browsers resolve `*.localhost` to loopback (RFC 6761), so the whole
|
|
130
|
+
map works locally with no `/etc/hosts` edits:
|
|
131
|
+
|
|
132
|
+
```python
|
|
133
|
+
HOSTMAP_PARENT_DOMAIN = "localhost"
|
|
134
|
+
HOSTMAP_SCHEME = "http"
|
|
135
|
+
HOSTMAP_PORT = "8000"
|
|
136
|
+
ALLOWED_HOSTS = [".localhost"]
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
## Behind a proxy
|
|
140
|
+
|
|
141
|
+
Host routing is only as good as the Host header that reaches Django. Behind a
|
|
142
|
+
reverse proxy, either the proxy passes Host through unchanged or the
|
|
143
|
+
deployment sets `USE_X_FORWARDED_HOST = True` with the proxy sending
|
|
144
|
+
`X-Forwarded-Host`. Misrouted hosts behind nginx are otherwise the first
|
|
145
|
+
support issue.
|
|
146
|
+
|
|
147
|
+
## Escape hatch
|
|
148
|
+
|
|
149
|
+
`HOSTMAP_PATCH_REVERSE = False` degrades cleanly to routing-only: the stock
|
|
150
|
+
`reverse()` is left untouched (cross-host links regress to paths), routing
|
|
151
|
+
keeps working, and the explicit API still works. Set it if a Django upgrade
|
|
152
|
+
lands before a compatible django-hostmap release; the startup self-test and
|
|
153
|
+
`hostmap.W004` warn before anything breaks.
|
|
154
|
+
|
|
155
|
+
## Diagnostics
|
|
156
|
+
|
|
157
|
+
```bash
|
|
158
|
+
manage.py hostmap # print the resolved map for the current settings
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
## Licence
|
|
162
|
+
|
|
163
|
+
MIT. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
django_hostmap-0.1.0.dist-info/licenses/LICENSE,sha256=3QR46NHASjF4t0msVNTgSXS2ofNYvpFcS6lrBoI9y2Y,1060
|
|
2
|
+
hostmap/__init__.py,sha256=E32VTzupqXON5wCA2t6rnFZ5isAhL4IPQKRyKp6pGIA,158
|
|
3
|
+
hostmap/apps.py,sha256=NRDA_pJ8jYaS2O6XE4ontV7DKyicvb3iwhr2bPlvbxg,2298
|
|
4
|
+
hostmap/checks.py,sha256=UA00NIi5mbF-la3vTLU6Btp8CTxHwdEAKGfGcMfPFEU,8304
|
|
5
|
+
hostmap/conf.py,sha256=vR2lF1Li_HKL2ZzuVgZ-kPVQOK_p49uuREjtRRkipmk,1993
|
|
6
|
+
hostmap/context.py,sha256=BPPXp4T6kZNrDs5cFtNVMZmnB0vEohmydMuZGKstPbA,2591
|
|
7
|
+
hostmap/map.py,sha256=mLLbkFrFa2y2fcdjKJr1BkeSKTBbZBtvZ6_8nmp8Thk,6933
|
|
8
|
+
hostmap/middleware.py,sha256=J6JF-2PqGQH2I3COrYD5LE4lH1n8c5ucp3jJIClRmtw,2740
|
|
9
|
+
hostmap/resolvers.py,sha256=co2s3E4XDtzvd1E9oCNvlLXF86h6p9VSX4VMRZBsRzg,6307
|
|
10
|
+
hostmap/urls.py,sha256=sohM1OwCizY3_UTPyD1HzNlos9Qrk7oPhK78dj-mprI,7523
|
|
11
|
+
hostmap/management/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
12
|
+
hostmap/management/commands/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
13
|
+
hostmap/management/commands/hostmap.py,sha256=Zs8rwZNj10wm_qBh_zSKdlyAu3TEAXCoI5HBomAsMtY,1338
|
|
14
|
+
hostmap/testing/__init__.py,sha256=zMDTif_OHC8vo54QqsGCCo75FDxJiSsT0q4i__Cc4io,353
|
|
15
|
+
hostmap/testing/fixtures.py,sha256=c7Dsw8YKRe9IYWwN_JRDX4CF7-sdlP8xDCuN8l3Mff0,437
|
|
16
|
+
hostmap/testing/helpers.py,sha256=SglqUevvGP2IR5rzCwJWsDlvenwgfFoOrqcltljNEfs,1193
|
|
17
|
+
django_hostmap-0.1.0.dist-info/METADATA,sha256=RqOqjcWrDby95AQxCNpxhHVKZ3Bii9u5YPeyeDi3Ssk,5773
|
|
18
|
+
django_hostmap-0.1.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
|
|
19
|
+
django_hostmap-0.1.0.dist-info/top_level.txt,sha256=glZGfu6nMyJGUAMC17i29GhGH5RiNHNZ9x-rZNU5ktg,8
|
|
20
|
+
django_hostmap-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 ICV
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
hostmap
|
hostmap/__init__.py
ADDED
hostmap/apps.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Hostmap Django app configuration.
|
|
2
|
+
|
|
3
|
+
Installs the resolver seam at ``ready()`` and runs a self-test that fails
|
|
4
|
+
loudly (``ImproperlyConfigured``) if the seam misbehaves on the running
|
|
5
|
+
Django, naming the remediation (03-services.md, seam guards; BR-HOSTMAP-007).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from django.apps import AppConfig
|
|
11
|
+
from django.core.exceptions import ImproperlyConfigured
|
|
12
|
+
|
|
13
|
+
# The highest Django feature version this release has been tested against.
|
|
14
|
+
# ``hostmap.W004`` warns when the running Django exceeds it (04-interfaces.md).
|
|
15
|
+
TESTED_DJANGO_CEILING = (6, 0)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class HostmapConfig(AppConfig):
|
|
19
|
+
name = "hostmap"
|
|
20
|
+
label = "hostmap"
|
|
21
|
+
verbose_name = "Hostmap"
|
|
22
|
+
default_auto_field = "django.db.models.BigAutoField"
|
|
23
|
+
|
|
24
|
+
def ready(self):
|
|
25
|
+
from hostmap import checks # noqa: F401 registers system checks
|
|
26
|
+
from hostmap.conf import hostmap_settings
|
|
27
|
+
|
|
28
|
+
if not hostmap_settings.PATCH_REVERSE:
|
|
29
|
+
return
|
|
30
|
+
if not hostmap_settings.MAP:
|
|
31
|
+
return
|
|
32
|
+
|
|
33
|
+
from hostmap import resolvers
|
|
34
|
+
|
|
35
|
+
resolvers.install()
|
|
36
|
+
self._seam_self_test()
|
|
37
|
+
|
|
38
|
+
def _seam_self_test(self):
|
|
39
|
+
"""Reverse a probe through the host-aware resolver to prove the seam works.
|
|
40
|
+
|
|
41
|
+
A ``TypeError``/``AttributeError`` here means the ``get_resolver`` /
|
|
42
|
+
``_reverse_with_prefix`` seam has moved under us; fail startup with the
|
|
43
|
+
remediation rather than let production traffic hit it.
|
|
44
|
+
"""
|
|
45
|
+
from django.urls import NoReverseMatch
|
|
46
|
+
from django.urls.resolvers import get_resolver
|
|
47
|
+
|
|
48
|
+
try:
|
|
49
|
+
resolver = get_resolver()
|
|
50
|
+
# A probe name that will not resolve: we only assert the seam's
|
|
51
|
+
# method signature holds, not that any URL exists.
|
|
52
|
+
try:
|
|
53
|
+
resolver._reverse_with_prefix("__hostmap_seam_probe__", "/")
|
|
54
|
+
except NoReverseMatch:
|
|
55
|
+
pass
|
|
56
|
+
except (TypeError, AttributeError) as exc: # pragma: no cover - defensive
|
|
57
|
+
raise ImproperlyConfigured(
|
|
58
|
+
"django-hostmap could not drive Django's URL reverse seam on this "
|
|
59
|
+
f"Django version ({exc}). Set HOSTMAP_PATCH_REVERSE = False to run "
|
|
60
|
+
"routing-only until a compatible django-hostmap release ships."
|
|
61
|
+
) from exc
|
hostmap/checks.py
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
"""Django system checks for hostmap configuration (04-interfaces.md section 3).
|
|
2
|
+
|
|
3
|
+
Registered in ``AppConfig.ready()`` and run at startup and during test
|
|
4
|
+
collection. Errors (E001-E008) fail startup; warnings (W001-W004) surface
|
|
5
|
+
misconfigurations that still boot.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from django.core.checks import Error, Tags, Warning, register
|
|
11
|
+
|
|
12
|
+
_KNOWN_KEYS = frozenset({"host", "subdomain", "urlconf", "redirect_to"})
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@register(Tags.urls)
|
|
16
|
+
def check_hostmap(app_configs, **kwargs):
|
|
17
|
+
from hostmap.conf import hostmap_settings
|
|
18
|
+
|
|
19
|
+
hostmap = hostmap_settings.MAP
|
|
20
|
+
if not hostmap:
|
|
21
|
+
return [] # empty map disables all behaviour; nothing to validate
|
|
22
|
+
|
|
23
|
+
problems = []
|
|
24
|
+
problems.extend(_check_entries(hostmap))
|
|
25
|
+
problems.extend(_check_default(hostmap))
|
|
26
|
+
problems.extend(_check_duplicate_hosts())
|
|
27
|
+
problems.extend(_check_allowed_hosts())
|
|
28
|
+
problems.extend(_check_middleware())
|
|
29
|
+
problems.extend(_check_root_urlconf())
|
|
30
|
+
problems.extend(_check_django_ceiling())
|
|
31
|
+
return problems
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _check_entries(hostmap):
|
|
35
|
+
from django.conf import settings
|
|
36
|
+
|
|
37
|
+
problems = []
|
|
38
|
+
parent_domain = getattr(settings, "HOSTMAP_PARENT_DOMAIN", "")
|
|
39
|
+
labels = set(hostmap.keys())
|
|
40
|
+
|
|
41
|
+
for label, entry in hostmap.items():
|
|
42
|
+
# E001: malformed entry (not a dict, unknown keys).
|
|
43
|
+
if not isinstance(entry, dict):
|
|
44
|
+
problems.append(Error(f"HOSTMAP entry '{label}' is not a dict.", id="hostmap.E001"))
|
|
45
|
+
continue
|
|
46
|
+
unknown = set(entry) - _KNOWN_KEYS
|
|
47
|
+
if unknown or not entry:
|
|
48
|
+
problems.append(
|
|
49
|
+
Error(
|
|
50
|
+
f"HOSTMAP entry '{label}' is empty or has unknown keys: {sorted(unknown)}.",
|
|
51
|
+
hint=f"Valid keys: {sorted(_KNOWN_KEYS)}.",
|
|
52
|
+
id="hostmap.E001",
|
|
53
|
+
)
|
|
54
|
+
)
|
|
55
|
+
continue
|
|
56
|
+
|
|
57
|
+
has_host = "host" in entry
|
|
58
|
+
has_subdomain = "subdomain" in entry
|
|
59
|
+
# E002: exactly one of host / subdomain.
|
|
60
|
+
if has_host == has_subdomain:
|
|
61
|
+
problems.append(
|
|
62
|
+
Error(
|
|
63
|
+
f"HOSTMAP entry '{label}' must set exactly one of 'host' or 'subdomain'.",
|
|
64
|
+
id="hostmap.E002",
|
|
65
|
+
)
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
has_urlconf = "urlconf" in entry
|
|
69
|
+
has_redirect = "redirect_to" in entry
|
|
70
|
+
# E003: exactly one of urlconf / redirect_to.
|
|
71
|
+
if has_urlconf == has_redirect:
|
|
72
|
+
problems.append(
|
|
73
|
+
Error(
|
|
74
|
+
f"HOSTMAP entry '{label}' must set exactly one of 'urlconf' or 'redirect_to'.",
|
|
75
|
+
id="hostmap.E003",
|
|
76
|
+
)
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
# E004: redirect_to must name a known, non-redirect label (no chains).
|
|
80
|
+
if has_redirect:
|
|
81
|
+
target = entry["redirect_to"]
|
|
82
|
+
if target not in labels:
|
|
83
|
+
problems.append(
|
|
84
|
+
Error(
|
|
85
|
+
f"HOSTMAP entry '{label}' redirects to unknown label '{target}'.",
|
|
86
|
+
id="hostmap.E004",
|
|
87
|
+
)
|
|
88
|
+
)
|
|
89
|
+
elif isinstance(hostmap.get(target), dict) and "redirect_to" in hostmap[target]:
|
|
90
|
+
problems.append(
|
|
91
|
+
Error(
|
|
92
|
+
f"HOSTMAP entry '{label}' redirects to another redirect entry '{target}' (no chains).",
|
|
93
|
+
id="hostmap.E004",
|
|
94
|
+
)
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
# E006: unimportable URLconf.
|
|
98
|
+
if has_urlconf:
|
|
99
|
+
problems.extend(_check_urlconf_importable(label, entry["urlconf"]))
|
|
100
|
+
|
|
101
|
+
# E008: subdomain entry without HOSTMAP_PARENT_DOMAIN.
|
|
102
|
+
if has_subdomain and not parent_domain:
|
|
103
|
+
problems.append(
|
|
104
|
+
Error(
|
|
105
|
+
f"HOSTMAP entry '{label}' uses 'subdomain' but HOSTMAP_PARENT_DOMAIN is not set.",
|
|
106
|
+
id="hostmap.E008",
|
|
107
|
+
)
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
return problems
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _check_urlconf_importable(label, urlconf):
|
|
114
|
+
from importlib import import_module
|
|
115
|
+
|
|
116
|
+
try:
|
|
117
|
+
import_module(urlconf)
|
|
118
|
+
except Exception as exc: # noqa: BLE001 - report any import failure
|
|
119
|
+
return [
|
|
120
|
+
Error(
|
|
121
|
+
f"HOSTMAP entry '{label}' URLconf '{urlconf}' is not importable: {exc}.",
|
|
122
|
+
id="hostmap.E006",
|
|
123
|
+
)
|
|
124
|
+
]
|
|
125
|
+
return []
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _check_default(hostmap):
|
|
129
|
+
# E005: HOSTMAP_DEFAULT missing or not a map label while the map is non-empty.
|
|
130
|
+
from django.conf import settings
|
|
131
|
+
|
|
132
|
+
default = getattr(settings, "HOSTMAP_DEFAULT", "")
|
|
133
|
+
if not default or default not in hostmap:
|
|
134
|
+
return [
|
|
135
|
+
Error(
|
|
136
|
+
f"HOSTMAP_DEFAULT ('{default}') is missing or not a HOSTMAP label.",
|
|
137
|
+
hint="Set HOSTMAP_DEFAULT to one of the map's labels.",
|
|
138
|
+
id="hostmap.E005",
|
|
139
|
+
)
|
|
140
|
+
]
|
|
141
|
+
return []
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _check_duplicate_hosts():
|
|
145
|
+
# E007: duplicate effective hosts.
|
|
146
|
+
from hostmap.map import resolved_entries
|
|
147
|
+
|
|
148
|
+
seen = {}
|
|
149
|
+
problems = []
|
|
150
|
+
for entry in resolved_entries().values():
|
|
151
|
+
if entry.host in seen:
|
|
152
|
+
problems.append(
|
|
153
|
+
Error(
|
|
154
|
+
f"HOSTMAP entries '{seen[entry.host]}' and '{entry.label}' resolve to the same host '{entry.host}'.",
|
|
155
|
+
id="hostmap.E007",
|
|
156
|
+
)
|
|
157
|
+
)
|
|
158
|
+
else:
|
|
159
|
+
seen[entry.host] = entry.label
|
|
160
|
+
return problems
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _check_allowed_hosts():
|
|
164
|
+
# W001: mapped host not covered by ALLOWED_HOSTS.
|
|
165
|
+
from django.conf import settings
|
|
166
|
+
|
|
167
|
+
from hostmap.map import resolved_entries
|
|
168
|
+
|
|
169
|
+
allowed = settings.ALLOWED_HOSTS
|
|
170
|
+
if "*" in allowed:
|
|
171
|
+
return []
|
|
172
|
+
|
|
173
|
+
problems = []
|
|
174
|
+
for entry in resolved_entries().values():
|
|
175
|
+
if entry.wildcard:
|
|
176
|
+
continue # wildcard coverage is a leading-dot ALLOWED_HOSTS concern
|
|
177
|
+
if not _host_allowed(entry.host, allowed):
|
|
178
|
+
problems.append(
|
|
179
|
+
Warning(
|
|
180
|
+
f"HOSTMAP host '{entry.host}' (entry '{entry.label}') is not covered by ALLOWED_HOSTS.",
|
|
181
|
+
id="hostmap.W001",
|
|
182
|
+
)
|
|
183
|
+
)
|
|
184
|
+
return problems
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _host_allowed(host, allowed):
|
|
188
|
+
for pattern in allowed:
|
|
189
|
+
if pattern == host:
|
|
190
|
+
return True
|
|
191
|
+
if pattern.startswith(".") and (host == pattern[1:] or host.endswith(pattern)):
|
|
192
|
+
return True
|
|
193
|
+
return False
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _check_middleware():
|
|
197
|
+
# W002: HOSTMAP configured without HostmapMiddleware installed.
|
|
198
|
+
from django.conf import settings
|
|
199
|
+
|
|
200
|
+
middleware = settings.MIDDLEWARE
|
|
201
|
+
if not any(
|
|
202
|
+
m.endswith("hostmap.middleware.HostmapMiddleware") or m == "hostmap.middleware.HostmapMiddleware"
|
|
203
|
+
for m in middleware
|
|
204
|
+
):
|
|
205
|
+
return [
|
|
206
|
+
Warning(
|
|
207
|
+
"HOSTMAP is configured but HostmapMiddleware is not in MIDDLEWARE.",
|
|
208
|
+
hint="Add 'hostmap.middleware.HostmapMiddleware' before CommonMiddleware.",
|
|
209
|
+
id="hostmap.W002",
|
|
210
|
+
)
|
|
211
|
+
]
|
|
212
|
+
return []
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _check_root_urlconf():
|
|
216
|
+
# W003: ROOT_URLCONF does not match the default entry's URLconf.
|
|
217
|
+
from django.conf import settings
|
|
218
|
+
|
|
219
|
+
from hostmap.map import default_entry
|
|
220
|
+
|
|
221
|
+
entry = default_entry()
|
|
222
|
+
if entry is None or entry.is_redirect:
|
|
223
|
+
return []
|
|
224
|
+
root = getattr(settings, "ROOT_URLCONF", None)
|
|
225
|
+
if root != entry.urlconf:
|
|
226
|
+
return [
|
|
227
|
+
Warning(
|
|
228
|
+
f"ROOT_URLCONF ('{root}') does not match the default entry's URLconf ('{entry.urlconf}').",
|
|
229
|
+
hint="Point ROOT_URLCONF at the HOSTMAP_DEFAULT entry's URLconf.",
|
|
230
|
+
id="hostmap.W003",
|
|
231
|
+
)
|
|
232
|
+
]
|
|
233
|
+
return []
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _check_django_ceiling():
|
|
237
|
+
# W004: running Django is newer than the package's tested ceiling.
|
|
238
|
+
import django
|
|
239
|
+
|
|
240
|
+
from hostmap.apps import TESTED_DJANGO_CEILING
|
|
241
|
+
|
|
242
|
+
if django.VERSION[:2] > TESTED_DJANGO_CEILING:
|
|
243
|
+
ceiling = ".".join(str(n) for n in TESTED_DJANGO_CEILING)
|
|
244
|
+
running = ".".join(str(n) for n in django.VERSION[:2])
|
|
245
|
+
return [
|
|
246
|
+
Warning(
|
|
247
|
+
f"Running Django {running} is newer than django-hostmap's tested ceiling ({ceiling}).",
|
|
248
|
+
hint="If reversing misbehaves, set HOSTMAP_PATCH_REVERSE = False until a compatible release ships.",
|
|
249
|
+
id="hostmap.W004",
|
|
250
|
+
)
|
|
251
|
+
]
|
|
252
|
+
return []
|
hostmap/conf.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""Hostmap settings with defaults.
|
|
2
|
+
|
|
3
|
+
All settings use the ``HOSTMAP_`` prefix. Access via ``hostmap_settings``,
|
|
4
|
+
which reads from ``django.conf.settings`` lazily at access time so a test or
|
|
5
|
+
consuming project can override a setting after import (04-interfaces.md
|
|
6
|
+
section 2). Every setting has a working default per STANDARDS section 4.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from django.conf import settings
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _setting(name, default=None):
|
|
13
|
+
return getattr(settings, name, default)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class _Settings:
|
|
17
|
+
"""Lazy settings that read from ``django.conf.settings`` at access time."""
|
|
18
|
+
|
|
19
|
+
@property
|
|
20
|
+
def MAP(self): # noqa: N802
|
|
21
|
+
"""The host map dict. Empty map disables all behaviour."""
|
|
22
|
+
return _setting("HOSTMAP", {})
|
|
23
|
+
|
|
24
|
+
@property
|
|
25
|
+
def PARENT_DOMAIN(self): # noqa: N802
|
|
26
|
+
"""Domain joined to ``subdomain`` entries."""
|
|
27
|
+
return _setting("HOSTMAP_PARENT_DOMAIN", "")
|
|
28
|
+
|
|
29
|
+
@property
|
|
30
|
+
def DEFAULT(self): # noqa: N802
|
|
31
|
+
"""Entry label used for unmatched hosts and out-of-request reversing."""
|
|
32
|
+
return _setting("HOSTMAP_DEFAULT", "")
|
|
33
|
+
|
|
34
|
+
@property
|
|
35
|
+
def PATCH_REVERSE(self): # noqa: N802
|
|
36
|
+
"""Make stock ``reverse()`` / ``{% url %}`` host-aware."""
|
|
37
|
+
return _setting("HOSTMAP_PATCH_REVERSE", True)
|
|
38
|
+
|
|
39
|
+
@property
|
|
40
|
+
def SCHEME(self): # noqa: N802
|
|
41
|
+
"""Scheme for cross-host absolute URLs."""
|
|
42
|
+
return _setting("HOSTMAP_SCHEME", "https")
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def PORT(self): # noqa: N802
|
|
46
|
+
"""Port appended to all generated hosts; one port applies uniformly."""
|
|
47
|
+
return _setting("HOSTMAP_PORT", "")
|
|
48
|
+
|
|
49
|
+
@property
|
|
50
|
+
def UNMATCHED(self): # noqa: N802
|
|
51
|
+
"""``"default"`` routes unmatched hosts to the default entry; ``"reject"`` returns 404."""
|
|
52
|
+
return _setting("HOSTMAP_UNMATCHED", "default")
|
|
53
|
+
|
|
54
|
+
@property
|
|
55
|
+
def REDIRECT_PERMANENT(self): # noqa: N802
|
|
56
|
+
"""``redirect_to`` entries use 301 when true, 302 when false."""
|
|
57
|
+
return _setting("HOSTMAP_REDIRECT_PERMANENT", True)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
hostmap_settings = _Settings()
|
hostmap/context.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""Active-host context propagation via a contextvar.
|
|
2
|
+
|
|
3
|
+
The active entry lives in a ``contextvars.ContextVar``, mirroring how Django
|
|
4
|
+
itself propagates the urlconf under ASGI (asgiref locals). No thread locals,
|
|
5
|
+
so concurrent ASGI requests on different hosts never leak host context
|
|
6
|
+
(BR-HOSTMAP-001, AC-HOSTMAP-016). Outside a request the contextvar is unset,
|
|
7
|
+
and readers fall back to the ``HOSTMAP_DEFAULT`` entry (BR-HOSTMAP-006).
|
|
8
|
+
|
|
9
|
+
Setting the active entry also calls Django's ``set_urlconf()`` so that stock
|
|
10
|
+
``reverse()`` (which resolves ``urlconf=None`` via ``get_urlconf()``) picks
|
|
11
|
+
the active host's URLconf natively. Same-host reversing is then byte-identical
|
|
12
|
+
to stock Django (BR-HOSTMAP-003) even under ``use_host()`` and out of a
|
|
13
|
+
request; the resolver seam only adds cross-host fallback on top.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
from contextvars import ContextVar
|
|
19
|
+
from typing import TYPE_CHECKING
|
|
20
|
+
|
|
21
|
+
from django.urls import set_urlconf
|
|
22
|
+
|
|
23
|
+
if TYPE_CHECKING:
|
|
24
|
+
from hostmap.map import ResolvedEntry
|
|
25
|
+
|
|
26
|
+
_active_entry: ContextVar[ResolvedEntry | None] = ContextVar("hostmap_active_entry", default=None)
|
|
27
|
+
# Remembers the urlconf in force before each ``set_active`` so ``reset_active``
|
|
28
|
+
# can restore it, mirroring the contextvar token dance. The default is None
|
|
29
|
+
# (no mutable default); the stack is copied on write, never mutated in place.
|
|
30
|
+
_urlconf_stack: ContextVar[tuple | None] = ContextVar("hostmap_urlconf_stack", default=None)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def set_active(entry: ResolvedEntry | None) -> object:
|
|
34
|
+
"""Set the active entry and sync Django's urlconf. Returns a reset token."""
|
|
35
|
+
from django.urls import get_urlconf
|
|
36
|
+
|
|
37
|
+
previous_urlconf = get_urlconf()
|
|
38
|
+
stack = _urlconf_stack.get() or ()
|
|
39
|
+
_urlconf_stack.set((*stack, previous_urlconf))
|
|
40
|
+
|
|
41
|
+
token = _active_entry.set(entry)
|
|
42
|
+
if entry is not None and not entry.is_redirect:
|
|
43
|
+
set_urlconf(entry.urlconf)
|
|
44
|
+
return token
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def reset_active(token: object) -> None:
|
|
48
|
+
"""Restore the previous active entry and urlconf using the token."""
|
|
49
|
+
_active_entry.reset(token)
|
|
50
|
+
stack = _urlconf_stack.get()
|
|
51
|
+
if stack:
|
|
52
|
+
previous_urlconf = stack[-1]
|
|
53
|
+
_urlconf_stack.set(stack[:-1])
|
|
54
|
+
set_urlconf(previous_urlconf)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def get_active() -> ResolvedEntry | None:
|
|
58
|
+
"""Return the active entry, or the ``HOSTMAP_DEFAULT`` entry outside a request.
|
|
59
|
+
|
|
60
|
+
Returns ``None`` only when no entry is active and no default is
|
|
61
|
+
configured (an empty or misconfigured map).
|
|
62
|
+
"""
|
|
63
|
+
entry = _active_entry.get()
|
|
64
|
+
if entry is not None:
|
|
65
|
+
return entry
|
|
66
|
+
from hostmap.map import default_entry
|
|
67
|
+
|
|
68
|
+
return default_entry()
|
|
File without changes
|
|
File without changes
|