Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions deploy_gateway/auth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
"""Authentication against the existing version 1 gateway key store."""
import hashlib
import hmac
import json
from pathlib import Path
import re


def authorized(key_store, value):
data = json.loads(Path(key_store).read_text())
if data.get('version') != 1 or not isinstance(data.get('records'), dict):
raise ValueError('Unsupported key store')
digest = hashlib.sha256(value.encode()).hexdigest()
accepted = False
for record in data['records'].values():
expected = record['sha256']
if not re.fullmatch(r'[0-9a-f]{64}', expected) or not isinstance(record['active'], bool):
raise ValueError('Invalid key record')
matches = hmac.compare_digest(digest, expected)
accepted = accepted or (matches and record['active'])
return accepted
15 changes: 2 additions & 13 deletions deploy_gateway/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
"""
import argparse
import hashlib
import hmac
from http.client import HTTPConnection, HTTPException, IncompleteRead
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
Expand All @@ -18,6 +17,7 @@
import time
from urllib.parse import urlsplit

from .auth import authorized
from .routing import Busy, SessionRouter, Unavailable, affinity_key, prefix_rank

HOP_HEADERS = {'connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization',
Expand Down Expand Up @@ -141,18 +141,7 @@ def server_close(self):
super().server_close()

def authorized(self, value):
data = json.loads(self.key_store.read_text())
if data.get('version') != 1 or not isinstance(data.get('records'), dict):
raise ValueError('Unsupported key store')
digest = hashlib.sha256(value.encode()).hexdigest()
accepted = False
for record in data['records'].values():
expected = record['sha256']
if not re.fullmatch(r'[0-9a-f]{64}', expected) or not isinstance(record['active'], bool):
raise ValueError('Invalid key record')
matches = hmac.compare_digest(digest, expected)
accepted = accepted or (matches and record['active'])
return accepted
return authorized(self.key_store, value)

def context_route(self, headers):
values = headers.get_all('x-model-context-window', [])
Expand Down
1 change: 1 addition & 0 deletions deploy_model_router/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""Model alias router for an existing authenticated inference gateway."""
3 changes: 3 additions & 0 deletions deploy_model_router/__main__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from .server import main

main()
66 changes: 66 additions & 0 deletions deploy_model_router/caddy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
"""Prepare an atomic Caddy servers update without altering other routes."""
from copy import deepcopy


def proxies(value):
if isinstance(value, dict):
if value.get('handler') == 'reverse_proxy':
yield value
for child in value.values():
yield from proxies(child)
elif isinstance(value, list):
for child in value:
yield from proxies(child)


def prepare_servers(servers, *, front_port, fallback_port, router_port):
"""Return a copy; reject a topology whose safety cannot be established."""
if not all(type(x) is int and 1 <= x <= 65535 for x in (front_port, fallback_port, router_port)):
raise ValueError('Invalid port')
if len({front_port, fallback_port, router_port}) != 3 or not isinstance(servers, dict):
raise ValueError('Ports must be distinct')
result = deepcopy(servers)

def find(port):
found = [s for s in result.values() if isinstance(s, dict)
and any(isinstance(x, str) and x.rsplit(':', 1)[-1] == str(port)
for x in s.get('listen', []))]
if len(found) != 1 or len(found[0].get('listen', [])) != 1:
raise ValueError('Expected one dedicated server per port')
return found[0]

front, fallback = find(front_port), find(fallback_port)
if front is fallback or fallback.get('trusted_proxies'):
raise ValueError('Unsupported trusted-proxy topology')
front_proxies = list(proxies(front.get('routes', [])))
fallback_proxies = list(proxies(fallback.get('routes', [])))
if not front_proxies or len(front_proxies) != len(fallback_proxies):
raise ValueError('Unexpected proxy routes')
old = [p.get('upstreams') for p in fallback_proxies]
if any(not isinstance(x, list) or not x for x in old):
raise ValueError('No fallback upstreams')
if [p.get('upstreams') for p in front_proxies] != old:
raise ValueError('Frontend and fallback routes differ')
forbidden = {f'127.0.0.1:{p}' for p in (front_port, fallback_port, router_port)}
for items in old:
if any(not isinstance(x, dict) or not isinstance(x.get('dial'), str)
or x['dial'] in forbidden for x in items):
raise ValueError('Unexpected fallback upstream')
for proxy in front_proxies:
proxy['upstreams'] = [{'dial': f'127.0.0.1:{router_port}'},
{'dial': f'127.0.0.1:{fallback_port}'}]
proxy['load_balancing'] = {'selection_policy': {'policy': 'first'},
'try_duration': 5_000_000_000, 'try_interval': 200_000_000}
# A model-specific HTTP error must not take down the shared frontend.
proxy['health_checks'] = {'passive': {'fail_duration': 5_000_000_000, 'max_fails': 1}}
response_set = proxy.get('headers', {}).get('response', {}).get('set', {})
for name in tuple(response_set):
if name.lower() == 'x-llmdeploy-service':
del response_set[name]
fallback['trusted_proxies'] = {'source': 'static', 'ranges': ['127.0.0.1/32', '::1/128']}
for proxy in fallback_proxies:
request_set = proxy.setdefault('headers', {}).setdefault('request', {}).setdefault('set', {})
if any(k.lower() == 'x-forwarded-for' for k in request_set):
raise ValueError('Existing client-IP override needs review')
request_set['X-Forwarded-For'] = ['{http.vars.client_ip}']
return result
41 changes: 41 additions & 0 deletions deploy_model_router/credentials.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
"""Read an upstream credential without placing it in arguments or files."""
import ctypes
import os
from ctypes import wintypes


class _FileTime(ctypes.Structure):
_fields_ = [('low', wintypes.DWORD), ('high', wintypes.DWORD)]


class _Credential(ctypes.Structure):
_fields_ = [
('flags', wintypes.DWORD), ('type', wintypes.DWORD),
('target', wintypes.LPWSTR), ('comment', wintypes.LPWSTR),
('last_written', _FileTime), ('blob_size', wintypes.DWORD),
('blob', ctypes.POINTER(ctypes.c_ubyte)), ('persist', wintypes.DWORD),
('attribute_count', wintypes.DWORD), ('attributes', ctypes.c_void_p),
('target_alias', wintypes.LPWSTR), ('username', wintypes.LPWSTR),
]


def read_windows_credential(target):
if os.name != 'nt':
raise OSError('Windows Credential Manager is unavailable')
api = ctypes.WinDLL('advapi32', use_last_error=True)
api.CredReadW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD,
ctypes.POINTER(ctypes.POINTER(_Credential))]
api.CredReadW.restype = wintypes.BOOL
api.CredFree.argtypes = [ctypes.c_void_p]
ptr = ctypes.POINTER(_Credential)()
if not api.CredReadW(target, 1, 0, ctypes.byref(ptr)):
raise OSError('Upstream credential is unavailable')
try:
blob = ctypes.string_at(ptr.contents.blob, ptr.contents.blob_size)
encoding = 'utf-16-le' if len(blob) > 1 and blob[1] == 0 else 'utf-8'
value = blob.decode(encoding).rstrip('\x00')
if not value or '\r' in value or '\n' in value:
raise ValueError('Invalid upstream credential')
return value
finally:
api.CredFree(ptr)
Loading
Loading