basal-engine 3.0.3__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.
- basal/__init__.py +7 -0
- basal/adapter.py +420 -0
- basal/adapters.py +8 -0
- basal/agree.py +393 -0
- basal/attach.py +160 -0
- basal/attn512.py +132 -0
- basal/auth.py +194 -0
- basal/bench.py +367 -0
- basal/blockquant.py +227 -0
- basal/calibrate.py +2198 -0
- basal/chat.py +175 -0
- basal/cli.py +70 -0
- basal/client.py +8 -0
- basal/decision_log.py +189 -0
- basal/decision_rules.py +569 -0
- basal/decisions.py +158 -0
- basal/derive.py +98 -0
- basal/disconnect.py +85 -0
- basal/engine.py +6023 -0
- basal/evidence.py +133 -0
- basal/examples/choice.jsonl +8 -0
- basal/examples/complex.jsonl +5 -0
- basal/examples/labelled_tickets.jsonl +500 -0
- basal/examples/local_backend.py +34 -0
- basal/examples/noul.jsonl +8 -0
- basal/examples/questions.jsonl +20 -0
- basal/examples/score.jsonl +8 -0
- basal/examples/selfcheck_basal-omni-pico-Q8_0.json +1 -0
- basal/examples/selfcheck_basal-omni-pico.json +1 -0
- basal/examples/types_demo.py +74 -0
- basal/facts.py +497 -0
- basal/feedback.py +234 -0
- basal/file_identity.py +39 -0
- basal/finetune.py +321 -0
- basal/fit_decisions.py +944 -0
- basal/fla_configs.json +1822 -0
- basal/fold.py +206 -0
- basal/fonts/OFL-DMSans.txt +93 -0
- basal/fonts/OFL-SpaceGrotesk.txt +93 -0
- basal/fonts/dm-sans-latin-ext.woff2 +0 -0
- basal/fonts/dm-sans-latin.woff2 +0 -0
- basal/fonts/space-grotesk-latin-ext.woff2 +0 -0
- basal/fonts/space-grotesk-latin.woff2 +0 -0
- basal/fp8block.py +100 -0
- basal/gdn_graph.py +1792 -0
- basal/gemma4.py +726 -0
- basal/gemma4_graph.py +931 -0
- basal/gguf_export.py +497 -0
- basal/identity.py +217 -0
- basal/int8block.py +50 -0
- basal/interpolate.py +330 -0
- basal/jsonl.py +172 -0
- basal/lean.py +204 -0
- basal/llama_attn.py +252 -0
- basal/llama_attn_kernels.py +266 -0
- basal/llama_graph.py +587 -0
- basal/llama_kernels.py +593 -0
- basal/loadtest.py +189 -0
- basal/mcp_server.py +432 -0
- basal/media.py +138 -0
- basal/metrics.py +16 -0
- basal/mlx_attn_kernels.py +1057 -0
- basal/mlx_forward.py +326 -0
- basal/mlx_kernels.py +543 -0
- basal/mlx_metal.py +510 -0
- basal/navcut.py +283 -0
- basal/navigate.py +646 -0
- basal/navtree.py +397 -0
- basal/nvfp4.py +245 -0
- basal/ordercheck.py +165 -0
- basal/pdf.py +183 -0
- basal/prepared.py +355 -0
- basal/presets.py +8 -0
- basal/prompt.py +462 -0
- basal/rank.py +373 -0
- basal/readout.py +121 -0
- basal/request.py +327 -0
- basal/response_cache.py +105 -0
- basal/router.py +1551 -0
- basal/router_ui.html +902 -0
- basal/router_ui.py +277 -0
- basal/run.py +376 -0
- basal/selfcheck.py +215 -0
- basal/server.py +5279 -0
- basal/sets.py +214 -0
- basal/signals.py +28 -0
- basal/state_disk.py +942 -0
- basal/strix.py +505 -0
- basal/synth.py +92 -0
- basal/tasks.py +848 -0
- basal/textio.py +21 -0
- basal/think.py +390 -0
- basal/tools.py +171 -0
- basal/tpu.py +336 -0
- basal/tpu_kernels.py +129 -0
- basal/trace.py +125 -0
- basal/ui.html +861 -0
- basal/ui.py +526 -0
- basal/varloop.py +813 -0
- basal/varloop_graph.py +1377 -0
- basal/varloop_kernels.py +907 -0
- basal/viz.html +660 -0
- basal/viz.py +375 -0
- basal/vllm_unified.py +100 -0
- basal_engine-3.0.3.dist-info/METADATA +416 -0
- basal_engine-3.0.3.dist-info/RECORD +111 -0
- basal_engine-3.0.3.dist-info/WHEEL +5 -0
- basal_engine-3.0.3.dist-info/entry_points.txt +21 -0
- basal_engine-3.0.3.dist-info/licenses/LICENSE +202 -0
- basal_engine-3.0.3.dist-info/licenses/NOTICE +34 -0
- basal_engine-3.0.3.dist-info/top_level.txt +1 -0
basal/attn512.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""Causal attention for 512-wide heads (the global layers of basal-omni, Gemma 4) in Triton, for plain rows: every row
|
|
2
|
+
from position 0, queries and keys the same tokens. FlexAttention takes these heads only with small tiles (32 x 32: its
|
|
3
|
+
default tiles need more shared memory than a GPU has), so the global layers of a long state spent most of their time
|
|
4
|
+
there.
|
|
5
|
+
|
|
6
|
+
The kernel: one program per (128 query rows, query head, half of the output dim). S = Q K^T over key tiles of 64 (the
|
|
7
|
+
full 512-wide dot), an online softmax in exp2, O[:, half] += P V[:, half]; each half recomputes S (two 256-wide
|
|
8
|
+
accumulators fit where one 512-wide does not). Key tiles below the diagonal run unmasked, the diagonal tiles masked; the
|
|
9
|
+
longest rows of the causal triangle start first. Grouped key / value heads (one key head serves query heads h // group).
|
|
10
|
+
On an H100, against flex with 32 x 32 tiles (bf16, causal, 16k / 32k tokens): 1.92 / 2.22x for mini's global layers (8
|
|
11
|
+
query / 2 key heads), 1.62 / 1.58x for 1.1-max's (16 / 1), 1.60 / 1.55x for ultra's (32 / 4); the error against exact
|
|
12
|
+
fp32 attention the same as flex's. Its tiles need 200+ KB of shared memory per block: Hopper (sm_90) only."""
|
|
13
|
+
import torch
|
|
14
|
+
|
|
15
|
+
CONFIG = dict(BLOCK_M=128, BLOCK_N=64, DSPLIT=2, num_warps=8, num_stages=1)
|
|
16
|
+
_KERNEL = []
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def available():
|
|
20
|
+
"""None if the kernel runs here, else why not."""
|
|
21
|
+
if not torch.cuda.is_available():
|
|
22
|
+
return "needs a CUDA GPU"
|
|
23
|
+
if torch.cuda.get_device_capability() != (9, 0):
|
|
24
|
+
return "needs a Hopper GPU (sm_90; its tiles need more shared memory than other GPU classes have per block)"
|
|
25
|
+
try:
|
|
26
|
+
import triton # noqa: F401
|
|
27
|
+
except ImportError:
|
|
28
|
+
return "needs Triton"
|
|
29
|
+
return None
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def reference(q, k, v, scale=1.0):
|
|
33
|
+
"""The kernel's maths without the kernel (CPU, tests): causal softmax attention in fp32 (or wider), grouped heads."""
|
|
34
|
+
g, dt = q.shape[1] // k.shape[1], torch.promote_types(q.dtype, torch.float32)
|
|
35
|
+
k, v = k.to(dt).repeat_interleave(g, 1), v.to(dt).repeat_interleave(g, 1)
|
|
36
|
+
s = (q.to(dt) @ k.transpose(-1, -2)) * scale
|
|
37
|
+
L = q.shape[2]
|
|
38
|
+
s = s.masked_fill(torch.ones(L, L, dtype=torch.bool, device=q.device).triu(1), float("-inf"))
|
|
39
|
+
return (torch.softmax(s, -1) @ v).to(q.dtype)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _build():
|
|
43
|
+
"""The kernel as the torch op basal::attn512_causal (triton_op: Inductor keeps it inside a compiled layer; a CUDA
|
|
44
|
+
graph captures it like any kernel)."""
|
|
45
|
+
import triton
|
|
46
|
+
import triton.language as tl
|
|
47
|
+
from torch.library import triton_op, wrap_triton
|
|
48
|
+
|
|
49
|
+
@triton.jit
|
|
50
|
+
def kernel(Q, K, V, O, sq_b, sq_h, sq_l, sk_b, sk_h, sk_l, sv_b, sv_h, sv_l, so_b, so_h, so_l, L, n_m, qk_scale,
|
|
51
|
+
HQ: tl.constexpr, GROUP: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, D: tl.constexpr,
|
|
52
|
+
DV: tl.constexpr):
|
|
53
|
+
qk_scale = qk_scale.to(tl.float32) # (a compiled graph passes Python floats as fp64)
|
|
54
|
+
pid_m = n_m - 1 - tl.program_id(0) # the longest rows of the causal triangle first
|
|
55
|
+
bh, part = tl.program_id(1), tl.program_id(2)
|
|
56
|
+
b, h = bh // HQ, bh % HQ
|
|
57
|
+
offs_m = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
|
|
58
|
+
offs_n = tl.arange(0, BLOCK_N)
|
|
59
|
+
offs_d = tl.arange(0, D)
|
|
60
|
+
offs_v = part * DV + tl.arange(0, DV)
|
|
61
|
+
rows = offs_m.to(tl.int64)
|
|
62
|
+
q = tl.load(Q + b.to(tl.int64) * sq_b + h * sq_h + rows[:, None] * sq_l + offs_d[None, :],
|
|
63
|
+
mask=offs_m[:, None] < L, other=0.0)
|
|
64
|
+
k_base = K + b.to(tl.int64) * sk_b + (h // GROUP) * sk_h
|
|
65
|
+
v_base = V + b.to(tl.int64) * sv_b + (h // GROUP) * sv_h
|
|
66
|
+
m_i = tl.full([BLOCK_M], float("-inf"), tl.float32)
|
|
67
|
+
l_i = tl.zeros([BLOCK_M], tl.float32)
|
|
68
|
+
acc = tl.zeros([BLOCK_M, DV], tl.float32)
|
|
69
|
+
lo_diag = pid_m * BLOCK_M // BLOCK_N * BLOCK_N # the first key tile that reaches the diagonal
|
|
70
|
+
hi = tl.minimum((pid_m + 1) * BLOCK_M, L)
|
|
71
|
+
for start in tl.range(0, lo_diag, BLOCK_N): # below the diagonal: no mask
|
|
72
|
+
keys = (start + offs_n).to(tl.int64)
|
|
73
|
+
k = tl.load(k_base + keys[None, :] * sk_l + offs_d[:, None])
|
|
74
|
+
s = tl.dot(q, k) * qk_scale
|
|
75
|
+
m_new = tl.maximum(m_i, tl.max(s, 1))
|
|
76
|
+
p = tl.math.exp2(s - m_new[:, None])
|
|
77
|
+
alpha = tl.math.exp2(m_i - m_new)
|
|
78
|
+
l_i = l_i * alpha + tl.sum(p, 1)
|
|
79
|
+
v = tl.load(v_base + keys[:, None] * sv_l + offs_v[None, :])
|
|
80
|
+
acc = acc * alpha[:, None] + tl.dot(p.to(v.dtype), v)
|
|
81
|
+
m_i = m_new
|
|
82
|
+
for start in tl.range(lo_diag, hi, BLOCK_N): # the diagonal tiles: the causal mask and the end of the row
|
|
83
|
+
offs_k = start + offs_n
|
|
84
|
+
keys = offs_k.to(tl.int64)
|
|
85
|
+
k = tl.load(k_base + keys[None, :] * sk_l + offs_d[:, None], mask=offs_k[None, :] < L, other=0.0)
|
|
86
|
+
s = tl.dot(q, k) * qk_scale
|
|
87
|
+
s = tl.where((offs_m[:, None] >= offs_k[None, :]) & (offs_k[None, :] < L), s, float("-inf"))
|
|
88
|
+
m_new = tl.maximum(m_i, tl.max(s, 1))
|
|
89
|
+
p = tl.math.exp2(s - m_new[:, None])
|
|
90
|
+
alpha = tl.math.exp2(m_i - m_new)
|
|
91
|
+
l_i = l_i * alpha + tl.sum(p, 1)
|
|
92
|
+
v = tl.load(v_base + keys[:, None] * sv_l + offs_v[None, :], mask=offs_k[:, None] < L, other=0.0)
|
|
93
|
+
acc = acc * alpha[:, None] + tl.dot(p.to(v.dtype), v)
|
|
94
|
+
m_i = m_new
|
|
95
|
+
acc = acc / l_i[:, None]
|
|
96
|
+
tl.store(O + b.to(tl.int64) * so_b + h * so_h + rows[:, None] * so_l + offs_v[None, :],
|
|
97
|
+
acc.to(O.dtype.element_ty), mask=offs_m[:, None] < L)
|
|
98
|
+
|
|
99
|
+
@triton_op("basal::attn512_causal", mutates_args=())
|
|
100
|
+
def op(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, scale: float) -> torch.Tensor:
|
|
101
|
+
B, Hq, L, D = q.shape
|
|
102
|
+
o = torch.empty_like(q)
|
|
103
|
+
cf = CONFIG
|
|
104
|
+
n_m = (L + cf["BLOCK_M"] - 1) // cf["BLOCK_M"]
|
|
105
|
+
if L:
|
|
106
|
+
wrap_triton(kernel)[(n_m, B * Hq, cf["DSPLIT"])](
|
|
107
|
+
q, k, v, o, q.stride(0), q.stride(1), q.stride(2), k.stride(0), k.stride(1), k.stride(2),
|
|
108
|
+
v.stride(0), v.stride(1), v.stride(2), o.stride(0), o.stride(1), o.stride(2), L, n_m,
|
|
109
|
+
scale * 1.4426950408889634, HQ=Hq, GROUP=Hq // k.shape[1], BLOCK_M=cf["BLOCK_M"],
|
|
110
|
+
BLOCK_N=cf["BLOCK_N"], D=D, DV=D // cf["DSPLIT"], num_warps=cf["num_warps"],
|
|
111
|
+
num_stages=cf["num_stages"])
|
|
112
|
+
return o
|
|
113
|
+
|
|
114
|
+
return op
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def prepare():
|
|
118
|
+
"""Build the op before any layer is compiled (a compiled layer must find it registered)."""
|
|
119
|
+
if not _KERNEL:
|
|
120
|
+
_KERNEL.append(_build())
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def attention(q, k, v, scale=1.0):
|
|
124
|
+
"""Causal attention of plain rows: q [b, Hq, L, 512], k / v [b, Hkv, L, 512] (Hq a multiple of Hkv; v may be k)
|
|
125
|
+
-> [b, Hq, L, 512] in q's dtype."""
|
|
126
|
+
if not q.is_cuda:
|
|
127
|
+
return reference(q, k, v, scale)
|
|
128
|
+
prepare()
|
|
129
|
+
same = v is k # (keys = values: 1.1-max's and ultra's global layers)
|
|
130
|
+
q, k = (x if x.stride(-1) == 1 else x.contiguous() for x in (q, k))
|
|
131
|
+
v = k if same else (v if v.stride(-1) == 1 else v.contiguous())
|
|
132
|
+
return torch.ops.basal.attn512_causal(q, k, v, scale)
|
basal/auth.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
"""API-key authentication for basal-serve."""
|
|
2
|
+
import hashlib
|
|
3
|
+
import hmac
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
import sys
|
|
8
|
+
import threading
|
|
9
|
+
import time
|
|
10
|
+
import uuid
|
|
11
|
+
|
|
12
|
+
from .request import error_object
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class ApiKeys:
|
|
16
|
+
def __init__(self, path):
|
|
17
|
+
self.path = os.fspath(path)
|
|
18
|
+
self._lock = threading.Lock()
|
|
19
|
+
self._signature = None
|
|
20
|
+
self._loaded_at = None
|
|
21
|
+
self._usage = {}
|
|
22
|
+
self._warned = False
|
|
23
|
+
|
|
24
|
+
def _load(self):
|
|
25
|
+
try:
|
|
26
|
+
stat = os.stat(self.path)
|
|
27
|
+
signature = (stat.st_mtime_ns, stat.st_size, stat.st_ino)
|
|
28
|
+
now = time.monotonic()
|
|
29
|
+
if signature == self._signature and now - self._loaded_at <= 2:
|
|
30
|
+
return self._records
|
|
31
|
+
from .textio import read_text
|
|
32
|
+
data = json.loads(read_text(self.path))
|
|
33
|
+
records = data["keys"]
|
|
34
|
+
if not isinstance(records, list) or any(not isinstance(k, dict) or
|
|
35
|
+
not isinstance(k.get("name"), str) or not isinstance(k.get("sha256"), str) or
|
|
36
|
+
len(k["sha256"]) != 64 or any(c not in "0123456789abcdefABCDEF" for c in k["sha256"])
|
|
37
|
+
or not isinstance(k.get("admin", False), bool) for k in records):
|
|
38
|
+
raise ValueError("invalid API key file")
|
|
39
|
+
self._signature, self._records, self._warned = signature, records, False
|
|
40
|
+
self._loaded_at = now
|
|
41
|
+
return records
|
|
42
|
+
except (OSError, ValueError, KeyError, TypeError, json.JSONDecodeError) as e:
|
|
43
|
+
self._signature, self._records = None, []
|
|
44
|
+
if not self._warned:
|
|
45
|
+
print(f"basal: cannot read API key file: {e}", file=sys.stderr, flush=True)
|
|
46
|
+
self._warned = True
|
|
47
|
+
return []
|
|
48
|
+
|
|
49
|
+
def check(self, secret):
|
|
50
|
+
with self._lock:
|
|
51
|
+
digest = hashlib.sha256(secret.encode()).hexdigest()
|
|
52
|
+
for record in self._load():
|
|
53
|
+
if hmac.compare_digest(digest, record["sha256"].lower()):
|
|
54
|
+
return record
|
|
55
|
+
return None
|
|
56
|
+
|
|
57
|
+
def touch(self, name):
|
|
58
|
+
with self._lock:
|
|
59
|
+
self._usage[name] = time.time()
|
|
60
|
+
|
|
61
|
+
def usage(self):
|
|
62
|
+
with self._lock:
|
|
63
|
+
return [{"name": key["name"], "last_used": self._usage.get(key["name"])}
|
|
64
|
+
for key in self._load()]
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
async def _json(send, status, body, headers=()):
|
|
68
|
+
data = json.dumps(body).encode()
|
|
69
|
+
await send({"type": "http.response.start", "status": status,
|
|
70
|
+
"headers": [(b"content-type", b"application/json"), *headers]})
|
|
71
|
+
await send({"type": "http.response.body", "body": data})
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def protect(app, keys, cors_origins=()):
|
|
75
|
+
"""Protect HTTP routes without consuming request or response streams."""
|
|
76
|
+
async def auth_app(scope, receive, send):
|
|
77
|
+
if scope["type"] != "http":
|
|
78
|
+
await app(scope, receive, send)
|
|
79
|
+
return
|
|
80
|
+
path, method = scope["path"], scope["method"]
|
|
81
|
+
open_health = path in ("/health", "/health/") and method in ("GET", "HEAD")
|
|
82
|
+
record = None
|
|
83
|
+
if not open_health and keys is not None:
|
|
84
|
+
headers = dict(scope.get("headers", ()))
|
|
85
|
+
authorization = headers.get(b"authorization", b"").decode("latin1")
|
|
86
|
+
secret = authorization[7:].strip() if authorization.lower().startswith("bearer ") else ""
|
|
87
|
+
x_key = headers.get(b"x-api-key", b"").decode("latin1")
|
|
88
|
+
record = next((r for r in (keys.check(s) for s in (x_key, secret) if s) if r is not None), None)
|
|
89
|
+
if record is None:
|
|
90
|
+
body = error_object(path, 401, "missing or invalid API key", "UNAUTHORIZED")
|
|
91
|
+
await _json(send, 401, body, ((b"www-authenticate", b"Bearer"),))
|
|
92
|
+
return
|
|
93
|
+
keys.touch(record["name"])
|
|
94
|
+
scope["basal.api_key"] = record # routes behind protect() may check admin rights
|
|
95
|
+
if path == "/v1/keys" and method == "GET" and keys is not None: # without --api-keys: the app's 404
|
|
96
|
+
if record is not None and not record.get("admin", False):
|
|
97
|
+
await _json(send, 403, {"error": "admin key required", "code": "FORBIDDEN"})
|
|
98
|
+
return
|
|
99
|
+
await _json(send, 200, {"keys": keys.usage() if keys else []})
|
|
100
|
+
return
|
|
101
|
+
await app(scope, receive, send)
|
|
102
|
+
|
|
103
|
+
if cors_origins:
|
|
104
|
+
from starlette.middleware.cors import CORSMiddleware
|
|
105
|
+
return CORSMiddleware(auth_app, allow_origins=list(cors_origins), allow_methods=["GET", "POST", "OPTIONS"],
|
|
106
|
+
allow_headers=["Authorization", "Content-Type", "X-API-Key", "X-Request-Id", "Mcp-Session-Id",
|
|
107
|
+
"Mcp-Protocol-Version"], expose_headers=["Mcp-Session-Id", "x-request-id"])
|
|
108
|
+
return auth_app
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def request_ids(app):
|
|
112
|
+
"""Echo X-Request-Id (or a generated req_<hex>) as x-request-id on every response; the app finds it in
|
|
113
|
+
scope["basal.request_id"] (basal-router passes it on to the replicas)."""
|
|
114
|
+
async def with_request_id(scope, receive, send):
|
|
115
|
+
if scope["type"] != "http":
|
|
116
|
+
await app(scope, receive, send)
|
|
117
|
+
return
|
|
118
|
+
supplied = dict(scope.get("headers", ())).get(b"x-request-id", b"").decode("latin1")
|
|
119
|
+
request_id = supplied if re.fullmatch(r"[A-Za-z0-9._:-]{1,128}", supplied) else f"req_{uuid.uuid4().hex}"
|
|
120
|
+
scope["basal.request_id"] = request_id
|
|
121
|
+
|
|
122
|
+
async def send_with_id(message):
|
|
123
|
+
if message["type"] == "http.response.start":
|
|
124
|
+
message = dict(message)
|
|
125
|
+
message["headers"] = list(message.get("headers", [])) + [(b"x-request-id", request_id.encode())]
|
|
126
|
+
await send(message)
|
|
127
|
+
await app(scope, receive, send_with_id)
|
|
128
|
+
return with_request_id
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
LOOPBACK_NAMES = ("localhost", "127.0.0.1", "::1")
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def loopback(host):
|
|
135
|
+
"""A loopback host: localhost or an address of 127.0.0.0/8 / ::1."""
|
|
136
|
+
import ipaddress
|
|
137
|
+
host = (host or "").strip().strip("[]").lower()
|
|
138
|
+
if host == "localhost" or host.endswith(".localhost"):
|
|
139
|
+
return True
|
|
140
|
+
try:
|
|
141
|
+
return ipaddress.ip_address(host).is_loopback
|
|
142
|
+
except ValueError:
|
|
143
|
+
return False
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def allowed_hosts(bind, allowed=None, api_keys=None):
|
|
147
|
+
"""The Host names a request may give (host_check), or None for no check. --allowed-hosts "*": none; a list: those
|
|
148
|
+
and the loopback names; without it, the loopback names when the server is bound to a loopback host and has no
|
|
149
|
+
--api-keys (a web page cannot then reach it through DNS rebinding), else no check (a server bound to the network
|
|
150
|
+
is reached by name or address; one with --api-keys needs a key a page does not have)."""
|
|
151
|
+
if allowed is not None:
|
|
152
|
+
names = [h.strip().lower() for h in allowed.split(",") if h.strip()]
|
|
153
|
+
return None if "*" in names else set(names) | set(LOOPBACK_NAMES)
|
|
154
|
+
return set(LOOPBACK_NAMES) if loopback(bind) and not api_keys else None
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _host_of(value):
|
|
158
|
+
"""The host part of a Host header value ("127.0.0.1:8000", "[::1]:8000", "localhost")."""
|
|
159
|
+
value = value.strip().lower()
|
|
160
|
+
if value.startswith("["):
|
|
161
|
+
return value[1:value.find("]")] if "]" in value else value[1:]
|
|
162
|
+
return value.rsplit(":", 1)[0] if value.count(":") == 1 else value
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def host_check(app, hosts, cors_origins=()):
|
|
166
|
+
"""ASGI: a request whose Host header names a host outside `hosts`, or that comes from a web page of another origin
|
|
167
|
+
(an Origin header outside `hosts` and --cors-origins), answers 403 before the app reads it: a page cannot reach a
|
|
168
|
+
loopback server through DNS rebinding, nor send it requests from another site. GET and HEAD of /health and /health/
|
|
169
|
+
stay open, as protect leaves them (a load balancer or a proxy probes with a host of its own)."""
|
|
170
|
+
from urllib.parse import urlsplit
|
|
171
|
+
origins = {o.rstrip("/").lower() for o in cors_origins}
|
|
172
|
+
|
|
173
|
+
async def checked(scope, receive, send):
|
|
174
|
+
if scope["type"] != "http" or (scope["path"] in ("/health", "/health/") and scope["method"] in ("GET", "HEAD")):
|
|
175
|
+
await app(scope, receive, send)
|
|
176
|
+
return
|
|
177
|
+
headers = dict(scope.get("headers", ()))
|
|
178
|
+
host = headers.get(b"host", b"").decode("latin1")
|
|
179
|
+
origin = headers.get(b"origin", b"").decode("latin1").strip()
|
|
180
|
+
why = None
|
|
181
|
+
if host and _host_of(host) not in hosts:
|
|
182
|
+
why = f"Host {host!r} is not one this server answers (--allowed-hosts)"
|
|
183
|
+
elif origin and origin.rstrip("/").lower() not in origins:
|
|
184
|
+
try:
|
|
185
|
+
name = urlsplit(origin).hostname
|
|
186
|
+
except ValueError:
|
|
187
|
+
name = None
|
|
188
|
+
if name is None or name.lower() not in hosts:
|
|
189
|
+
why = f"Origin {origin!r} is not allowed (--allowed-hosts, --cors-origins)"
|
|
190
|
+
if why is not None:
|
|
191
|
+
await _json(send, 403, error_object(scope["path"], 403, why, "FORBIDDEN"))
|
|
192
|
+
return
|
|
193
|
+
await app(scope, receive, send)
|
|
194
|
+
return checked
|