diff --git a/openwebui-functionality/README.md b/openwebui-functionality/README.md index 8898de7..4d747f0 100644 --- a/openwebui-functionality/README.md +++ b/openwebui-functionality/README.md @@ -10,6 +10,8 @@ This part of the repository contains definitions of additional functionality cre ### Functions +- SciLifeLab ALTCHA Browser Gate from [oi_altcha_browser_gate.py](functions/oi_altcha_browser_gate.py). An Event Function serving a standalone browser interstitial for the optional Helm proxy. See [ALTCHA browser gate](#altcha-browser-gate). + - Request Quota Guard from [oi_request_quota_guard.py](functions/oi_request_quota_guard.py). Restricts the number of user requests per minute and also logs user request usage. - Rate Limit Enforcer from [oi_rate_limit_enforcer.py](functions/oi_rate_limit_enforcer.py). Restricts the number of user requests per minute. - SciLifeLab Email Verification from [oi_email_verification_callback.py](functions/oi_email_verification_callback.py). An Event Function that sends signup verification emails through the Gmail API and records email ownership in the `email-verified` group. See [Email verification](#email-verification) for setup. @@ -201,6 +203,89 @@ Saved admin Valve values override the optional environment defaults below. Envir Sender name and subject must be nonempty and contain no control characters; `login_url` must be empty or an HTTPS URL. +## ALTCHA browser gate + +The `altcha_browser_gate` Event Function serves a separate “Checking your browser” +page and delegates proof-of-work generation and verification to `whale-auth-tools`. +The optional `altchaGate` NGINX sidecar in the `openllm-charts` repository gates +browser navigation before it reaches Open WebUI. **No Open WebUI source changes, +frontend dependencies, or custom image rebuild are needed.** The Function alone +neither intercepts navigation nor blocks signup; the proxy provides enforcement. + +An unverified GET receives the interstitial at its original URL. The page runs +ALTCHA automatically, submits the solution, and reloads the same URL after the +server sets a Secure, HttpOnly, SameSite=Lax, host-only clearance cookie. This +preserves the path, query and fragment without accepting arbitrary redirect URLs. +Direct visits to `/auth/verify-human` continue to `/` after verification. JavaScript +and HTTPS are required. A retry button appears on failures. + +### Browser gate setup + +1. Bootstrap the initial administrator with the chart's `altchaGate.enabled=false` + (the default). Install `oi_altcha_browser_gate.py` in Admin Panel > Functions > + New: paste, save as `altcha_browser_gate`, and enable. No Global setting is needed. +2. Configure the environment settings below on **every worker and replica** using + the chart's `altchaGate` values and existing Kubernetes Secrets. Shared Redis + 6.2+ is required for atomic challenge consumption. HMAC secrets stay exclusively + in whale-auth-tools. +3. Enable `altchaGate.enabled` in your environment overlay and restart all replicas + through the normal deployment workflow. Enabling a Function does not replay + startup; each worker must register its routes before receiving gated traffic. +4. Check the chart's exception paths against your callback URLs and API clients. + Test a fresh browser, verification expiry, direct signup without a cookie, + service/Redis outages, OAuth, email links, streaming, and WebSockets before rollout. + +| Environment setting | Purpose | +| --- | --- | +| `WHALE_AUTH_URL` | Service base URL, normally `http://whale-auth-tools:8080`. HTTP is for a trusted internal network; otherwise use HTTPS. | +| `WHALE_AUTH_API_TOKEN` | Service Bearer credential, supplied from a Secret. Never exposed to browsers. | +| `ALTCHA_REDIS_URL` | Same Redis 6.2+ database on all replicas. Supply credentials through a Secret. | +| `ALTCHA_PUBLIC_ORIGINS` | Comma-separated exact HTTPS origins, e.g. `https://openllm.example.org,https://openllm-dev.example.org`. Include each public hostname; omit paths and trailing slashes. | + +The Function installs `httpx==0.28.1` and `redis==8.0.1` through its metadata. +Include them in the image if runtime package installation is disabled. Missing +settings leave the Function inactive with a warning. With the proxy enabled, +missing/disabled Functions or service/Redis failures block protected traffic. +Restart after environment changes. To remove the gate, disable `altchaGate.enabled` +and redeploy; disabling only the Function intentionally blocks protected traffic. + +| Valve | Default | Purpose | +| --- | --- | --- | +| `clearance_ttl` | `3600` | Integer seconds the verified browser may access protected routes, from 60 to 86400. Saved settings refresh on requests; existing cookies retain their original expiry. | + +Routes registered before the SPA catch-all: + +- `GET /auth/verify-human`: standalone interstitial, with no-store and CSP headers. +- `POST /api/v1/altcha-gate/challenge`: service challenge, bound for at most ten minutes to a separate SameSite=Strict pending cookie. Each tab's challenge is stored separately. Returns `{"verified": true}` without a new challenge when the browser already has valid clearance. +- `POST /api/v1/altcha-gate/verify`: accepts JSON `{"altchaPayload":""}` up to 16 KiB. Atomically consumes the issued challenge, compares it with the submitted challenge, then calls the service. The service also validates signed expiry. Success sets the clearance cookie to a random token. +- `POST /api/v1/altcha-gate/check`: returns 204 for valid clearance, 401 if absent/expired, or 503 if unavailable. The chart blocks direct public access and invokes it through an internal proxy subrequest. POST is deliberate: a missing Function must not be mistaken for Open WebUI's HTTP-200 SPA fallback for unknown GET paths. + +The chart serves the pinned `altcha@3.5.0` widget locally at +`/auth/verify-human/altcha-3.5.0.min.js`, including its license. Widget v3 supports +the service's v2 challenge protocol. No external CDN or CORS configuration is needed. + +Challenges are single-use, including failed verification attempts. **Clearance is +reusable until expiry**, as in a browser interstitial; it is not a one-account-per- +challenge quota. Redis loss invalidates outstanding checks and clearance. The +clearance cookie is SameSite=Lax so links from email, Slack, other sites and OAuth +returns keep it; cross-site POSTs to protected endpoints still omit it. Tabs verify +independently, and a new challenge never replaces existing clearance. The chart +rate-limits challenge and verify requests per client; the page reports 429s. + +The chart exempts health checks, email callbacks, OAuth, static assets, WebSockets, +and API routes, which retain Open WebUI's normal authentication. Password signup, +signin and LDAP auth remain protected even under the broad API exception, including +trailing-slash forms. Unverified API submissions get 403 JSON asking the user to +reload; the proxy never replays their POST body. OAuth and other provisioning remain +outside this proof-of-work gate. Documentation routes served by the separate docs +Service also remain public. This is an anti-abuse check, not a substitute for API +authentication, request-rate limits, or volumetric DDoS protection. + +Function tests cover clearance, cookie separation, parallel tabs, cross-replica +state, replay, expiry, malformed and oversized payloads, service failure, origin checks, Valve validation, route reload, +and the missing-Function SPA fallback. Chart proxy tests cover routing and exceptions +with the real pinned NGINX image and an isolated fake backend. + ## Tests Run the unit tests with the optional test dependencies from [pyproject.toml](pyproject.toml): diff --git a/openwebui-functionality/functions/oi_altcha_browser_gate.py b/openwebui-functionality/functions/oi_altcha_browser_gate.py new file mode 100644 index 0000000..781041c --- /dev/null +++ b/openwebui-functionality/functions/oi_altcha_browser_gate.py @@ -0,0 +1,282 @@ +""" +title: SciLifeLab ALTCHA Browser Gate +oi_type: event +function_id: altcha_browser_gate +description: Serve a browser interstitial and validate clearance for an NGINX proxy. +author: SciLifeLab +version: 0.3.0 +requirements: httpx==0.28.1, redis==8.0.1 + +Requires the optional openllm-charts ALTCHA proxy and HTTPS; no app source changes. +Deployment: WHALE_AUTH_URL, WHALE_AUTH_API_TOKEN, ALTCHA_REDIS_URL, +ALTCHA_PUBLIC_ORIGINS (comma-separated exact HTTPS origins). +Restart all replicas after installation. No HMAC secrets enter Open WebUI. +""" + +import base64 +import binascii +import hashlib +import json +import logging +import os +import re +import secrets +from urllib.parse import urlsplit + +import httpx +from fastapi import HTTPException, Request +from fastapi.responses import HTMLResponse, JSONResponse, Response +from open_webui.models.functions import Functions +from pydantic import BaseModel, Field +from redis.asyncio import Redis +from redis.exceptions import RedisError +from starlette.routing import Mount + +log = logging.getLogger(__name__) +PREFIX = "/api/v1/altcha-gate" +PAGE = "/auth/verify-human" +COOKIE = "__Host-altcha-clearance" +# Pending challenges use a separate cookie so a new challenge never replaces clearance. +PENDING = "__Host-altcha-pending" +KEY = "openwebui:altcha-gate:" +REQUIRED = ("WHALE_AUTH_URL", "WHALE_AUTH_API_TOKEN", "ALTCHA_REDIS_URL", "ALTCHA_PUBLIC_ORIGINS") + + +class Event: + class Valves(BaseModel): + clearance_ttl: int = Field(default=3600, ge=60, le=86400, description="Seconds the verified browser may access the website.") + + def __init__(self): + self.valves = self.Valves() + self._function_id = None + self._app = None + self._redis = None + self._warned = False + + async def event(self, event: dict, __id__: str | None = None, __app__=None): + self._function_id = __id__ or self._function_id + missing = [key for key in REQUIRED if not os.getenv(key, "").strip()] + if missing: + if not self._warned: + log.warning("ALTCHA browser gate inactive; missing: %s", ", ".join(missing)) + self._warned = True + return + if __app__ is not None: + self.setup(__app__) + + def setup(self, app): + if app is self._app: + return + self.origins = {origin.strip().rstrip("/") for origin in os.environ["ALTCHA_PUBLIC_ORIGINS"].split(",")} + self.service = os.environ["WHALE_AUTH_URL"].rstrip("/") + for url, public in [(origin, True) for origin in self.origins] + [(self.service, False)]: + parsed = urlsplit(url) + if (parsed.scheme not in ({"https"} if public else {"http", "https"}) + or not parsed.netloc or parsed.username or parsed.password + or parsed.query or parsed.fragment or (public and parsed.path)): + raise ValueError("Invalid ALTCHA origin or service URL") + self._redis = Redis.from_url(os.environ["ALTCHA_REDIS_URL"], decode_responses=True, + socket_connect_timeout=5, socket_timeout=5) + routes = app.router.routes + routes[:] = [r for r in routes if not (getattr(r, "name", "") or "").startswith("altcha_browser_")] + for path, handler, method in ((f"{PREFIX}/challenge", self.challenge, "POST"), + (f"{PREFIX}/verify", self.verify, "POST"), + (f"{PREFIX}/check", self.check, "POST"), + (PAGE, self.page, "GET")): + suffix = path.rsplit("/", 1)[-1] + if any(getattr(r, "path", None) == path for r in routes): + raise RuntimeError("ALTCHA route already exists") + app.add_api_route(path, handler, methods=[method], name=f"altcha_browser_{suffix}", include_in_schema=False) + added = [r for r in routes if (getattr(r, "name", "") or "").startswith("altcha_browser_")] + for route in added: + routes.remove(route) + index = next((i for i, r in enumerate(routes) if isinstance(r, Mount) and r.path in ("", "/")), len(routes)) + routes[index:index] = added + self._app = app + + async def ready(self, request: Request, check_origin=True): + # Registered routes survive disabling a Function; explicitly fail closed. + function = await Functions.get_function_by_id(self._function_id) if self._function_id else None + if not function or not function.is_active or not all(os.getenv(key, "").strip() for key in REQUIRED): + raise HTTPException(503, "Browser verification is unavailable") + self.valves = self.Valves(**(await Functions.get_function_valves_by_id(self._function_id) or {})) + if check_origin and (request.headers.get("origin") not in self.origins or request.headers.get("sec-fetch-site") == "cross-site"): + raise HTTPException(403, "Same-origin browser verification is required") + + async def storage(self, method, *args, **kwargs): + try: + return await getattr(self._redis, method)(*args, **kwargs) + except RedisError: + raise HTTPException(503, "Browser verification is unavailable") from None + + async def upstream(self, endpoint, payload=None): + try: + async with httpx.AsyncClient(timeout=10, follow_redirects=False, trust_env=False) as client: + response = await client.post(f"{self.service}/api/v1/altcha/{endpoint}", json=payload, + headers={"Authorization": f"Bearer {os.environ['WHALE_AUTH_API_TOKEN']}"}) + response.raise_for_status() + data = response.json() + if not isinstance(data, dict): + raise ValueError() + return data + except (httpx.HTTPError, ValueError): + raise HTTPException(503, "Browser verification is unavailable") from None + + @staticmethod + def token(request, cookie): + token = request.cookies.get(cookie, "") + return token if re.fullmatch(r"[0-9a-f]{64}", token) else None + + @staticmethod + def pending_key(browser, signature): + # One key per issued challenge lets several tabs verify independently. + return f"{KEY}pending:{browser}:{hashlib.sha256(signature.encode()).hexdigest()}" + + async def cleared(self, request): + token = self.token(request, COOKIE) + return bool(token) and await self.storage("get", KEY + token) == "verified" + + def response(self, data, cookie, token, ttl): + response = JSONResponse(data, headers={"Cache-Control": "no-store"}) + # Lax keeps clearance on top-level navigations from other sites (email, Slack, + # OAuth returns); cross-site POSTs to protected endpoints still omit it. + samesite = "lax" if cookie == COOKIE else "strict" + response.set_cookie(cookie, token, max_age=ttl, secure=True, httponly=True, samesite=samesite, path="/") + return response + + async def challenge(self, request: Request): + await self.ready(request) + if await self.cleared(request): + # Another tab already verified this browser; keep its clearance cookie. + return JSONResponse({"verified": True}, headers={"Cache-Control": "no-store"}) + challenge = await self.upstream("challenge") + if not isinstance(challenge.get("parameters"), dict) or not isinstance(challenge.get("signature"), str) \ + or not challenge["signature"]: + raise HTTPException(503, "Unsupported ALTCHA challenge") + browser = self.token(request, PENDING) or secrets.token_hex(32) + # Match the exact challenge issued to this browser. Redis TTL caps its lifetime; + # whale-auth-tools independently checks its signed expiresAt timestamp. + await self.storage("set", self.pending_key(browser, challenge["signature"]), json.dumps(challenge), ex=600) + return self.response(challenge, PENDING, browser, 600) + + async def verify(self, request: Request): + await self.ready(request) + raw = bytearray() + async for chunk in request.stream(): + raw.extend(chunk) + if len(raw) > 16384: + raise HTTPException(413, "Verification payload is too large") + try: + data = json.loads(raw) + payload = data["altchaPayload"] + if not isinstance(payload, str): + raise ValueError() + decoded = json.loads(base64.b64decode(payload, validate=True)) + challenge = decoded["challenge"] + signature = challenge["signature"] + if not isinstance(signature, str): + raise ValueError() + except (ValueError, KeyError, TypeError, binascii.Error): + raise HTTPException(400, "Invalid ALTCHA payload") from None + browser = self.token(request, PENDING) + if not browser: + raise HTTPException(403, "Complete browser verification first") + issued = await self.storage("getdel", self.pending_key(browser, signature)) + if not issued or json.loads(issued) != challenge: + raise HTTPException(403, "Challenge expired or already used; try again") + result = await self.upstream("verify", {"altchaPayload": payload}) + if result.get("verified") is not True or any(result.get(key) for key in ("expired", "invalidSignature", "invalidSolution", "error")): + raise HTTPException(403, "Verification failed; try again") + token = secrets.token_hex(32) + await self.storage("set", KEY + token, "verified", ex=self.valves.clearance_ttl) + return self.response({"verified": True, "expiresIn": self.valves.clearance_ttl}, COOKIE, token, self.valves.clearance_ttl) + + async def check(self, request: Request): + await self.ready(request, check_origin=False) + valid = await self.cleared(request) + return Response(status_code=204 if valid else 401, headers={"Cache-Control": "no-store"}) + + async def page(self, request: Request): + await self.ready(request, check_origin=False) + nonce = secrets.token_urlsafe(24) + # The proxy serves this HTML at the original navigation URL. Reloading + # preserves the path, query and fragment without accepting redirect URLs. + html = GATE_HTML.replace("__NONCE__", nonce) + return HTMLResponse(html, headers={ + "Cache-Control": "no-store", + "Referrer-Policy": "no-referrer", + "X-Content-Type-Options": "nosniff", + "Content-Security-Policy": ( + f"default-src 'none'; script-src 'self' 'nonce-{nonce}'; " + f"style-src 'self' 'unsafe-inline'; connect-src 'self'; " + "worker-src 'self' blob:; img-src 'self' data:; " + "base-uri 'none'; form-action 'none'; frame-ancestors 'none'" + ), + }) + + +GATE_HTML = r''' + +Checking your browser +
+

Checking your browser

This brief security check helps keep automated abuse away. You will continue automatically.

+

Preparing verification…

+
+ +
''' diff --git a/openwebui-functionality/pyproject.toml b/openwebui-functionality/pyproject.toml index e75f6b2..c72c91b 100644 --- a/openwebui-functionality/pyproject.toml +++ b/openwebui-functionality/pyproject.toml @@ -14,6 +14,8 @@ test = [ "google-auth", "requests", "itsdangerous", + "httpx==0.28.1", + "redis==8.0.1", ] [tool.pytest.ini_options] diff --git a/openwebui-functionality/tests/functions/test_oi_altcha_browser_gate.py b/openwebui-functionality/tests/functions/test_oi_altcha_browser_gate.py new file mode 100644 index 0000000..9627bc4 --- /dev/null +++ b/openwebui-functionality/tests/functions/test_oi_altcha_browser_gate.py @@ -0,0 +1,242 @@ +import asyncio +import base64 +import importlib.util +import json +from pathlib import Path +import sys +from types import ModuleType, SimpleNamespace +from unittest.mock import AsyncMock + +import httpx +import pytest +from fastapi import FastAPI, Request +from pydantic import ValidationError +from redis.exceptions import ConnectionError +from starlette.staticfiles import StaticFiles +from starlette.exceptions import HTTPException as StarletteHTTPException + + +class Store: + def __init__(self): + self.values = {} + self.ttls = {} + + async def set(self, key, value, ex): + self.values[key] = value + self.ttls[key] = ex + + async def get(self, key): + return self.values.get(key) + + async def getdel(self, key): + return self.values.pop(key, None) + + +@pytest.fixture +async def gate(monkeypatch, tmp_path): + functions = SimpleNamespace(get_function_by_id=AsyncMock(return_value=SimpleNamespace(is_active=True)), + get_function_valves_by_id=AsyncMock(return_value={})) + for name in ('open_webui', 'open_webui.models', 'open_webui.models.functions'): + module = ModuleType(name) + module.Functions = functions + monkeypatch.setitem(sys.modules, name, module) + for key, value in {'WHALE_AUTH_URL': 'http://whale.test', 'WHALE_AUTH_API_TOKEN': 'test-only', + 'ALTCHA_REDIS_URL': 'redis://localhost', 'ALTCHA_PUBLIC_ORIGINS': 'https://webui.test'}.items(): + monkeypatch.setenv(key, value) + path = Path(__file__).parents[2] / 'functions/oi_altcha_browser_gate.py' + spec = importlib.util.spec_from_file_location('test_altcha_gate', path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + store = Store() + monkeypatch.setattr(module.Redis, 'from_url', lambda *a, **kw: store) + fn = module.Event() + app = FastAPI() + + class SPA(StaticFiles): + async def get_response(self, path, scope): + try: + return await super().get_response(path, scope) + except StarletteHTTPException as error: + if error.status_code == 404: + return await super().get_response('index.html', scope) + raise + (tmp_path / 'index.html').write_text('SPA') + app.mount('/', SPA(directory=tmp_path, html=True)) + await fn.event({}, __id__='altcha_browser_gate', __app__=app) + challenge = {'parameters': {'nonce': 'unique', 'algorithm': 'PBKDF2/SHA-256'}, 'signature': 'signed'} + fn.upstream = AsyncMock(side_effect=lambda endpoint, payload=None: challenge if endpoint == 'challenge' else {'verified': True}) + async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url='https://webui.test', + headers={'Origin': 'https://webui.test'}) as client: + yield SimpleNamespace(fn=fn, app=app, client=client, module=module, store=store, + functions=functions, challenge=challenge) + + +def payload(challenge): + return {'altchaPayload': base64.b64encode(json.dumps({'challenge': challenge, 'solution': {}}).encode()).decode()} + + +async def verified(gate): + assert (await gate.client.post(gate.module.PREFIX + '/challenge')).status_code == 200 + return await gate.client.post(gate.module.PREFIX + '/verify', json=payload(gate.challenge)) + + +async def test_clearance_cookie_expiry_and_cross_replica(gate): + assert (await gate.client.post(gate.module.PREFIX + '/check')).status_code == 401 + response = await verified(gate) + assert response.json() == {'verified': True, 'expiresIn': 3600} + cookie = response.headers['set-cookie'] + assert all(flag in cookie for flag in ('Secure', 'HttpOnly', 'SameSite=lax', 'Path=/')) + replica = gate.module.Event() + replica._function_id = 'altcha_browser_gate' + replica.origins = gate.fn.origins + replica._redis = gate.store + from starlette.requests import Request + request = Request({'type': 'http', 'headers': [(b'cookie', ('%s=%s' % (gate.module.COOKIE, gate.client.cookies.get(gate.module.COOKIE))).encode())]}) + assert (await replica.check(request)).status_code == 204 + responses = await asyncio.gather(*(gate.client.post(gate.module.PREFIX + '/check') for _ in range(2))) + assert [r.status_code for r in responses] == [204, 204] + gate.store.values.clear() # Redis expiration invalidates clearance everywhere. + assert (await replica.check(request)).status_code == 401 + + +async def test_replay_and_different_browser_rejected(gate): + await gate.client.post(gate.module.PREFIX + '/challenge') + original = gate.client.cookies.get(gate.module.PENDING) + gate.client.cookies.clear() + assert (await gate.client.post(gate.module.PREFIX + '/verify', json=payload(gate.challenge))).status_code == 403 + gate.client.cookies.set(gate.module.PENDING, original) + assert (await gate.client.post(gate.module.PREFIX + '/verify', json=payload(gate.challenge))).status_code == 200 + gate.client.cookies.clear() + gate.client.cookies.set(gate.module.PENDING, original) + assert (await gate.client.post(gate.module.PREFIX + '/verify', json=payload(gate.challenge))).status_code == 403 + + +async def test_challenge_cookie_is_separate_from_clearance(gate): + response = await gate.client.post(gate.module.PREFIX + '/challenge') + cookie = response.headers['set-cookie'] + assert cookie.startswith(gate.module.PENDING + '=') and 'SameSite=strict' in cookie + assert gate.client.cookies.get(gate.module.COOKIE) is None + + +async def test_challenge_keeps_existing_clearance(gate): + assert (await verified(gate)).status_code == 200 + clearance = gate.client.cookies.get(gate.module.COOKIE) + gate.fn.upstream.reset_mock() + response = await gate.client.post(gate.module.PREFIX + '/challenge') + assert response.json() == {'verified': True} + assert 'set-cookie' not in response.headers + gate.fn.upstream.assert_not_called() + assert gate.client.cookies.get(gate.module.COOKIE) == clearance + assert (await gate.client.post(gate.module.PREFIX + '/check')).status_code == 204 + + +async def test_parallel_tabs_verify_independently(gate): + issued = iter([{'parameters': {'nonce': n}, 'signature': 'signed-' + n} for n in ('a', 'b')]) + gate.fn.upstream.side_effect = lambda endpoint, payload=None: next(issued) if endpoint == 'challenge' else {'verified': True} + first = (await gate.client.post(gate.module.PREFIX + '/challenge')).json() + second = (await gate.client.post(gate.module.PREFIX + '/challenge')).json() + assert (await gate.client.post(gate.module.PREFIX + '/verify', json=payload(second))).status_code == 200 + gate.client.cookies.delete(gate.module.COOKIE) # The other tab still solves its own challenge. + assert (await gate.client.post(gate.module.PREFIX + '/verify', json=payload(first))).status_code == 200 + assert (await gate.client.post(gate.module.PREFIX + '/check')).status_code == 204 + + +@pytest.mark.parametrize('body', [{}, [], {'altchaPayload': 42}, {'altchaPayload': '!'}, {'altchaPayload': 'bnVsbA=='}, + payload({'signature': 42})]) +async def test_bad_payload(gate, body): + assert (await gate.client.post(gate.module.PREFIX + '/verify', json=body)).status_code == 400 + + +async def test_payload_limit(gate): + assert (await gate.client.post(gate.module.PREFIX + '/verify', content='x' * 16385)).status_code == 413 + + +async def test_wrong_challenge_and_expired_session(gate): + await gate.client.post(gate.module.PREFIX + '/challenge') + assert (await gate.client.post(gate.module.PREFIX + '/verify', json=payload({'signature': 'different'}))).status_code == 403 + await gate.client.post(gate.module.PREFIX + '/challenge') + gate.store.values.clear() # Redis expiration. + assert (await gate.client.post(gate.module.PREFIX + '/verify', json=payload(gate.challenge))).status_code == 403 + + +@pytest.mark.parametrize('result', [{'verified': False}, {'verified': 'true'}, {'verified': True, 'expired': True}, {'verified': True, 'invalidSignature': True}]) +async def test_upstream_rejection(gate, result): + await gate.client.post(gate.module.PREFIX + '/challenge') + gate.fn.upstream.side_effect = None + gate.fn.upstream.return_value = result + assert (await gate.client.post(gate.module.PREFIX + '/verify', json=payload(gate.challenge))).status_code == 403 + assert (await gate.client.post(gate.module.PREFIX + '/check')).status_code == 401 + + +async def test_origin_disabled_and_redis_failure(gate): + assert (await gate.client.post(gate.module.PREFIX + '/challenge', headers={'Origin': 'https://other.test'})).status_code == 403 + gate.functions.get_function_by_id.return_value.is_active = False + assert (await gate.client.post(gate.module.PREFIX + '/challenge')).status_code == 503 + gate.functions.get_function_by_id.return_value.is_active = True + gate.store.set = AsyncMock(side_effect=ConnectionError()) + assert (await gate.client.post(gate.module.PREFIX + '/challenge')).status_code == 503 + + +async def test_saved_valves_and_missing_settings(gate, monkeypatch): + gate.functions.get_function_valves_by_id.return_value = {'clearance_ttl': 60} + assert (await verified(gate)).json()['expiresIn'] == 60 + assert 60 in gate.store.ttls.values() + with pytest.raises(ValidationError): + gate.module.Event.Valves(clearance_ttl=0) + monkeypatch.delenv('WHALE_AUTH_API_TOKEN') + app = FastAPI() + await gate.module.Event().event({}, __app__=app) + assert not hasattr(app.state, 'altcha_browser_guard') + assert (await gate.client.post(gate.module.PREFIX + '/check')).status_code == 503 + + +async def test_route_reload_and_upstream_auth(gate, monkeypatch): + other = gate.module.Event() + await other.event({}, __id__='altcha_browser_gate', __app__=gate.app) + assert len([r for r in gate.app.routes if (r.name or '').startswith('altcha_browser_')]) == 4 + real_client = httpx.AsyncClient + def transport(request): + assert request.headers['authorization'] == 'Bearer test-only' + assert str(request.url) == 'http://whale.test/api/v1/altcha/verify' + return httpx.Response(200, json={'verified': True}) + monkeypatch.setattr(gate.module.httpx, 'AsyncClient', lambda **kw: real_client(transport=httpx.MockTransport(transport), **kw)) + assert await other.upstream('verify', {'altchaPayload': 'test'}) == {'verified': True} + + +@pytest.mark.parametrize('failure', ['timeout', 'http', 'json']) +async def test_upstream_failure_is_closed(gate, monkeypatch, failure): + real_client = httpx.AsyncClient + def transport(request): + if failure == 'timeout': + raise httpx.ReadTimeout('test', request=request) + if failure == 'http': + return httpx.Response(401) + return httpx.Response(200, text='not JSON') + monkeypatch.setattr(gate.module.httpx, 'AsyncClient', lambda **kw: real_client(transport=httpx.MockTransport(transport), **kw)) + with pytest.raises(gate.module.HTTPException) as error: + await gate.module.Event.upstream(gate.fn, 'challenge') + assert error.value.status_code == 503 + + +async def test_unsolved_challenge_is_not_a_signup_pass(gate): + await gate.client.post(gate.module.PREFIX + '/challenge') + assert (await gate.client.post(gate.module.PREFIX + '/check')).status_code == 401 + + +async def test_interstitial_no_cache_and_script_policy(gate): + response = await gate.client.get('/auth/verify-human') + assert response.status_code == 200 + assert 'Checking your browser' in response.text + assert '/auth/verify-human/altcha-3.5.0.min.js' in response.text + assert response.headers['cache-control'] == 'no-store' + assert "frame-ancestors 'none'" in response.headers['content-security-policy'] + assert '__NONCE__' not in response.text + assert 'test-only' not in response.text + + +async def test_check_is_post_and_not_spa_get_fallback(gate): + assert (await gate.client.post(gate.module.PREFIX + '/check')).status_code == 401 + # The real SPA returns 405 for POST when a Function isn't registered. + gate.app.router.routes[:] = [r for r in gate.app.routes if (r.name or '') != 'altcha_browser_check'] + assert (await gate.client.get(gate.module.PREFIX + '/check')).text == 'SPA' + assert (await gate.client.post(gate.module.PREFIX + '/check')).status_code == 405 diff --git a/openwebui-functionality/uv.lock b/openwebui-functionality/uv.lock index 2166d0a..c020911 100644 --- a/openwebui-functionality/uv.lock +++ b/openwebui-functionality/uv.lock @@ -39,6 +39,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/12/b8/4bd346e22b28902df4d651910f5242c28d84e4a5c2435ca5c3f797ed7e2e/anyio-4.15.1-py3-none-any.whl", hash = "sha256:6152fdbbf9a77fdec97731721bebf7c4c44f7c29b424b0065826173efc7ed101", size = 132079, upload-time = "2026-09-05T10:42:37.923Z" }, ] +[[package]] +name = "async-timeout" +version = "5.0.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a5/ae/136395dfbfe00dfc94da3f3e136d0b13f394cba8f4841120e34226265780/async_timeout-5.0.1.tar.gz", hash = "sha256:d9321a7a3d5a6a5e187e824d2fa0793ce379a202935782d555d6e9d2735677d3", size = 9274, upload-time = "2024-11-06T16:41:39.6Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fe/ba/e2081de779ca30d473f21f5b30e0e737c438205440784c7dfc81efc2b029/async_timeout-5.0.1-py3-none-any.whl", hash = "sha256:39e3809566ff85354557ec2398b55e096c8364bacac9405a7a1fa429e77fe76c", size = 6233, upload-time = "2024-11-06T16:41:37.9Z" }, +] + [[package]] name = "backports-asyncio-runner" version = "1.2.0" @@ -414,7 +423,7 @@ name = "exceptiongroup" version = "1.3.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "typing-extensions", marker = "python_full_version < '3.13'" }, + { name = "typing-extensions", marker = "python_full_version < '3.11'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/50/79/66800aadf48771f6b62f7eb014e352e5d06856655206165d775e675a02c9/exceptiongroup-1.3.1.tar.gz", hash = "sha256:8b412432c6055b0b7d14c310000ae93352ed6754f70fa8f7c34141f91c4e3219", size = 30371, upload-time = "2025-11-21T23:01:54.787Z" } wheels = [ @@ -452,6 +461,43 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/eb/a3/87fe9b7203ec2e56ea6a57c75e6d632eaf9487c7f7978cdad1d801bee0af/google_auth-2.62.0-py3-none-any.whl", hash = "sha256:4ff4319aeb4ad128409759d397a9fcafad126d0031d241cc0dd6b9a00b43e3f3", size = 267911, upload-time = "2026-10-12T19:20:46.355Z" }, ] +[[package]] +name = "h11" +version = "0.16.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/01/ee/02a2c011bdab74c6fb3c75474d40b3052059d95df7e73351460c8588d963/h11-0.16.0.tar.gz", hash = "sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1", size = 101250, upload-time = "2025-04-24T03:35:25.427Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86", size = 37515, upload-time = "2025-04-24T03:35:24.344Z" }, +] + +[[package]] +name = "httpcore" +version = "1.0.9" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "certifi" }, + { name = "h11" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/06/94/82699a10bca87a5556c9c59b5963f2d039dbd239f25bc2a63907a05a14cb/httpcore-1.0.9.tar.gz", hash = "sha256:6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8", size = 85484, upload-time = "2025-04-24T22:06:22.219Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7e/f5/f66802a942d491edb555dd61e3a9961140fd64c90bce1eafd741609d334d/httpcore-1.0.9-py3-none-any.whl", hash = "sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55", size = 78784, upload-time = "2025-04-24T22:06:20.566Z" }, +] + +[[package]] +name = "httpx" +version = "0.28.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, + { name = "certifi" }, + { name = "httpcore" }, + { name = "idna" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b1/df/48c586a5fe32a0f01324ee087459e112ebb7224f646c0b5023f5e79e9956/httpx-0.28.1.tar.gz", hash = "sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc", size = 141406, upload-time = "2024-12-06T15:37:23.222Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2a/39/e50c7c3a983047577ee07d2a9e53faf5a69493943ec3f6a384bdc792deb2/httpx-0.28.1-py3-none-any.whl", hash = "sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad", size = 73517, upload-time = "2024-12-06T15:37:21.509Z" }, +] + [[package]] name = "idna" version = "3.20" @@ -503,9 +549,11 @@ dependencies = [ test = [ { name = "fastapi" }, { name = "google-auth" }, + { name = "httpx" }, { name = "itsdangerous" }, { name = "pytest" }, { name = "pytest-asyncio" }, + { name = "redis" }, { name = "requests" }, ] @@ -513,10 +561,12 @@ test = [ requires-dist = [ { name = "fastapi", marker = "extra == 'test'" }, { name = "google-auth", marker = "extra == 'test'" }, + { name = "httpx", marker = "extra == 'test'", specifier = "==0.28.1" }, { name = "itsdangerous", marker = "extra == 'test'" }, { name = "pydantic" }, { name = "pytest", marker = "extra == 'test'" }, { name = "pytest-asyncio", marker = "extra == 'test'" }, + { name = "redis", marker = "extra == 'test'", specifier = "==8.0.1" }, { name = "requests", marker = "extra == 'test'" }, ] provides-extras = ["test"] @@ -772,6 +822,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/03/e2/08a497ef684b88559c9cc5f4ad53a37e7b99e727094a86d6ea32536d5d3c/pytest_asyncio-1.4.0-py3-none-any.whl", hash = "sha256:933ca923a23075a87fb7070c0ec272a6848489824d887c85c812670932835aa1", size = 16930, upload-time = "2026-05-26T09:56:02.576Z" }, ] +[[package]] +name = "redis" +version = "8.0.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "async-timeout", marker = "python_full_version < '3.11.3'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/cc/c3/928b290c2c0ca99ab96eea5b4ff8f30be8112b075301a7d3ba214a3c8c12/redis-8.0.1.tar.gz", hash = "sha256:afc5a7a2f5a084f5b1880dec548dd45be17db7e43c82a30d84f952aefb05cfb0", size = 5114170, upload-time = "2026-06-23T14:52:37.728Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fd/0a/c2345ebf1ebe70840ce3f6c6ee612f8fa749cfbd1b03069c53bf0c62aaad/redis-8.0.1-py3-none-any.whl", hash = "sha256:47daa35a058c23468d6437f17a8c76882cb316b838ef763036af99b96cedd743", size = 502406, upload-time = "2026-06-23T14:52:36.137Z" }, +] + [[package]] name = "requests" version = "2.34.2"